util.c

来自「支持SSL v2/v3, TLS, PKCS #5, PKCS #7, PKCS」· C语言 代码 · 共 1,013 行 · 第 1/2 页

C
1,013
字号
    char *filename;        dir = SECU_ConfigDirectory (NULL);    switch ( dbVersion ) {      case 7:        fnarg = "7";        break;      case 6:	fnarg = "6";	break;      case 5:	fnarg = "5";	break;      case 4:      default:	fnarg = "";	break;    }    filename = PR_smprintf("%s/cert%s.db", dir, fnarg);    return(filename);}/*************************************************************** * * s e c E r r o r S t r i n g * * Returns an error string corresponding to the given error code. * Doesn't cover all errors; returns a default for many. * Returned string is only valid until the next call of this function. */const char*secErrorString(long code){	static char errstring[80]; /* dynamically constructed error string */	char *c; /* the returned string */	switch(code) {	case SEC_ERROR_IO: c = "io error";		break;	case SEC_ERROR_LIBRARY_FAILURE: c = "security library failure";		break;	case SEC_ERROR_BAD_DATA: c = "bad data";		break;	case SEC_ERROR_OUTPUT_LEN: c = "output length";		break;	case SEC_ERROR_INPUT_LEN: c = "input length";		break;	case SEC_ERROR_INVALID_ARGS: c = "invalid args";		break;	case SEC_ERROR_EXPIRED_CERTIFICATE: c = "expired certificate";		break;	case SEC_ERROR_REVOKED_CERTIFICATE: c = "revoked certificate";		break;	case SEC_ERROR_INADEQUATE_KEY_USAGE: c = "inadequate key usage";		break;	case SEC_ERROR_INADEQUATE_CERT_TYPE: c = "inadequate certificate type";		break;	case SEC_ERROR_UNTRUSTED_CERT: c = "untrusted cert";		break;	case SEC_ERROR_NO_KRL: c = "no key revocation list";		break;	case SEC_ERROR_KRL_BAD_SIGNATURE: c = "key revocation list: bad signature";		break;	case SEC_ERROR_KRL_EXPIRED: c = "key revocation list expired";		break;	case SEC_ERROR_REVOKED_KEY: c = "revoked key";		break;	case SEC_ERROR_CRL_BAD_SIGNATURE:		c = "certificate revocation list: bad signature";		break;	case SEC_ERROR_CRL_EXPIRED: c = "certificate revocation list expired";		break;	case SEC_ERROR_CRL_NOT_YET_VALID:		c = "certificate revocation list not yet valid";		break;	case SEC_ERROR_UNKNOWN_ISSUER: c = "unknown issuer";		break;	case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE: c = "expired issuer certificate";		break;	case SEC_ERROR_BAD_SIGNATURE: c = "bad signature";		break;	case SEC_ERROR_BAD_KEY: c = "bad key";		break;	case SEC_ERROR_NOT_FORTEZZA_ISSUER: c = "not fortezza issuer";		break;	case SEC_ERROR_CA_CERT_INVALID:		c = "Certificate Authority certificate invalid";		break;	case SEC_ERROR_EXTENSION_NOT_FOUND: c = "extension not found";		break;	case SEC_ERROR_CERT_NOT_IN_NAME_SPACE: c = "certificate not in name space";		break;	case SEC_ERROR_UNTRUSTED_ISSUER: c = "untrusted issuer";		break;	default:		sprintf(errstring, "security error %ld", code);		c = errstring;		break;	}	return c;}/*************************************************************** * * d i s p l a y V e r i f y L o g * * Prints the log of a cert verification. */voiddisplayVerifyLog(CERTVerifyLog *log){	CERTVerifyLogNode	*node;	CERTCertificate		*cert;	char				*name;	if( !log  || (log->count <= 0) ) {		return;	}	for(node = log->head; node != NULL; node = node->next) {		if( !(cert = node->cert) ) {			continue;		}		/* Get a name for this cert */		if(cert->nickname != NULL) {			name = cert->nickname;		} else if(cert->emailAddr != NULL) {			name = cert->emailAddr;		} else {			name = cert->subjectName;		}		printf( "%s%s:\n",			name,			(node->depth > 0) ? " [Certificate Authority]" : ""		);		printf("\t%s\n", secErrorString(node->error));	}}/* *  J a r L i s t M o d u l e s * *  Print a list of the PKCS11 modules that are *  available. This is useful for smartcard people to *  make sure they have the drivers loaded. * */voidJarListModules(void){  int i;  int count = 0;  SECMODModuleList *modules = NULL;  static SECMODListLock *moduleLock = NULL;  SECMODModuleList *mlp;  modules = SECMOD_GetDefaultModuleList();  if (modules == NULL)    {    PR_fprintf(errorFD, "%s: Can't get module list\n", PROGRAM_NAME);	errorCount++;    exit (ERRX);    }  if ((moduleLock = SECMOD_NewListLock()) == NULL)    {    /* this is the wrong text */    PR_fprintf(errorFD, "%s: unable to acquire lock on module list\n",		PROGRAM_NAME);	errorCount++;    exit (ERRX);    }  SECMOD_GetReadLock (moduleLock);  PR_fprintf(outputFD, "\nListing of PKCS11 modules\n");  PR_fprintf(outputFD, "-----------------------------------------------\n");   for (mlp = modules; mlp != NULL; mlp = mlp->next)     {    count++;    PR_fprintf(outputFD, "%3d. %s\n", count, mlp->module->commonName);    if (mlp->module->internal)      PR_fprintf(outputFD, "          (this module is internally loaded)\n");    else      PR_fprintf(outputFD, "          (this is an external module)\n");    if (mlp->module->dllName)      PR_fprintf(outputFD, "          DLL name: %s\n", mlp->module->dllName);    if (mlp->module->slotCount == 0)      PR_fprintf(outputFD, "          slots: There are no slots attached to this module\n");    else      PR_fprintf(outputFD, "          slots: %d slots attached\n", mlp->module->slotCount);    if (mlp->module->loaded == 0)      PR_fprintf(outputFD, "          status: Not loaded\n");    else      PR_fprintf(outputFD, "          status: loaded\n");    for (i = 0; i < mlp->module->slotCount; i++)       {      PK11SlotInfo *slot = mlp->module->slots[i];      PR_fprintf(outputFD, "\n");      PR_fprintf(outputFD, "    slot: %s\n", PK11_GetSlotName(slot));      PR_fprintf(outputFD, "   token: %s\n", PK11_GetTokenName(slot));      }    }  PR_fprintf(outputFD, "-----------------------------------------------\n");  if (count == 0)    PR_fprintf(outputFD,		"Warning: no modules were found (should have at least one)\n");  SECMOD_ReleaseReadLock (moduleLock);}/********************************************************************** * c h o p * * Eliminates leading and trailing whitespace.  Returns a pointer to the  * beginning of non-whitespace, or an empty string if it's all whitespace. */char*chop(char *str){	char *start, *end;	if(str) {		start = str;		/* Nip leading whitespace */		while(isspace(*start)) {			start++;		}		/* Nip trailing whitespace */		if(strlen(start) > 0) {			end = start + strlen(start) - 1;			while(isspace(*end) && end > start) {				end--;			}			*(end+1) = '\0';		}				return start;	} else {		return NULL;	}}/*********************************************************************** * * F a t a l E r r o r * * Outputs an error message and bails out of the program. */voidFatalError(char *msg){	if(!msg) msg = "";	PR_fprintf(errorFD, "FATAL ERROR: %s\n", msg);	errorCount++;	exit(ERRX);}/************************************************************************* * * I n i t C r y p t o */intInitCrypto(char *cert_dir, PRBool readOnly){  SECStatus rv;  static int prior = 0;	PK11SlotInfo *slotinfo;  CERTCertDBHandle *db;	if (prior == 0) {		/* some functions such as OpenKeyDB expect this path to be		 * implicitly set prior to calling */		SECU_ConfigDirectory (cert_dir);		if ((rv = SECU_PKCS11Init(readOnly)) != SECSuccess) {			PR_fprintf(errorFD, "%s: Unable to initialize PKCS11, code %d\n",				PROGRAM_NAME, rv);			errorCount++;			exit (ERRX);		}		SEC_Init();		/* Been there done that */		prior++;		/* open cert database and set the default certificate DB */		db = OpenCertDB(readOnly); 		if (db == NULL) return -1;		CERT_SetDefaultCertDB (db);		if(password) {			PK11_SetPasswordFunc(pk11_password_hardcode);		} 		/* Must login to FIPS before you do anything else */		if(PK11_IsFIPS()) {			slotinfo = PK11_GetInternalSlot();			if(!slotinfo) {				fprintf(stderr, "%s: Unable to get PKCS #11 Internal Slot."				  "\n", PROGRAM_NAME);				return -1;			}			if(PK11_Authenticate(slotinfo, PR_FALSE /*loadCerts*/,			  NULL /*wincx*/) != SECSuccess) {				fprintf(stderr, "%s: Unable to authenticate to %s.\n",					PROGRAM_NAME, PK11_GetSlotName(slotinfo));				return -1;			}		}		/* Make sure there is a password set on the internal key slot */		slotinfo = PK11_GetInternalKeySlot();		if(!slotinfo) {			fprintf(stderr, "%s: Unable to get PKCS #11 Internal Key Slot."			  "\n", PROGRAM_NAME);			return -1;		}		if(PK11_NeedUserInit(slotinfo)) {			PR_fprintf(errorFD,"\nWARNING: No password set on internal key database.  Most operations will fail.""\nYou must use Communicator to create a password.\n");			warningCount++;		}		/* Make sure we can authenticate to the key slot in FIPS mode */		if(PK11_IsFIPS()) {			if(PK11_Authenticate(slotinfo, PR_FALSE /*loadCerts*/,			  NULL /*wincx*/) != SECSuccess) {				fprintf(stderr, "%s: Unable to authenticate to %s.\n",					PROGRAM_NAME, PK11_GetSlotName(slotinfo));				return -1;			}		}	}	return 0;}/* Windows foolishness is now in the secutil lib *//***************************************************************** *  g e t _ d e f a u l t _ c e r t _ d i r * *  Attempt to locate a certificate directory. *  Failing that, complain that the user needs to *  use the -d(irectory) parameter. * */char *get_default_cert_dir (void){  char *home;  char *cd = NULL;  static char db [FNSIZE];#ifdef XP_UNIX  home = getenv ("HOME");  if (home && *home)    {    sprintf (db, "%s/.netscape", home);    cd = db;    }#endif#ifdef XP_PC  FILE *fp;  /* first check the environment override */  home = getenv ("JAR_HOME");  if (home && *home)    {    sprintf (db, "%s/cert7.db", home);    if ((fp = fopen (db, "r")) != NULL)      {      fclose (fp);      cd = home;      }    }  /* try the old navigator directory */  if (cd == NULL)    {    home = "c:/Program Files/Netscape/Navigator";    sprintf (db, "%s/cert7.db", home);    if ((fp = fopen (db, "r")) != NULL)      {      fclose (fp);      cd = home;      }    }  /* Try the current directory, I wonder if this     is really a good idea. Remember, Windows only.. */  if (cd == NULL)    {    home = ".";    sprintf (db, "%s/cert7.db", home);    if ((fp = fopen (db, "r")) != NULL)      {      fclose (fp);      cd = home;      }    }#endif  if (!cd)    {    PR_fprintf(errorFD,		"You must specify the location of your certificate directory\n");    PR_fprintf(errorFD,		"with the -d option. Example: -d ~/.netscape in many cases with Unix.\n");	errorCount++;    exit (ERRX);    }  return cd;}/************************************************************************ * g i v e _ h e l p */void give_help (int status){  if (status == SEC_ERROR_UNKNOWN_ISSUER)    {    PR_fprintf(errorFD,		"The Certificate Authority (CA) for this certificate\n");    PR_fprintf(errorFD,		"does not appear to be in your database. You should contact\n");    PR_fprintf(errorFD,		"the organization which issued this certificate to obtain\n");    PR_fprintf(errorFD, "a copy of its CA Certificate.\n");    }}/************************************************************************** * * p r _ f g e t s * * fgets implemented with NSPR. */char*pr_fgets(char *buf, int size, PRFileDesc *file){	int i;	int status;	char c;	i=0;	while(i < size-1) {		status = PR_Read(file, (void*) &c, 1);		if(status==-1) {			return NULL;		} else if(status==0) {			break;		}		buf[i++] = c;		if(c=='\n') {			break;		}	}	buf[i]='\0';	return buf;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?