SECStatus parseGroupList(const char *arg, SSLNamedGroup **enabledGroups, unsigned int *enabledGroupsCount) { SSLNamedGroup *groups; char *str; char *p; unsigned int numValues = 0; unsigned int count = 0; /* Count the number of groups. */ str = PORT_Strdup(arg); if (!str) { return SECFailure; } p = strtok(str, ","); while (p) { ++numValues; p = strtok(NULL, ","); } PORT_Free(str); str = NULL; groups = PORT_ZNewArray(SSLNamedGroup, numValues); if (!groups) { goto done; } /* Get group names. */ str = PORT_Strdup(arg); if (!str) { goto done; } p = strtok(str, ","); while (p) { SSLNamedGroup group = groupNameToNamedGroup(p); if (group == ssl_grp_none) { count = 0; goto done; } groups[count++] = group; p = strtok(NULL, ","); } done: if (str) { PORT_Free(str); } if (!count) { PORT_Free(groups); return SECFailure; } *enabledGroupsCount = count; *enabledGroups = groups; return SECSuccess; }
/* ** Convert a der-encoded integer to a hex printable string form */ char *CERT_Hexify (SECItem *i, int do_colon) { unsigned char *cp, *end; char *rv, *o; if (!i->len) { return PORT_Strdup("00"); } rv = o = (char*) PORT_Alloc(i->len * 3); if (!rv) return rv; cp = i->data; end = cp + i->len; while (cp < end) { unsigned char ch = *cp++; *o++ = hex[(ch >> 4) & 0xf]; *o++ = hex[ch & 0xf]; if (cp != end) { if (do_colon) { *o++ = ':'; } } } *o = 0; /* Null terminate the string */ return rv; }
static char * lg_keydb_name_cb(void *arg, int dbVersion) { const char *configdir = (const char *)arg; const char *dbver; char *smpname = NULL; char *dbname = NULL; switch (dbVersion) { case 4: dbver = "4"; break; case 3: dbver = "3"; break; case 1: dbver = "1"; break; case 2: default: dbver = ""; break; } smpname = PR_smprintf(KEY_DB_FMT, configdir, dbver); if (smpname) { dbname = PORT_Strdup(smpname); PR_smprintf_free(smpname); } return dbname; }
/* * Allow the application to pass the url or hostname into the SSL library * so that we can do some checking on it. It will be used for the value in * SNI extension of client hello message. */ SECStatus SSL_SetURL(PRFileDesc *fd, const char *url) { sslSocket * ss = ssl_FindSocket(fd); SECStatus rv = SECSuccess; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL", SSL_GETPID(), fd)); return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); if ( ss->url ) { PORT_Free((void *)ss->url); /* CONST */ } ss->url = (const char *)PORT_Strdup(url); if ( ss->url == NULL ) { rv = SECFailure; } ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); return rv; }
/* * this is a legacy configuration function which used to be part of * the PKCS #11 internal token. */ void PK11_ConfigurePKCS11(const char *man, const char *libdesc, const char *tokdesc, const char *ptokdesc, const char *slotdesc, const char *pslotdesc, const char *fslotdesc, const char *fpslotdesc, int minPwd, int pwRequired) { char * strings; strings = nss_MkConfigString(man,libdesc,tokdesc,ptokdesc,slotdesc, pslotdesc,fslotdesc,fpslotdesc,minPwd); if (strings == NULL) { return; } if (libdesc) { if (pk11_config_name != NULL) { PORT_Free(pk11_config_name); } pk11_config_name = PORT_Strdup(libdesc); } if (pk11_config_strings != NULL) { PR_smprintf_free(pk11_config_strings); } pk11_config_strings = strings; pk11_password_required = pwRequired; return; }
/* * J A R _ f i n d * * Establish the search pattern for use * by JAR_find_next, to traverse the filenames * or certificates in the JAR structure. * * See jar.h for a description on how to use. * */ JAR_Context * JAR_find(JAR *jar, char *pattern, jarType type) { JAR_Context *ctx; PORT_Assert(jar != NULL); if (!jar) return NULL; ctx = (JAR_Context *)PORT_ZAlloc(sizeof(JAR_Context)); if (ctx == NULL) return NULL; ctx->jar = jar; if (pattern) { if ((ctx->pattern = PORT_Strdup(pattern)) == NULL) { PORT_Free(ctx); return NULL; } } ctx->finding = type; switch (type) { case jarTypeMF: ctx->next = ZZ_ListHead(jar->hashes); break; case jarTypeSF: case jarTypeSign: ctx->next = NULL; ctx->nextsign = ZZ_ListHead(jar->signers); break; case jarTypeSect: ctx->next = ZZ_ListHead(jar->manifest); break; case jarTypePhy: ctx->next = ZZ_ListHead(jar->phy); break; case jarTypeOwner: if (jar->signers) ctx->next = ZZ_ListHead(jar->signers); else ctx->next = NULL; break; case jarTypeMeta: ctx->next = ZZ_ListHead(jar->metainfo); break; default: PORT_Assert(1 != 2); break; } return ctx; }
static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg) { (void)slot; /* unused */ if(retry || NULL == arg) return NULL; else return (char *)PORT_Strdup((char *)arg); }
/* Unrecoverable error */ exitErr("Unable to connect to server", errCode); } #if 0 /* No client authorization */ static char * myPasswd(PK11SlotInfo *info, PRBool retry, void *arg) { char * passwd = NULL; if ( (!retry) && arg ) passwd = PORT_Strdup((char *)arg); return passwd; }
static char * getPassword(PK11SlotInfo *slot, PRBool retry, void *arg) { int *success = (int *)arg; if (retry) { *success = 0; return NULL; } *success = 1; return PORT_Strdup(userPassword); }
/* * NSS_CMSSignerInfo_GetSignerEmailAddress - return the common name of the signer * * sinfo - signerInfo data for this signer * * Returns a pointer to allocated memory, which must be freed. * A return value of NULL is an error. */ char * NSS_CMSSignerInfo_GetSignerEmailAddress(NSSCMSSignerInfo *sinfo) { CERTCertificate *signercert; if ((signercert = NSS_CMSSignerInfo_GetSigningCertificate(sinfo, NULL)) == NULL) return NULL; if (!signercert->emailAddr || !signercert->emailAddr[0]) return NULL; return (PORT_Strdup(signercert->emailAddr)); }
static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg) { pphrase_arg_t *parg; parg = (pphrase_arg_t *) arg; (void)slot; /* unused */ if(retry > 2) return NULL; if(parg->data->set.str[STRING_KEY_PASSWD]) return (char *)PORT_Strdup((char *)parg->data->set.str[STRING_KEY_PASSWD]); else return NULL; }
/* * NSS needs the app to supply a password prompt. In our case the only time * the password is supplied is as part of the Login APDU. The actual password * is passed in the pw_arg in that case. In all other cases pw_arg should be * NULL. */ static char * vcard_emul_get_password(PK11SlotInfo *slot, PRBool retries, void *pw_arg) { /* if it didn't work the first time, don't keep trying */ if (retries) { return NULL; } /* we are looking up a password when we don't have one in hand */ if (pw_arg == NULL) { return NULL; } /* TODO: we really should verify that were are using the right slot */ return PORT_Strdup(pw_arg); }
char* nss_get_password_from_console(PK11SlotInfo* slot, PRBool retry, void *arg) { char prompt[255]; char* pw = NULL; if(arg != NULL) pw = (char *)PORT_Strdup((char *)arg); if(pw != NULL) return pw; sprintf(prompt, "Enter Password or Pin for \"%s\":", PK11_GetTokenName(slot)); return getPasswordString(NULL, prompt); std::cerr<<"Password check failed: No password found."<<std::endl; return NULL; }
char *SEC_GetPassword(FILE *input, FILE *output, char *prompt, PRBool (*ok)(char *)) { #if defined(_WINDOWS) int isTTY = (input == stdin); #define echoOn(x) #define echoOff(x) #else int infd = fileno(input); int isTTY = isatty(infd); #endif char phrase[200] = {'\0'}; /* ensure EOF doesn't return junk */ for (;;) { /* Prompt for password */ if (isTTY) { fprintf(output, "%s", prompt); fflush (output); echoOff(infd); } QUIET_FGETS ( phrase, sizeof(phrase), input); if (isTTY) { fprintf(output, "\n"); echoOn(infd); } /* stomp on newline */ phrase[PORT_Strlen(phrase)-1] = 0; /* Validate password */ if (!(*ok)(phrase)) { /* Not weird enough */ if (!isTTY) return 0; fprintf(output, "Password must be at least 8 characters long with one or more\n"); fprintf(output, "non-alphabetic characters\n"); continue; } return (char*) PORT_Strdup(phrase); } }
static char * nss_doubleEscape(const char *string) { char *round1 = NULL; char *retValue = NULL; if (string == NULL) { goto done; } round1 = nss_addEscape(string,'\''); if (round1) { retValue = nss_addEscape(round1,'"'); PORT_Free(round1); } done: if (retValue == NULL) { retValue = PORT_Strdup(""); } return retValue; }
char * NSSUTIL_DoubleEscape(const char *string, char quote1, char quote2) { char *round1 = NULL; char *retValue = NULL; if (string == NULL) { goto done; } round1 = nssutil_escapeQuotes(string, quote1, PR_FALSE); if (round1) { retValue = nssutil_escapeQuotes(round1, quote2, PR_FALSE); PORT_Free(round1); } done: if (retValue == NULL) { retValue = PORT_Strdup(""); } return retValue; }
static char *_NSSUTIL_GetOldSecmodName(const char *dbname,const char *filename) { char *file = NULL; char *dirPath = PORT_Strdup(dbname); char *sep; sep = PORT_Strrchr(dirPath,*NSSUTIL_PATH_SEPARATOR); #ifdef WINDOWS if (!sep) { sep = PORT_Strrchr(dirPath,'\\'); } #endif if (sep) { *(sep)=0; } file= PR_smprintf("%s"NSSUTIL_PATH_SEPARATOR"%s", dirPath, filename); PORT_Free(dirPath); return file; }
/* * Secret keys must have a CKA_ID value to be stored in the database. This code * will generate one if there wasn't one already. */ static CK_RV lg_GenerateSecretCKA_ID(NSSLOWKEYDBHandle *handle, SECItem *id, char *label) { unsigned int retries; SECStatus rv = SECSuccess; CK_RV crv = CKR_OK; id->data = NULL; if (label) { id->data = (unsigned char *)PORT_Strdup(label); if (id->data == NULL) { return CKR_HOST_MEMORY; } id->len = PORT_Strlen(label) + 1; if (!nsslowkey_KeyForIDExists(handle, id)) { return CKR_OK; } PORT_Free(id->data); id->data = NULL; id->len = 0; } id->data = (unsigned char *)PORT_Alloc(LG_KEY_ID_SIZE); if (id->data == NULL) { return CKR_HOST_MEMORY; } id->len = LG_KEY_ID_SIZE; retries = 0; do { rv = RNG_GenerateGlobalRandomBytes(id->data, id->len); } while (rv == SECSuccess && nsslowkey_KeyForIDExists(handle, id) && (++retries <= LG_KEY_MAX_RETRIES)); if ((rv != SECSuccess) || (retries > LG_KEY_MAX_RETRIES)) { crv = CKR_DEVICE_ERROR; /* random number generator is bad */ PORT_Free(id->data); id->data = NULL; id->len = 0; } return crv; }
char * GetPasswordString(void *arg, char *prompt) { FILE *input = stdin; char phrase[200] = {'\0'}; int isInputTerminal = isatty(fileno(stdin)); #ifndef _WINDOWS if (isInputTerminal) { input = fopen(consoleName, "r"); if (input == NULL) { fprintf(stderr, "Error opening input terminal for read\n"); return NULL; } } #endif if (isInputTerminal) { fprintf(stdout, "Please enter your password:\n"); fflush(stdout); } QUIET_FGETS (phrase, sizeof(phrase), input); if (isInputTerminal) { fprintf(stdout, "\n"); } #ifndef _WINDOWS if (isInputTerminal) { fclose(input); } #endif /* Strip off the newlines if present */ if (phrase[PORT_Strlen(phrase)-1] == '\n' || phrase[PORT_Strlen(phrase)-1] == '\r') { phrase[PORT_Strlen(phrase)-1] = 0; } return (char*) PORT_Strdup(phrase); }
int JAR_get_metainfo(JAR *jar, char *name, char *header, void **info, unsigned long *length) { JAR_Item *it; ZZLink *link; ZZList *list; PORT_Assert(jar != NULL && header != NULL); if (jar == NULL || header == NULL) return JAR_ERR_PNF; list = jar->metainfo; if (ZZ_ListEmpty(list)) return JAR_ERR_PNF; for (link = ZZ_ListHead(list); !ZZ_ListIterDone(list, link); link = link->next) { it = link->thing; if (it->type == jarTypeMeta) { JAR_Metainfo *met; if ((name && !it->pathname) || (!name && it->pathname)) continue; if (name && it->pathname && strcmp(it->pathname, name)) continue; met = (JAR_Metainfo *)it->data; if (!PORT_Strcasecmp(met->header, header)) { *info = PORT_Strdup(met->info); *length = PORT_Strlen(met->info); return 0; } } } return JAR_ERR_PNF; }
const char * lg_EvaluateConfigDir(const char *configdir,char **appName) { if (PORT_Strncmp(configdir, MULTIACCESS, sizeof(MULTIACCESS)-1) == 0) { char *cdir; *appName = PORT_Strdup(configdir+sizeof(MULTIACCESS)-1); if (*appName == NULL) { return configdir; } cdir = *appName; while (*cdir && *cdir != ':') { cdir++; } if (*cdir == ':') { *cdir = 0; cdir++; } configdir = cdir; } return configdir; }
static char *sftk_getOldSecmodName(const char *dbname,const char *filename) { char *file = NULL; char *dirPath = PORT_Strdup(dbname); char *sep; sep = PORT_Strrchr(dirPath,*PATH_SEPARATOR); #ifdef _WIN32 if (!sep) { /* pkcs11i.h defines PATH_SEPARATOR as "/" for all platforms. */ sep = PORT_Strrchr(dirPath,'\\'); } #endif if (sep) { *sep = 0; file = PR_smprintf("%s"PATH_SEPARATOR"%s", dirPath, filename); } else { file = PR_smprintf("%s", filename); } PORT_Free(dirPath); return file; }
static char * lg_certdb_name_cb(void *arg, int dbVersion) { const char *configdir = (const char *)arg; const char *dbver; char *smpname = NULL; char *dbname = NULL; switch (dbVersion) { case 8: dbver = "8"; break; case 7: dbver = "7"; break; case 6: dbver = "6"; break; case 5: dbver = "5"; break; case 4: default: dbver = ""; break; } /* make sure we return something allocated with PORT_ so we have properly * matched frees at the end */ smpname = PR_smprintf(CERT_DB_FMT, configdir, dbver); if (smpname) { dbname = PORT_Strdup(smpname); PR_smprintf_free(smpname); } return dbname; }
/* * return the crl associated with a derSubjectName */ SECItem * PK11_FindCrlByName(PK11SlotInfo **slot, CK_OBJECT_HANDLE *crlHandle, SECItem *name, int type, char **pUrl) { NSSCRL **crls, **crlp, *crl = NULL; NSSDER subject; SECItem *rvItem; NSSTrustDomain *td = STAN_GetDefaultTrustDomain(); char * url = NULL; PORT_SetError(0); NSSITEM_FROM_SECITEM(&subject, name); if (*slot) { nssCryptokiObject **instances; nssPKIObjectCollection *collection; nssTokenSearchType tokenOnly = nssTokenSearchType_TokenOnly; NSSToken *token = PK11Slot_GetNSSToken(*slot); collection = nssCRLCollection_Create(td, NULL); if (!collection) { goto loser; } instances = nssToken_FindCRLsBySubject(token, NULL, &subject, tokenOnly, 0, NULL); nssPKIObjectCollection_AddInstances(collection, instances, 0); nss_ZFreeIf(instances); crls = nssPKIObjectCollection_GetCRLs(collection, NULL, 0, NULL); nssPKIObjectCollection_Destroy(collection); } else { crls = nssTrustDomain_FindCRLsBySubject(td, &subject); } if ((!crls) || (*crls == NULL)) { if (crls) { nssCRLArray_Destroy(crls); } if (NSS_GetError() == NSS_ERROR_NOT_FOUND) { PORT_SetError(SEC_ERROR_CRL_NOT_FOUND); } goto loser; } for (crlp = crls; *crlp; crlp++) { if ((!(*crlp)->isKRL && type == SEC_CRL_TYPE) || ((*crlp)->isKRL && type != SEC_CRL_TYPE)) { crl = nssCRL_AddRef(*crlp); break; } } nssCRLArray_Destroy(crls); if (!crl) { /* CRL collection was found, but no interesting CRL's were on it. * Not an error */ PORT_SetError(SEC_ERROR_CRL_NOT_FOUND); goto loser; } if (crl->url) { url = PORT_Strdup(crl->url); if (!url) { goto loser; } } rvItem = SECITEM_AllocItem(NULL, NULL, crl->encoding.size); if (!rvItem) { goto loser; } memcpy(rvItem->data, crl->encoding.data, crl->encoding.size); *slot = PK11_ReferenceSlot(crl->object.instances[0]->token->pk11slot); *crlHandle = crl->object.instances[0]->handle; *pUrl = url; nssCRL_Destroy(crl); return rvItem; loser: if (url) PORT_Free(url); if (crl) nssCRL_Destroy(crl); if (PORT_GetError() == 0) { PORT_SetError(SEC_ERROR_CRL_NOT_FOUND); } return NULL; }
char * SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg) { char* phrases, *phrase; PRFileDesc *fd; int32_t nb; char *pwFile = arg; int i; const long maxPwdFileSize = 4096; char* tokenName = NULL; int tokenLen = 0; if (!pwFile) return 0; if (retry) { return 0; /* no good retrying - the files contents will be the same */ } phrases = PORT_ZAlloc(maxPwdFileSize); if (!phrases) { return 0; /* out of memory */ } fd = PR_Open(pwFile, PR_RDONLY, 0); if (!fd) { fprintf(stderr, "No password file \"%s\" exists.\n", pwFile); PORT_Free(phrases); return NULL; } nb = PR_Read(fd, phrases, maxPwdFileSize); PR_Close(fd); if (nb == 0) { fprintf(stderr,"password file contains no data\n"); PORT_Free(phrases); return NULL; } if (slot) { tokenName = PK11_GetTokenName(slot); if (tokenName) { tokenLen = PORT_Strlen(tokenName); } } i = 0; do { int startphrase = i; int phraseLen; /* handle the Windows EOL case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any EOL before the start of the next passphrase */ while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) { phrases[i++] = '\0'; } /* now analyze the current passphrase */ phrase = &phrases[startphrase]; if (!tokenName) break; if (PORT_Strncmp(phrase, tokenName, tokenLen)) continue; phraseLen = PORT_Strlen(phrase); if (phraseLen < (tokenLen+1)) continue; if (phrase[tokenLen] != ':') continue; phrase = &phrase[tokenLen+1]; break; } while (i<nb); phrase = PORT_Strdup((char*)phrase); PORT_Free(phrases); return phrase; }
static void ListCRLNames (CERTCertDBHandle *certHandle, int crlType, PRBool deletecrls) { CERTCrlHeadNode *crlList = NULL; CERTCrlNode *crlNode = NULL; CERTName *name = NULL; PLArenaPool *arena = NULL; SECStatus rv; do { arena = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE); if (arena == NULL) { fprintf(stderr, "%s: fail to allocate memory\n", progName); break; } name = PORT_ArenaZAlloc (arena, sizeof(*name)); if (name == NULL) { fprintf(stderr, "%s: fail to allocate memory\n", progName); break; } name->arena = arena; rv = SEC_LookupCrls (certHandle, &crlList, crlType); if (rv != SECSuccess) { fprintf(stderr, "%s: fail to look up CRLs (%s)\n", progName, SECU_Strerror(PORT_GetError())); break; } /* just in case */ if (!crlList) break; crlNode = crlList->first; fprintf (stdout, "\n"); fprintf (stdout, "\n%-40s %-5s\n\n", "CRL names", "CRL Type"); while (crlNode) { char* asciiname = NULL; CERTCertificate *cert = NULL; if (crlNode->crl && &crlNode->crl->crl.derName) { cert = CERT_FindCertByName(certHandle, &crlNode->crl->crl.derName); if (!cert) { SECU_PrintError(progName, "could not find signing " "certificate in database"); } } if (cert) { char* certName = NULL; if (cert->nickname && PORT_Strlen(cert->nickname) > 0) { certName = cert->nickname; } else if (cert->emailAddr && PORT_Strlen(cert->emailAddr) > 0) { certName = cert->emailAddr; } if (certName) { asciiname = PORT_Strdup(certName); } CERT_DestroyCertificate(cert); } if (!asciiname) { name = &crlNode->crl->crl.name; if (!name){ SECU_PrintError(progName, "fail to get the CRL " "issuer name"); continue; } asciiname = CERT_NameToAscii(name); } fprintf (stdout, "%-40s %-5s\n", asciiname, "CRL"); if (asciiname) { PORT_Free(asciiname); } if ( PR_TRUE == deletecrls) { CERTSignedCrl* acrl = NULL; SECItem* issuer = &crlNode->crl->crl.derName; acrl = SEC_FindCrlByName(certHandle, issuer, crlType); if (acrl) { SEC_DeletePermCRL(acrl); SEC_DestroyCrl(acrl); } } crlNode = crlNode->next; } } while (0); if (crlList) PORT_FreeArena (crlList->arena, PR_FALSE); PORT_FreeArena (arena, PR_FALSE); }
/* NEED LOCKS IN HERE. */ SECStatus SSL_SecurityStatus(PRFileDesc *fd, int *op, char **cp, int *kp0, int *kp1, char **ip, char **sp) { sslSocket *ss; const char *cipherName; PRBool isDes = PR_FALSE; ss = ssl_FindSocket(fd); if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in SecurityStatus", SSL_GETPID(), fd)); return SECFailure; } if (cp) *cp = 0; if (kp0) *kp0 = 0; if (kp1) *kp1 = 0; if (ip) *ip = 0; if (sp) *sp = 0; if (op) { *op = SSL_SECURITY_STATUS_OFF; } if (ss->opt.useSecurity && ss->enoughFirstHsDone) { if (ss->version < SSL_LIBRARY_VERSION_3_0) { cipherName = ssl_cipherName[ss->sec.cipherType]; } else { cipherName = ssl3_cipherName[ss->sec.cipherType]; } PORT_Assert(cipherName); if (cipherName) { if (PORT_Strstr(cipherName, "DES")) isDes = PR_TRUE; if (cp) { *cp = PORT_Strdup(cipherName); } } if (kp0) { *kp0 = ss->sec.keyBits; if (isDes) *kp0 = (*kp0 * 7) / 8; } if (kp1) { *kp1 = ss->sec.secretKeyBits; if (isDes) *kp1 = (*kp1 * 7) / 8; } if (op) { if (ss->sec.keyBits == 0) { *op = SSL_SECURITY_STATUS_OFF; } else if (ss->sec.secretKeyBits < 90) { *op = SSL_SECURITY_STATUS_ON_LOW; } else { *op = SSL_SECURITY_STATUS_ON_HIGH; } } if (ip || sp) { CERTCertificate *cert; cert = ss->sec.peerCert; if (cert) { if (ip) { *ip = CERT_NameToAscii(&cert->issuer); } if (sp) { *sp = CERT_NameToAscii(&cert->subject); } } else { if (ip) { *ip = PORT_Strdup("no certificate"); } if (sp) { *sp = PORT_Strdup("no certificate"); } } } } return SECSuccess; }
int main(int argc, char *argv[], char *envp[]) { char * certDir = NULL; char * progName = NULL; char * oidStr = NULL; CERTCertificate * cert; CERTCertificate * firstCert = NULL; CERTCertificate * issuerCert = NULL; CERTCertDBHandle * defaultDB = NULL; PRBool isAscii = PR_FALSE; PRBool trusted = PR_FALSE; SECStatus secStatus; SECCertificateUsage certUsage = certificateUsageSSLServer; PLOptState * optstate; PRTime time = 0; PLOptStatus status; int usePkix = 0; int rv = 1; int usage; CERTVerifyLog log; CERTCertList *builtChain = NULL; PRBool certFetching = PR_FALSE; int revDataIndex = 0; PRBool ocsp_fetchingFailureIsAFailure = PR_TRUE; PRBool useDefaultRevFlags = PR_TRUE; int vfyCounts = 1; PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); progName = PL_strdup(argv[0]); optstate = PL_CreateOptState(argc, argv, "ab:c:d:efg:h:i:m:o:prs:tu:vw:W:"); while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { switch(optstate->option) { case 0 : /* positional parameter */ goto breakout; case 'a' : isAscii = PR_TRUE; break; case 'b' : secStatus = DER_AsciiToTime(&time, optstate->value); if (secStatus != SECSuccess) Usage(progName); break; case 'd' : certDir = PL_strdup(optstate->value); break; case 'e' : ocsp_fetchingFailureIsAFailure = PR_FALSE; break; case 'f' : certFetching = PR_TRUE; break; case 'g' : if (revMethodsData[revDataIndex].testTypeStr || revMethodsData[revDataIndex].methodTypeStr) { revDataIndex += 1; if (revDataIndex == REV_METHOD_INDEX_MAX) { fprintf(stderr, "Invalid revocation configuration" "specified.\n"); secStatus = SECFailure; break; } } useDefaultRevFlags = PR_FALSE; revMethodsData[revDataIndex]. testTypeStr = PL_strdup(optstate->value); break; case 'h' : revMethodsData[revDataIndex]. testFlagsStr = PL_strdup(optstate->value);break; case 'i' : vfyCounts = PORT_Atoi(optstate->value); break; break; case 'm' : if (revMethodsData[revDataIndex].methodTypeStr) { revDataIndex += 1; if (revDataIndex == REV_METHOD_INDEX_MAX) { fprintf(stderr, "Invalid revocation configuration" "specified.\n"); secStatus = SECFailure; break; } } useDefaultRevFlags = PR_FALSE; revMethodsData[revDataIndex]. methodTypeStr = PL_strdup(optstate->value); break; case 'o' : oidStr = PL_strdup(optstate->value); break; case 'p' : usePkix += 1; break; case 'r' : isAscii = PR_FALSE; break; case 's' : revMethodsData[revDataIndex]. methodFlagsStr = PL_strdup(optstate->value); break; case 't' : trusted = PR_TRUE; break; case 'u' : usage = PORT_Atoi(optstate->value); if (usage < 0 || usage > 62) Usage(progName); certUsage = ((SECCertificateUsage)1) << usage; if (certUsage > certificateUsageHighest) Usage(progName); break; case 'w': pwdata.source = PW_PLAINTEXT; pwdata.data = PORT_Strdup(optstate->value); break; case 'W': pwdata.source = PW_FROMFILE; pwdata.data = PORT_Strdup(optstate->value); break; case 'v' : verbose++; break; default : Usage(progName); break; } } breakout: if (status != PL_OPT_OK) Usage(progName); if (usePkix < 2) { if (oidStr) { fprintf(stderr, "Policy oid(-o) can be used only with" " CERT_PKIXVerifyChain(-pp) function.\n"); Usage(progName); } if (trusted) { fprintf(stderr, "Cert trust flag can be used only with" " CERT_PKIXVerifyChain(-pp) function.\n"); Usage(progName); } } if (!useDefaultRevFlags && parseRevMethodsAndFlags()) { fprintf(stderr, "Invalid revocation configuration specified.\n"); goto punt; } /* Set our password function callback. */ PK11_SetPasswordFunc(SECU_GetModulePassword); /* Initialize the NSS libraries. */ if (certDir) { secStatus = NSS_Init(certDir); } else { secStatus = NSS_NoDB_Init(NULL); /* load the builtins */ SECMOD_AddNewModule("Builtins", DLL_PREFIX"nssckbi."DLL_SUFFIX, 0, 0); } if (secStatus != SECSuccess) { exitErr("NSS_Init"); } SECU_RegisterDynamicOids(); if (isOCSPEnabled()) { CERT_EnableOCSPChecking(CERT_GetDefaultCertDB()); CERT_DisableOCSPDefaultResponder(CERT_GetDefaultCertDB()); if (!ocsp_fetchingFailureIsAFailure) { CERT_SetOCSPFailureMode(ocspMode_FailureIsNotAVerificationFailure); } } while (status == PL_OPT_OK) { switch(optstate->option) { default : Usage(progName); break; case 'a' : isAscii = PR_TRUE; break; case 'r' : isAscii = PR_FALSE; break; case 't' : trusted = PR_TRUE; break; case 0 : /* positional parameter */ if (usePkix < 2 && trusted) { fprintf(stderr, "Cert trust flag can be used only with" " CERT_PKIXVerifyChain(-pp) function.\n"); Usage(progName); } cert = getCert(optstate->value, isAscii, progName); if (!cert) goto punt; rememberCert(cert, trusted); if (!firstCert) firstCert = cert; trusted = PR_FALSE; } status = PL_GetNextOpt(optstate); } PL_DestroyOptState(optstate); if (status == PL_OPT_BAD || !firstCert) Usage(progName); /* Initialize log structure */ log.arena = PORT_NewArena(512); log.head = log.tail = NULL; log.count = 0; do { if (usePkix < 2) { /* NOW, verify the cert chain. */ if (usePkix) { /* Use old API with libpkix validation lib */ CERT_SetUsePKIXForValidation(PR_TRUE); } if (!time) time = PR_Now(); defaultDB = CERT_GetDefaultCertDB(); secStatus = CERT_VerifyCertificate(defaultDB, firstCert, PR_TRUE /* check sig */, certUsage, time, &pwdata, /* wincx */ &log, /* error log */ NULL);/* returned usages */ } else do { static CERTValOutParam cvout[4]; static CERTValInParam cvin[6]; SECOidTag oidTag; int inParamIndex = 0; static PRUint64 revFlagsLeaf[2]; static PRUint64 revFlagsChain[2]; static CERTRevocationFlags rev; if (oidStr) { PRArenaPool *arena; SECOidData od; memset(&od, 0, sizeof od); od.offset = SEC_OID_UNKNOWN; od.desc = "User Defined Policy OID"; od.mechanism = CKM_INVALID_MECHANISM; od.supportedExtension = INVALID_CERT_EXTENSION; arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if ( !arena ) { fprintf(stderr, "out of memory"); goto punt; } secStatus = SEC_StringToOID(arena, &od.oid, oidStr, 0); if (secStatus != SECSuccess) { PORT_FreeArena(arena, PR_FALSE); fprintf(stderr, "Can not encode oid: %s(%s)\n", oidStr, SECU_Strerror(PORT_GetError())); break; } oidTag = SECOID_AddEntry(&od); PORT_FreeArena(arena, PR_FALSE); if (oidTag == SEC_OID_UNKNOWN) { fprintf(stderr, "Can not add new oid to the dynamic " "table: %s\n", oidStr); secStatus = SECFailure; break; } cvin[inParamIndex].type = cert_pi_policyOID; cvin[inParamIndex].value.arraySize = 1; cvin[inParamIndex].value.array.oids = &oidTag; inParamIndex++; } if (trustedCertList) { cvin[inParamIndex].type = cert_pi_trustAnchors; cvin[inParamIndex].value.pointer.chain = trustedCertList; inParamIndex++; } cvin[inParamIndex].type = cert_pi_useAIACertFetch; cvin[inParamIndex].value.scalar.b = certFetching; inParamIndex++; rev.leafTests.cert_rev_flags_per_method = revFlagsLeaf; rev.chainTests.cert_rev_flags_per_method = revFlagsChain; secStatus = configureRevocationParams(&rev); if (secStatus) { fprintf(stderr, "Can not config revocation parameters "); break; } cvin[inParamIndex].type = cert_pi_revocationFlags; cvin[inParamIndex].value.pointer.revocation = &rev; inParamIndex++; if (time) { cvin[inParamIndex].type = cert_pi_date; cvin[inParamIndex].value.scalar.time = time; inParamIndex++; } cvin[inParamIndex].type = cert_pi_end; cvout[0].type = cert_po_trustAnchor; cvout[0].value.pointer.cert = NULL; cvout[1].type = cert_po_certList; cvout[1].value.pointer.chain = NULL; /* setting pointer to CERTVerifyLog. Initialized structure * will be used CERT_PKIXVerifyCert */ cvout[2].type = cert_po_errorLog; cvout[2].value.pointer.log = &log; cvout[3].type = cert_po_end; secStatus = CERT_PKIXVerifyCert(firstCert, certUsage, cvin, cvout, &pwdata); if (secStatus != SECSuccess) { break; } issuerCert = cvout[0].value.pointer.cert; builtChain = cvout[1].value.pointer.chain; } while (0); /* Display validation results */ if (secStatus != SECSuccess || log.count > 0) { CERTVerifyLogNode *node = NULL; PRIntn err = PR_GetError(); fprintf(stderr, "Chain is bad, %d = %s\n", err, SECU_Strerror(err)); SECU_displayVerifyLog(stderr, &log, verbose); /* Have cert refs in the log only in case of failure. * Destroy them. */ for (node = log.head; node; node = node->next) { if (node->cert) CERT_DestroyCertificate(node->cert); } rv = 1; } else { fprintf(stderr, "Chain is good!\n"); if (issuerCert) { if (verbose > 1) { rv = SEC_PrintCertificateAndTrust(issuerCert, "Root Certificate", NULL); if (rv != SECSuccess) { SECU_PrintError(progName, "problem printing certificate"); } } else if (verbose > 0) { SECU_PrintName(stdout, &issuerCert->subject, "Root " "Certificate Subject:", 0); } CERT_DestroyCertificate(issuerCert); } if (builtChain) { CERTCertListNode *node; int count = 0; char buff[256]; if (verbose) { for(node = CERT_LIST_HEAD(builtChain); !CERT_LIST_END(node, builtChain); node = CERT_LIST_NEXT(node), count++ ) { sprintf(buff, "Certificate %d Subject", count + 1); SECU_PrintName(stdout, &node->cert->subject, buff, 0); } } CERT_DestroyCertList(builtChain); } rv = 0; } } while (--vfyCounts > 0); /* Need to destroy CERTVerifyLog arena at the end */ PORT_FreeArena(log.arena, PR_FALSE); punt: forgetCerts(); if (NSS_Shutdown() != SECSuccess) { SECU_PrintError(progName, "NSS_Shutdown"); rv = 1; } PORT_Free(progName); PORT_Free(certDir); PORT_Free(oidStr); freeRevocationMethodData(); if (pwdata.data) { PORT_Free(pwdata.data); } PR_Cleanup(); return rv; }
/* * Delete a module from the Data Base */ static SECStatus nssutil_DeleteSecmodDBEntry(const char *appName, const char *filename, const char *dbname, char *args, PRBool rw) { /* SHDB_FIXME implement */ os_stat_type stat_existing; os_open_permissions_type file_mode; FILE *fd = NULL; FILE *fd2 = NULL; char line[MAX_LINE_LENGTH]; char *dbname2 = NULL; char *block = NULL; char *name = NULL; char *lib = NULL; int name_len = 0, lib_len = 0; PRBool skip = PR_FALSE; PRBool found = PR_FALSE; if (dbname == NULL) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } if (!rw) { PORT_SetError(SEC_ERROR_READ_ONLY); return SECFailure; } dbname2 = PORT_Strdup(dbname); if (dbname2 == NULL) goto loser; dbname2[strlen(dbname)-1]++; /* get the permissions of the existing file, or use the default */ if (!os_stat(dbname, &stat_existing)) { file_mode = stat_existing.st_mode; } else { file_mode = os_open_permissions_default; } /* do we really want to use streams here */ fd = fopen(dbname, "r"); if (fd == NULL) goto loser; fd2 = lfopen(dbname2, lfopen_truncate, file_mode); if (fd2 == NULL) goto loser; name = NSSUTIL_ArgGetParamValue("name",args); if (name) { name_len = PORT_Strlen(name); } lib = NSSUTIL_ArgGetParamValue("library",args); if (lib) { lib_len = PORT_Strlen(lib); } /* * the following loop takes line separated config files and collapses * the lines to a single string, escaping and quoting as necessary. */ /* loop state variables */ block = NULL; skip = PR_FALSE; while (fgets(line, sizeof(line), fd) != NULL) { /* If we are processing a block (we haven't hit a blank line yet */ if (*line != '\n') { /* skip means we are in the middle of a block we are deleting */ if (skip) { continue; } /* if we haven't found the block yet, check to see if this block * matches our requirements */ if (!found && ((name && (PORT_Strncasecmp(line,"name=",5) == 0) && (PORT_Strncmp(line+5,name,name_len) == 0)) || (lib && (PORT_Strncasecmp(line,"library=",8) == 0) && (PORT_Strncmp(line+8,lib,lib_len) == 0)))) { /* yup, we don't need to save any more data, */ PORT_Free(block); block=NULL; /* we don't need to collect more of this block */ skip = PR_TRUE; /* we don't need to continue searching for the block */ found =PR_TRUE; continue; } /* not our match, continue to collect data in this block */ block = nssutil_DupCat(block,line); continue; } /* we've collected a block of data that wasn't the module we were * looking for, write it out */ if (block) { fwrite(block, PORT_Strlen(block), 1, fd2); PORT_Free(block); block = NULL; } /* If we didn't just delete the this block, keep the blank line */ if (!skip) { fputs(line,fd2); } /* we are definately not in a deleted block anymore */ skip = PR_FALSE; } fclose(fd); fclose(fd2); if (found) { /* rename dbname2 to dbname */ PR_Delete(dbname); PR_Rename(dbname2,dbname); } else { PR_Delete(dbname2); } PORT_Free(dbname2); PORT_Free(lib); PORT_Free(name); PORT_Free(block); return SECSuccess; loser: if (fd != NULL) { fclose(fd); } if (fd2 != NULL) { fclose(fd2); } if (dbname2) { PR_Delete(dbname2); PORT_Free(dbname2); } PORT_Free(lib); PORT_Free(name); return SECFailure; }
int main(int argc, char **argv) { char * certDir = NULL; char * progName = NULL; int connections = 1; char * cipherString = NULL; char * respUrl = NULL; char * respCertName = NULL; SECStatus secStatus; PLOptState * optstate; PLOptStatus status; PRBool doOcspCheck = PR_FALSE; /* Call the NSPR initialization routines */ PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1); progName = PORT_Strdup(argv[0]); hostName = NULL; optstate = PL_CreateOptState(argc, argv, "C:cd:f:l:n:p:ot:w:"); while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) { switch(optstate->option) { case 'C' : cipherString = PL_strdup(optstate->value); break; case 'c' : dumpChain = PR_TRUE; break; case 'd' : certDir = PL_strdup(optstate->value); break; case 'l' : respUrl = PL_strdup(optstate->value); break; case 'p' : port = PORT_Atoi(optstate->value); break; case 'o' : doOcspCheck = PR_TRUE; break; case 't' : respCertName = PL_strdup(optstate->value); break; case 'w': pwdata.source = PW_PLAINTEXT; pwdata.data = PORT_Strdup(optstate->value); break; case 'f': pwdata.source = PW_FROMFILE; pwdata.data = PORT_Strdup(optstate->value); break; case '\0': hostName = PL_strdup(optstate->value); break; default : Usage(progName); } } if (port == 0) { port = 443; } if (port == 0 || hostName == NULL) Usage(progName); if (doOcspCheck && ((respCertName != NULL && respUrl == NULL) || (respUrl != NULL && respCertName == NULL))) { SECU_PrintError (progName, "options -l <url> and -t " "<responder> must be used together"); Usage(progName); } PK11_SetPasswordFunc(SECU_GetModulePassword); /* Initialize the NSS libraries. */ if (certDir) { secStatus = NSS_Init(certDir); } else { secStatus = NSS_NoDB_Init(NULL); /* load the builtins */ SECMOD_AddNewModule("Builtins", DLL_PREFIX"nssckbi."DLL_SUFFIX, 0, 0); } if (secStatus != SECSuccess) { exitErr("NSS_Init"); } SECU_RegisterDynamicOids(); if (doOcspCheck == PR_TRUE) { SECStatus rv; CERTCertDBHandle *handle = CERT_GetDefaultCertDB(); if (handle == NULL) { SECU_PrintError (progName, "problem getting certdb handle"); goto cleanup; } rv = CERT_EnableOCSPChecking (handle); if (rv != SECSuccess) { SECU_PrintError (progName, "error enabling OCSP checking"); goto cleanup; } if (respUrl != NULL) { rv = CERT_SetOCSPDefaultResponder (handle, respUrl, respCertName); if (rv != SECSuccess) { SECU_PrintError (progName, "error setting default responder"); goto cleanup; } rv = CERT_EnableOCSPDefaultResponder (handle); if (rv != SECSuccess) { SECU_PrintError (progName, "error enabling default responder"); goto cleanup; } } } /* All cipher suites except RSA_NULL_MD5 are enabled by * Domestic Policy. */ NSS_SetDomesticPolicy(); SSL_CipherPrefSetDefault(SSL_RSA_WITH_NULL_MD5, PR_TRUE); /* all the SSL2 and SSL3 cipher suites are enabled by default. */ if (cipherString) { int ndx; /* disable all the ciphers, then enable the ones we want. */ disableAllSSLCiphers(); while (0 != (ndx = *cipherString++)) { int cipher; if (ndx == ':') { int ctmp; cipher = 0; HEXCHAR_TO_INT(*cipherString, ctmp) cipher |= (ctmp << 12); cipherString++; HEXCHAR_TO_INT(*cipherString, ctmp) cipher |= (ctmp << 8); cipherString++; HEXCHAR_TO_INT(*cipherString, ctmp) cipher |= (ctmp << 4); cipherString++; HEXCHAR_TO_INT(*cipherString, ctmp) cipher |= ctmp; cipherString++; } else { const int *cptr; if (! isalpha(ndx)) Usage(progName); cptr = islower(ndx) ? ssl3CipherSuites : ssl2CipherSuites; for (ndx &= 0x1f; (cipher = *cptr++) != 0 && --ndx > 0; ) /* do nothing */; } if (cipher > 0) { SSL_CipherPrefSetDefault(cipher, PR_TRUE); } else { Usage(progName); } } } client_main(port, connections, hostName); cleanup: if (doOcspCheck) { CERTCertDBHandle *handle = CERT_GetDefaultCertDB(); CERT_DisableOCSPDefaultResponder(handle); CERT_DisableOCSPChecking (handle); } if (NSS_Shutdown() != SECSuccess) { exit(1); } PR_Cleanup(); PORT_Free(progName); return 0; }