Beispiel #1
0
/**
 * xmlSecNssGetInternalKeySlot:
 *
 * Gets internal NSS key slot.
 *
 * Returns: internal key slot and initializes it if needed.
 */
PK11SlotInfo *
xmlSecNssGetInternalKeySlot()
{
    PK11SlotInfo *slot = NULL;
    SECStatus rv;

    slot = PK11_GetInternalKeySlot();
    if (slot == NULL) {
        xmlSecNssError("PK11_GetInternalKeySlot", NULL);
        return NULL;
    }

    if (PK11_NeedUserInit(slot)) {
        rv = PK11_InitPin(slot, NULL, NULL);
        if (rv != SECSuccess) {
            xmlSecNssError("PK11_InitPin", NULL);
            return NULL;
        }
    }

    if(PK11_IsLoggedIn(slot, NULL) != PR_TRUE) {
        rv = PK11_Authenticate(slot, PR_TRUE, NULL);
        if (rv != SECSuccess) {
            xmlSecNssError2("PK11_Authenticate", NULL,
                            "token=%s", xmlSecErrorsSafeString(PK11_GetTokenName(slot)));
            return NULL;
        }
    }

    return(slot);
}
Beispiel #2
0
/************************************************************************
 *
 * I n i t P W
 */
Error
InitPW(void)
{
    PK11SlotInfo *slot;
    Error ret = UNSPECIFIED_ERR;

    slot = PK11_GetInternalKeySlot();
    if (!slot) {
        PR_fprintf(PR_STDERR, errStrings[NO_SUCH_TOKEN_ERR], "internal");
        return NO_SUCH_TOKEN_ERR;
    }

    /* Set the initial password to empty */
    if (PK11_NeedUserInit(slot)) {
        if (PK11_InitPin(slot, NULL, "") != SECSuccess) {
            PR_fprintf(PR_STDERR, errStrings[INITPW_FAILED_ERR]);
            ret = INITPW_FAILED_ERR;
            goto loser;
        }
    }

    ret = SUCCESS;

loser:
    PK11_FreeSlot(slot);

    return ret;
}
Beispiel #3
0
NS_IMETHODIMP nsPK11Token::InitPassword(const char16_t *initialPassword)
{
  nsNSSShutDownPreventionLock locker;
  if (isAlreadyShutDown())
    return NS_ERROR_NOT_AVAILABLE;

    nsresult rv = NS_OK;
    SECStatus status;

    NS_ConvertUTF16toUTF8 aUtf8InitialPassword(initialPassword);
    status = PK11_InitPin(mSlot, "", const_cast<char*>(aUtf8InitialPassword.get()));
    if (status == SECFailure) { rv = NS_ERROR_FAILURE; goto done; }

done:
    return rv;
}
Beispiel #4
0
NS_IMETHODIMP
nsPK11Token::InitPassword(const nsACString& initialPassword)
{
  const nsCString& passwordCStr = PromiseFlatCString(initialPassword);
  // PSM initializes the sqlite-backed softoken with an empty password. The
  // implementation considers this not to be a password (GetHasPassword returns
  // false), but we can't actually call PK11_InitPin again. Instead, we call
  // PK11_ChangePW with the empty password.
  bool hasPassword;
  nsresult rv = GetHasPassword(&hasPassword);
  if (NS_FAILED(rv)) {
    return rv;
  }
  if (!PK11_NeedUserInit(mSlot.get()) && !hasPassword) {
    return MapSECStatus(PK11_ChangePW(mSlot.get(), "", passwordCStr.get()));
  }
  return MapSECStatus(PK11_InitPin(mSlot.get(), "", passwordCStr.get()));
}
nsresult
LocalCertService::LoginToKeySlot()
{
  nsresult rv;

  // Get access to key slot
  UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
  if (!slot) {
    return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
  }

  // If no user password yet, set it an empty one
  if (PK11_NeedUserInit(slot.get())) {
    rv = MapSECStatus(PK11_InitPin(slot.get(), "", ""));
    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  // If user has a password set, prompt to login
  if (PK11_NeedLogin(slot.get()) && !PK11_IsLoggedIn(slot.get(), nullptr)) {
    // Switching to XPCOM to get the UI prompt that PSM owns
    nsCOMPtr<nsIPK11TokenDB> tokenDB =
      do_GetService(NS_PK11TOKENDB_CONTRACTID);
    if (!tokenDB) {
      return NS_ERROR_FAILURE;
    }
    nsCOMPtr<nsIPK11Token> keyToken;
    tokenDB->GetInternalKeyToken(getter_AddRefs(keyToken));
    if (!keyToken) {
      return NS_ERROR_FAILURE;
    }
    // Prompt the user to login
    return keyToken->Login(false /* force */);
  }

  return NS_OK;
}
NS_IMETHODIMP
LocalCertService::GetLoginPromptRequired(bool* aRequired)
{
  nsresult rv;

  // Get access to key slot
  UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
  if (!slot) {
    return mozilla::psm::GetXPCOMFromNSSError(PR_GetError());
  }

  // If no user password yet, set it an empty one
  if (PK11_NeedUserInit(slot.get())) {
    rv = MapSECStatus(PK11_InitPin(slot.get(), "", ""));
    if (NS_FAILED(rv)) {
      return rv;
    }
  }

  *aRequired = PK11_NeedLogin(slot.get()) &&
               !PK11_IsLoggedIn(slot.get(), nullptr);
  return NS_OK;
}
Beispiel #7
0
  bool nss_change_password(PK11SlotInfo* slot, const char* oldpass, const char* newpass) {
    SECStatus rv;
    const char *oldpw = NULL, *newpw = NULL;
    oldpw = oldpass; newpw = newpass;

    if (PK11_NeedUserInit(slot)) {
      rv = PK11_InitPin(slot, (char*)NULL, (char*)newpw);
      return true;
    }

    if (PK11_CheckUserPassword(slot, (char*)oldpw) != SECSuccess) {
      std::cerr<<"Invalid password to nss db"<<std::endl;
      return false;
    }

    if (PK11_ChangePW(slot, (char*)oldpw, (char*)newpw) != SECSuccess) {
      std::cerr<<"Failed to change password of nss db"<<std::endl;
      return false;
    }

    std::cout<<"Succeeded to change password"<<std::endl;

    return true;
  }
Beispiel #8
0
SECStatus
AddKeyFromFile(const char* basePath, const char* filename)
{
  const char* PRIVATE_KEY_HEADER = "-----BEGIN PRIVATE KEY-----";
  const char* PRIVATE_KEY_FOOTER = "-----END PRIVATE KEY-----";

  char buf[16384] = { 0 };
  SECStatus rv = ReadFileToBuffer(basePath, filename, buf);
  if (rv != SECSuccess) {
    return rv;
  }
  if (strncmp(buf, PRIVATE_KEY_HEADER, strlen(PRIVATE_KEY_HEADER)) != 0) {
    PR_fprintf(PR_STDERR, "invalid key - not importing\n");
    return SECFailure;
  }
  const char* bufPtr = buf + strlen(PRIVATE_KEY_HEADER);
  size_t bufLen = strlen(buf);
  char base64[16384] = { 0 };
  char* base64Ptr = base64;
  while (bufPtr < buf + bufLen) {
    if (strncmp(bufPtr, PRIVATE_KEY_FOOTER, strlen(PRIVATE_KEY_FOOTER)) == 0) {
      break;
    }
    if (*bufPtr != '\r' && *bufPtr != '\n') {
      *base64Ptr = *bufPtr;
      base64Ptr++;
    }
    bufPtr++;
  }

  unsigned int binLength;
  UniquePORTString bin(
    reinterpret_cast<char*>(ATOB_AsciiToData(base64, &binLength)));
  if (!bin || binLength == 0) {
    PrintPRError("ATOB_AsciiToData failed");
    return SECFailure;
  }
  ScopedSECItem secitem(::SECITEM_AllocItem(nullptr, nullptr, binLength));
  if (!secitem) {
    PrintPRError("SECITEM_AllocItem failed");
    return SECFailure;
  }
  PORT_Memcpy(secitem->data, bin.get(), binLength);
  ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
  if (!slot) {
    PrintPRError("PK11_GetInternalKeySlot failed");
    return SECFailure;
  }
  if (PK11_NeedUserInit(slot)) {
    if (PK11_InitPin(slot, nullptr, nullptr) != SECSuccess) {
      PrintPRError("PK11_InitPin failed");
      return SECFailure;
    }
  }
  SECKEYPrivateKey* privateKey;
  if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, secitem, nullptr, nullptr,
                                               true, false, KU_ALL,
                                               &privateKey, nullptr)
        != SECSuccess) {
    PrintPRError("PK11_ImportDERPrivateKeyInfoAndReturnKey failed");
    return SECFailure;
  }
  SECKEY_DestroyPrivateKey(privateKey);
  return SECSuccess;
}
Beispiel #9
0
/************************************************************************
 *
 * C h a n g e P W
 */
Error
ChangePW(char *tokenName, char *pwFile, char *newpwFile)
{
    char *oldpw = NULL, *newpw = NULL, *newpw2 = NULL;
    PK11SlotInfo *slot;
    Error ret = UNSPECIFIED_ERR;
    PRBool matching;

    slot = PK11_FindSlotByName(tokenName);
    if (!slot) {
        PR_fprintf(PR_STDERR, errStrings[NO_SUCH_TOKEN_ERR], tokenName);
        return NO_SUCH_TOKEN_ERR;
    }

    /* Get old password */
    if (!PK11_NeedUserInit(slot)) {
        if (pwFile) {
            oldpw = SECU_FilePasswd(NULL, PR_FALSE, pwFile);
            if (PK11_CheckUserPassword(slot, oldpw) != SECSuccess) {
                PR_fprintf(PR_STDERR, errStrings[BAD_PW_ERR]);
                ret = BAD_PW_ERR;
                goto loser;
            }
        } else if (PK11_NeedLogin(slot)) {
            for (matching = PR_FALSE; !matching;) {
                oldpw = SECU_GetPasswordString(NULL, "Enter old password: "******"Enter new password: "******"Re-enter new password: ");
            if (strcmp(newpw, newpw2)) {
                PR_fprintf(PR_STDOUT, msgStrings[PW_MATCH_MSG]);
                PORT_ZFree(newpw, strlen(newpw));
                PORT_ZFree(newpw2, strlen(newpw2));
            } else {
                matching = PR_TRUE;
            }
        }
    }

    /* Change the password */
    if (PK11_NeedUserInit(slot)) {
        if (PK11_InitPin(slot, NULL /*ssopw*/, newpw) != SECSuccess) {
            PR_fprintf(PR_STDERR, errStrings[CHANGEPW_FAILED_ERR], tokenName);
            ret = CHANGEPW_FAILED_ERR;
            goto loser;
        }
    } else {
        if (PK11_ChangePW(slot, oldpw, newpw) != SECSuccess) {
            PR_fprintf(PR_STDERR, errStrings[CHANGEPW_FAILED_ERR], tokenName);
            ret = CHANGEPW_FAILED_ERR;
            goto loser;
        }
    }

    PR_fprintf(PR_STDOUT, msgStrings[CHANGEPW_SUCCESS_MSG], tokenName);
    ret = SUCCESS;

loser:
    if (oldpw) {
        PORT_ZFree(oldpw, strlen(oldpw));
    }
    if (newpw) {
        PORT_ZFree(newpw, strlen(newpw));
    }
    if (newpw2) {
        PORT_ZFree(newpw2, strlen(newpw2));
    }
    PK11_FreeSlot(slot);

    return ret;
}
Beispiel #10
0
int
main(int argc, char **argv)
{
    PLOptState *optstate;
    PLOptStatus optstatus;

    PRUint32 flags = 0;
    Error ret;
    SECStatus rv;
    char *dbString = NULL;
    PRBool doInitTest = PR_FALSE;
    int i;

    progName = strrchr(argv[0], '/');
    if (!progName)
        progName = strrchr(argv[0], '\\');
    progName = progName ? progName + 1 : argv[0];

    optstate = PL_CreateOptState(argc, argv, "rfip:d:h");

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
        switch (optstate->option) {
            case 'h':
            default:
                Usage(progName);
                break;

            case 'r':
                flags |= NSS_INIT_READONLY;
                break;

            case 'f':
                flags |= NSS_INIT_FORCEOPEN;
                break;

            case 'i':
                doInitTest = PR_TRUE;
                break;

            case 'p':
                userPassword = PORT_Strdup(optstate->value);
                break;

            case 'd':
                dbDir = PORT_Strdup(optstate->value);
                break;
        }
    }
    if (optstatus == PL_OPT_BAD)
        Usage(progName);

    if (!dbDir) {
        dbDir = SECU_DefaultSSLDir(); /* Look in $SSL_DIR */
    }
    dbDir = SECU_ConfigDirectory(dbDir);
    PR_fprintf(PR_STDERR, "dbdir selected is %s\n\n", dbDir);

    if (dbDir[0] == '\0') {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dbDir);
        ret = DIR_DOESNT_EXIST_ERR;
        goto loser;
    }

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

    /* get the status of the directory and databases and output message */
    if (PR_Access(dbDir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dbDir);
    } else if (PR_Access(dbDir, PR_ACCESS_READ_OK) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_NOT_READABLE_ERR], dbDir);
    } else {
        if (!(flags & NSS_INIT_READONLY) &&
            PR_Access(dbDir, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[DIR_NOT_WRITEABLE_ERR], dbDir);
        }
        if (!doInitTest) {
            for (i = 0; i < 3; i++) {
                dbString = PR_smprintf("%s/%s", dbDir, dbName[i]);
                PR_fprintf(PR_STDOUT, "database checked is %s\n", dbString);
                if (PR_Access(dbString, PR_ACCESS_EXISTS) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_DOESNT_EXIST_ERR],
                               dbString);
                } else if (PR_Access(dbString, PR_ACCESS_READ_OK) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_NOT_READABLE_ERR],
                               dbString);
                } else if (!(flags & NSS_INIT_READONLY) &&
                           PR_Access(dbString, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
                    PR_fprintf(PR_STDERR, errStrings[FILE_NOT_WRITEABLE_ERR],
                               dbString);
                }
            }
        }
    }

    rv = NSS_Initialize(SECU_ConfigDirectory(dbDir), dbprefix, dbprefix,
                        secmodName, flags);
    if (rv != SECSuccess) {
        SECU_PrintPRandOSError(progName);
        ret = NSS_INITIALIZE_FAILED_ERR;
    } else {
        ret = SUCCESS;
        if (doInitTest) {
            PK11SlotInfo *slot = PK11_GetInternalKeySlot();
            SECStatus rv;
            int passwordSuccess = 0;
            int type = CKM_DES3_CBC;
            SECItem keyid = { 0, NULL, 0 };
            unsigned char keyIdData[] = { 0xff, 0xfe };
            PK11SymKey *key = NULL;

            keyid.data = keyIdData;
            keyid.len = sizeof(keyIdData);

            PK11_SetPasswordFunc(getPassword);
            rv = PK11_InitPin(slot, (char *)NULL, userPassword);
            if (rv != SECSuccess) {
                PR_fprintf(PR_STDERR, "Failed to Init DB: %s\n",
                           SECU_Strerror(PORT_GetError()));
                ret = CHANGEPW_FAILED_ERR;
            }
            if (*userPassword && !PK11_IsLoggedIn(slot, &passwordSuccess)) {
                PR_fprintf(PR_STDERR, "New DB did not log in after init\n");
                ret = AUTHENTICATION_FAILED_ERR;
            }
            /* generate a symetric key */
            key = PK11_TokenKeyGen(slot, type, NULL, 0, &keyid,
                                   PR_TRUE, &passwordSuccess);

            if (!key) {
                PR_fprintf(PR_STDERR, "Could not generated symetric key: %s\n",
                           SECU_Strerror(PORT_GetError()));
                exit(UNSPECIFIED_ERR);
            }
            PK11_FreeSymKey(key);
            PK11_Logout(slot);

            PK11_Authenticate(slot, PR_TRUE, &passwordSuccess);

            if (*userPassword && !passwordSuccess) {
                PR_fprintf(PR_STDERR, "New DB Did not initalize\n");
                ret = AUTHENTICATION_FAILED_ERR;
            }
            key = PK11_FindFixedKey(slot, type, &keyid, &passwordSuccess);

            if (!key) {
                PR_fprintf(PR_STDERR, "Could not find generated key: %s\n",
                           SECU_Strerror(PORT_GetError()));
                ret = UNSPECIFIED_ERR;
            } else {
                PK11_FreeSymKey(key);
            }
            PK11_FreeSlot(slot);
        }

        if (NSS_Shutdown() != SECSuccess) {
            PR_fprintf(PR_STDERR, "Could not find generated key: %s\n",
                       SECU_Strerror(PORT_GetError()));
            exit(1);
        }
    }

loser:
    return ret;
}