Exemple #1
0
int sign_value(pkcs11_handle_t *h, cert_object_t *cert, CK_BYTE *data,
	      CK_ULONG length, CK_BYTE **signature, CK_ULONG *signature_length)
{
  SECOidTag algtag;
  SECKEYPrivateKey *key;
  SECItem result;
  SECStatus rv;

  if (h->slot == NULL) {
    return -1;
  }

  /* get the key */
  key = PK11_FindPrivateKeyFromCert(h->slot, (CERTCertificate *)cert, NULL);
  if (key == NULL) {
    DBG1("Couldn't Find key for Cert: %s", SECU_Strerror(PR_GetError()));
    return -1;
  }

  /* get the oid */
  algtag = SEC_GetSignatureAlgorithmOidTag(key->keyType, SEC_OID_SHA1);

  /* sign the data */
  rv = SEC_SignData(&result, data, length, key, algtag);
  SECKEY_DestroyPrivateKey(key);
  if (rv != SECSuccess) {
    DBG1("Signature failed: %s", SECU_Strerror(PR_GetError()));
    return -1;
  }

  *signature = (CK_BYTE *)result.data;
  *signature_length = result.len;
  return 0;
}
Exemple #2
0
void release_pkcs11_module(pkcs11_handle_t *h)
{
  SECStatus rv;
  close_pkcs11_session(h);
  if (h->is_user_module) {
    rv = SECMOD_UnloadUserModule(h->module);
    if (rv != SECSuccess) {
      DBG1("Unloading UserModule failed: %s", SECU_Strerror(PR_GetError()));
    }
  }

  if (h->module) {
    SECMOD_DestroyModule(h->module);
  }
  memset(h, 0, sizeof(pkcs11_handle_t));
  free(h);

  /* if we initialized NSS, then we need to shut it down */
  if (!app_has_NSS) {
    rv = NSS_Shutdown();
    if (rv != SECSuccess) {
      DBG1("NSS Shutdown Failed: %s", SECU_Strerror(PR_GetError()));
    }
  }
}
Exemple #3
0
/*************************************************************************
 *
 * F i p s M o d e
 * If arg=="true", enable FIPS mode on the internal module.  If arg=="false",
 * disable FIPS mode on the internal module.
 */
Error
FipsMode(char *arg)
{
    char *internal_name;

    if (!PORT_Strcasecmp(arg, "true")) {
        if (!PK11_IsFIPS()) {
            internal_name = PR_smprintf("%s",
                                        SECMOD_GetInternalModule()->commonName);
            if (SECMOD_DeleteInternalModule(internal_name) != SECSuccess) {
                PR_fprintf(PR_STDERR, "%s\n", SECU_Strerror(PORT_GetError()));
                PR_smprintf_free(internal_name);
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_smprintf_free(internal_name);
            if (!PK11_IsFIPS()) {
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_fprintf(PR_STDOUT, msgStrings[FIPS_ENABLED_MSG]);
        } else {
            PR_fprintf(PR_STDERR, errStrings[FIPS_ALREADY_ON_ERR]);
            return FIPS_ALREADY_ON_ERR;
        }
    } else if (!PORT_Strcasecmp(arg, "false")) {
        if (PK11_IsFIPS()) {
            internal_name = PR_smprintf("%s",
                                        SECMOD_GetInternalModule()->commonName);
            if (SECMOD_DeleteInternalModule(internal_name) != SECSuccess) {
                PR_fprintf(PR_STDERR, "%s\n", SECU_Strerror(PORT_GetError()));
                PR_smprintf_free(internal_name);
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_smprintf_free(internal_name);
            if (PK11_IsFIPS()) {
                PR_fprintf(PR_STDERR, errStrings[FIPS_SWITCH_FAILED_ERR]);
                return FIPS_SWITCH_FAILED_ERR;
            }
            PR_fprintf(PR_STDOUT, msgStrings[FIPS_DISABLED_MSG]);
        } else {
            PR_fprintf(PR_STDERR, errStrings[FIPS_ALREADY_OFF_ERR]);
            return FIPS_ALREADY_OFF_ERR;
        }
    } else {
        PR_fprintf(PR_STDERR, errStrings[INVALID_FIPS_ARG]);
        return INVALID_FIPS_ARG;
    }

    return SUCCESS;
}
Exemple #4
0
CERTCertificate *
getCert(const char *name, PRBool isAscii, const char * progName)
{
    CERTCertificate * cert;
    CERTCertDBHandle *defaultDB;
    PRFileDesc*     fd;
    SECStatus       rv;
    SECItem         item        = {0, NULL, 0};

    defaultDB = CERT_GetDefaultCertDB();

    /* First, let's try to find the cert in existing DB. */
    cert = CERT_FindCertByNicknameOrEmailAddr(defaultDB, name);
    if (cert) {
        return cert;
    }

    /* Don't have a cert with name "name" in the DB. Try to
     * open a file with such name and get the cert from there.*/
    fd = PR_Open(name, PR_RDONLY, 0777); 
    if (!fd) {
	PRIntn err = PR_GetError();
    	fprintf(stderr, "open of %s failed, %d = %s\n", 
	        name, err, SECU_Strerror(err));
	return cert;
    }

    rv = SECU_ReadDERFromFile(&item, fd, isAscii);
    PR_Close(fd);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
	return cert;
    }

    if (!item.len) { /* file was empty */
	fprintf(stderr, "cert file %s was empty.\n", name);
	return cert;
    }

    cert = CERT_NewTempCertificate(defaultDB, &item, 
                                   NULL     /* nickname */, 
                                   PR_FALSE /* isPerm */, 
				   PR_TRUE  /* copyDER */);
    if (!cert) {
	PRIntn err = PR_GetError();
	fprintf(stderr, "couldn't import %s, %d = %s\n",
	        name, err, SECU_Strerror(err));
    }
    PORT_Free(item.data);
    return cert;
}
Exemple #5
0
int crypto_init(cert_policy *policy) {
  SECStatus rv;

  DBG("Initializing NSS ...");
  if (NSS_IsInitialized()) {
    app_has_NSS = 1;
    /* we should save the app's password function */
    PK11_SetPasswordFunc(password_passthrough);
    DBG("...  NSS is initialized");
    return 0;
  }
  if (policy->nss_dir) {
    /* initialize with read only databases */
    DBG1("Initializing NSS ... database=%s", policy->nss_dir);
    rv = NSS_Init(policy->nss_dir);
  } else {
    /* not database secified */
    DBG("Initializing NSS ... with no db");
    rv = NSS_NoDB_Init(NULL);
  }

  if (rv != SECSuccess) {
    DBG1("NSS_Initialize failed: %s", SECU_Strerror(PR_GetError()));
    return -1;
  }
  /* register a callback */
  PK11_SetPasswordFunc(password_passthrough);

  if (policy->ocsp_policy == OCSP_ON) {
    CERT_EnableOCSPChecking(CERT_GetDefaultCertDB());
  }
  DBG("...  NSS Complete");
  return 0;
}
Exemple #6
0
/*
 * Get the status for the specified certificate (whose nickname is "cert_name").
 * Directly use the OCSP function rather than doing a full verification.
 */
static SECStatus
get_cert_status (FILE *out_file, CERTCertDBHandle *handle,
		 CERTCertificate *cert, const char *cert_name,
		 PRTime verify_time)
{
    SECStatus rv = SECFailure;

    if (handle == NULL || cert == NULL)
	goto loser;

    rv = CERT_CheckOCSPStatus (handle, cert, verify_time, NULL);

    fprintf (out_file, "Check of certificate \"%s\" ", cert_name); 
    if (rv == SECSuccess) {
	fprintf (out_file, "succeeded.\n"); 
    } else {
	const char *error_string = SECU_Strerror(PORT_GetError());
	fprintf (out_file, "failed.  Reason:\n");
	if (error_string != NULL && PORT_Strlen(error_string) > 0)
	    fprintf (out_file, "%s\n", error_string);
	else
	    fprintf (out_file, "Unknown\n");
    }

    rv = SECSuccess;

loser:

    return rv;
}
Exemple #7
0
/*
 * Verify the specified certificate (whose nickname is "cert_name").
 * OCSP is already turned on, so we just need to call the standard
 * certificate verification API and let it do all the work.
 */
static SECStatus
verify_cert (FILE *out_file, CERTCertDBHandle *handle, CERTCertificate *cert,
	     const char *cert_name, SECCertUsage cert_usage, PRTime verify_time)
{
    SECStatus rv = SECFailure;

    if (handle == NULL || cert == NULL)
	return rv;

    rv = CERT_VerifyCert (handle, cert, PR_TRUE, cert_usage, verify_time,
			  NULL, NULL);

    fprintf (out_file, "Verification of certificate \"%s\" ", cert_name); 
    if (rv == SECSuccess) {
	fprintf (out_file, "succeeded.\n"); 
    } else {
	const char *error_string = SECU_Strerror(PORT_GetError());
	fprintf (out_file, "failed.  Reason:\n");
	if (error_string != NULL && PORT_Strlen(error_string) > 0)
	    fprintf (out_file, "%s\n", error_string);
	else
	    fprintf (out_file, "Unknown\n");
    }

    rv = SECSuccess;

    return rv;
}
Exemple #8
0
char *
XP_GetString(int i)
{
    /* nasty hackish cast to avoid changing the signature of
     * JAR_init_callbacks() */
    return (char *)SECU_Strerror(i);
}
Exemple #9
0
int get_random_value(unsigned char *data, int length)
{
  SECStatus rv = PK11_GenerateRandom(data,length);
  if (rv != SECSuccess) {
    DBG1("couldn't generate random number: %s", SECU_Strerror(PR_GetError()));
  }
  return (rv == SECSuccess) ? 0 : -1;
}
static void
errWarn(char * funcString)
{
    PRErrorCode  perr      = PR_GetError();
    const char * errString = SECU_Strerror(perr);

    fprintf(stderr, "strsclnt: %s returned error %d:\n%s\n",
            funcString, perr, errString);
}
Exemple #11
0
SECStatus ImportCRL (CERTCertDBHandle *certHandle, char *url, int type, 
                     PRFileDesc *inFile, PRInt32 importOptions, PRInt32 decodeOptions)
{
    CERTSignedCrl *crl = NULL;
    SECItem crlDER;
    PK11SlotInfo* slot = NULL;
    int rv;
#if defined(DEBUG_jp96085)
    PRIntervalTime starttime, endtime, elapsed;
    PRUint32 mins, secs, msecs;
#endif

    crlDER.data = NULL;


    /* Read in the entire file specified with the -f argument */
    rv = SECU_ReadDERFromFile(&crlDER, inFile, PR_FALSE);
    if (rv != SECSuccess) {
	SECU_PrintError(progName, "unable to read input file");
	return (SECFailure);
    }

    decodeOptions |= CRL_DECODE_DONT_COPY_DER;

    slot = PK11_GetInternalKeySlot();
 
#if defined(DEBUG_jp96085)
    starttime = PR_IntervalNow();
#endif
    crl = PK11_ImportCRL(slot, &crlDER, url, type,
          NULL, importOptions, NULL, decodeOptions);
#if defined(DEBUG_jp96085)
    endtime = PR_IntervalNow();
    elapsed = endtime - starttime;
    mins = PR_IntervalToSeconds(elapsed) / 60;
    secs = PR_IntervalToSeconds(elapsed) % 60;
    msecs = PR_IntervalToMilliseconds(elapsed) % 1000;
    printf("Elapsed : %2d:%2d.%3d\n", mins, secs, msecs);
#endif
    if (!crl) {
	const char *errString;

	rv = SECFailure;
	errString = SECU_Strerror(PORT_GetError());
	if ( errString && PORT_Strlen (errString) == 0)
	    SECU_PrintError (progName, 
	        "CRL is not imported (error: input CRL is not up to date.)");
	else    
	    SECU_PrintError (progName, "unable to import CRL");
    } else {
	SEC_DestroyCrl (crl);
    }
    if (slot) {
        PK11_FreeSlot(slot);
    }
    return (rv);
}
Exemple #12
0
void
errWarn(char *function)
{
    PRErrorCode  errorNumber = PR_GetError();
    const char * errorString = SECU_Strerror(errorNumber);

    fprintf(stderr, "Error in function %s: %d\n - %s\n",
		    function, errorNumber, errorString);
}
Exemple #13
0
static const char *
errWarn(char *funcString)
{
    PRErrorCode perr = PR_GetError();
    const char *errString = SECU_Strerror(perr);

    fprintf(stderr, "httpserv: %s returned error %d:\n%s\n",
            funcString, perr, errString);
    return errString;
}
Exemple #14
0
static SECStatus
myBadCertHandler( void *arg, PRFileDesc *fd)
{
    PRErrorCode err = PR_GetError();
    if (!MakeCertOK)
	fprintf(stderr, 
	    "strsclnt: -- SSL: Server Certificate Invalid, err %d.\n%s\n", 
            err, SECU_Strerror(err));
    return (MakeCertOK ? SECSuccess : SECFailure);
}
Exemple #15
0
LDAP_CALL
ldapssl_err2string( const int prerrno )
{
    const char	*s;

    if (( s = SECU_Strerror( (PRErrorCode)prerrno )) == NULL ) {
	s = dgettext(TEXT_DOMAIN, "unknown");
    }

    return( s );
}
static int
HashDecodeAndVerify(FILE *out, FILE *content, PRFileDesc *signature,
		    SECCertUsage usage, char *progName)
{
    SECItem derdata;
    SEC_PKCS7ContentInfo *cinfo;
    SEC_PKCS7SignedData *signedData;
    HASH_HashType digestType;
    SECItem digest;
    unsigned char buffer[32];

    if (SECU_ReadDERFromFile(&derdata, signature, PR_FALSE) != SECSuccess) {
	SECU_PrintError(progName, "error reading signature file");
	return -1;
    }

    cinfo = SEC_PKCS7DecodeItem(&derdata, NULL, NULL, NULL, NULL,
				NULL, NULL, NULL);
    if (cinfo == NULL)
	return -1;

    if (! SEC_PKCS7ContentIsSigned(cinfo)) {
	fprintf (out, "Signature file is pkcs7 data, but not signed.\n");
	return -1;
    }

    signedData = cinfo->content.signedData;

    /* assume that there is only one digest algorithm for now */
    digestType = AlgorithmToHashType(signedData->digestAlgorithms[0]);
    if (digestType == HASH_AlgNULL) {
	fprintf (out, "Invalid hash algorithmID\n");
	return -1;
    }

    digest.data = buffer;
    if (DigestFile (digest.data, &digest.len, 32, content, digestType)) {
	SECU_PrintError (progName, "problem computing message digest");
	return -1;
    }

    fprintf(out, "Signature is ");
    if (SEC_PKCS7VerifyDetachedSignature (cinfo, usage, &digest, digestType,
					  PR_FALSE))
	fprintf(out, "valid.\n");
    else
	fprintf(out, "invalid (Reason: %s).\n",
		SECU_Strerror(PORT_GetError()));

    SEC_PKCS7DestroyContentInfo(cinfo);
    return 0;
}
Exemple #17
0
int pkcs11_login(pkcs11_handle_t *h, char *password)
{
  SECStatus rv;

  if (h->slot == NULL) {
    DBG("Login failed: No Slot selected");
    return -1;
  }
  rv = PK11_Authenticate(h->slot, PR_FALSE, password);
  if (rv != SECSuccess) {
    DBG1("Login failed: %s", SECU_Strerror(PR_GetError()));
  }
  return (rv == SECSuccess) ? 0 : -1;
}
Exemple #18
0
void
doDecrypt(char * dataString, FILE *outFile, FILE *logFile, secuPWData *pwdata)
{
    int        strLen = strlen(dataString);
    SECItem   *decoded = NSSBase64_DecodeBuffer(NULL, NULL, dataString, strLen);
    SECStatus  rv;
    int        err;
    SECItem    result = { siBuffer, NULL, 0 };

    if ((decoded == NULL) || (decoded->len == 0)) {
	if (logFile) {
	    err = PORT_GetError();
	    fprintf(logFile,"Base 64 decode failed on <%s>\n", dataString);
	    fprintf(logFile," Error %d: %s\n", err, SECU_Strerror(err));
	}
	fputs(dataString, outFile);
	if (decoded)
	    SECITEM_FreeItem(decoded, PR_TRUE);
	return;
    }

    rv = PK11SDR_Decrypt(decoded, &result, pwdata);
    SECITEM_ZfreeItem(decoded, PR_TRUE);
    if (rv == SECSuccess) {
	/* result buffer has no extra space for a NULL */
	fprintf(outFile, "Decrypted: \"%.*s\"\n", result.len, result.data);
	SECITEM_ZfreeItem(&result, PR_FALSE);
	return;
    }
    /* Encryption failed. output raw input. */
    if (logFile) {
	err = PORT_GetError();
	fprintf(logFile,"SDR decrypt failed on <%s>\n", dataString);
	fprintf(logFile," Error %d: %s\n", err, SECU_Strerror(err));
    }
    fputs(dataString,outFile);
}
Exemple #19
0
/*
 * NSS allows you to load a specific module. If the user specified a module
 * to load, load it, otherwize select on of the standard modules from the
 * secmod.db list.
 */
int load_pkcs11_module(const char *pkcs11_module, pkcs11_handle_t **hp)
{
  pkcs11_handle_t *h = (pkcs11_handle_t *)calloc(sizeof(pkcs11_handle_t),1);
  SECMODModule *module = NULL;
#define SPEC_TEMPLATE "library=\"%s\" name=\"SmartCard\""
  char *moduleSpec = NULL;

  if (!pkcs11_module || (strcasecmp(pkcs11_module,"any module") == 0)) {
    h->is_user_module = PR_FALSE;
    h->module = NULL;
    *hp = h;
    return 0;
  }

  /* found it, use the existing module */
  module = find_module_by_library(pkcs11_module);
  if (module) {
    h->is_user_module = PR_FALSE;
    h->module = module;
    *hp = h;
    return 0;
  }

  /* specified module is not already loaded, load it now */
  moduleSpec = malloc(sizeof(SPEC_TEMPLATE) + strlen(pkcs11_module));
  if (!moduleSpec) {
    DBG1("Malloc failed when allocating module spec", strerror(errno));
    free (h);
    return -1;
  }
  sprintf(moduleSpec,SPEC_TEMPLATE, pkcs11_module);
  DBG2("loading Module explictly, moduleSpec=<%s> module=%s",
                                                moduleSpec, pkcs11_module);
  module = SECMOD_LoadUserModule(moduleSpec, NULL, 0);
  free(moduleSpec);
  if ((!module) || !module->loaded) {
    DBG1("Failed to load SmartCard software %s", SECU_Strerror(PR_GetError()));
    free (h);
    if (module) {
      SECMOD_DestroyModule(module);
    }
    return -1;
  }
  h->is_user_module = PR_TRUE;
  h->module = module;
  *hp = h;
  DBG("load module complete");
  return 0;
}
Exemple #20
0
/* Function: SECStatus myBadCertHandler()
 *
 * Purpose: This callback is called when the incoming certificate is not
 * valid. We define a certain set of parameters that still cause the
 * certificate to be "valid" for this session, and return SECSuccess to cause
 * the server to continue processing the request when any of these conditions
 * are met. Otherwise, SECFailure is return and the server rejects the 
 * request.
 */
SECStatus 
myBadCertHandler(void *arg, PRFileDesc *socket) 
{

    SECStatus	secStatus = SECFailure;
    PRErrorCode	err;

    /* log invalid cert here */

    if (!arg) {
	return secStatus;
    }

    *(PRErrorCode *)arg = err = PORT_GetError();

    /* If any of the cases in the switch are met, then we will proceed   */
    /* with the processing of the request anyway. Otherwise, the default */	
    /* case will be reached and we will reject the request.              */

    switch (err) {
    case SEC_ERROR_INVALID_AVA:
    case SEC_ERROR_INVALID_TIME:
    case SEC_ERROR_BAD_SIGNATURE:
    case SEC_ERROR_EXPIRED_CERTIFICATE:
    case SEC_ERROR_UNKNOWN_ISSUER:
    case SEC_ERROR_UNTRUSTED_CERT:
    case SEC_ERROR_CERT_VALID:
    case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
    case SEC_ERROR_CRL_EXPIRED:
    case SEC_ERROR_CRL_BAD_SIGNATURE:
    case SEC_ERROR_EXTENSION_VALUE_INVALID:
    case SEC_ERROR_CA_CERT_INVALID:
    case SEC_ERROR_CERT_USAGES_INVALID:
    case SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION:
	secStatus = SECSuccess;
	break;
    default:
	secStatus = SECFailure;
	break;
    }

    fprintf(stderr, "Bad certificate: %d, %s\n", err, SECU_Strerror(err));

    return secStatus;
}
Exemple #21
0
void 
SECU_PrintErrMsg(FILE *out, int level, char *progName, char *msg, ...)
{
    va_list args;
    PRErrorCode err = PORT_GetError();
    const char * errString = SECU_Strerror(err);

    va_start(args, msg);

    SECU_Indent(out, level);
    fprintf(out, "%s: ", progName);
    vfprintf(out, msg, args);
    if (errString != NULL && PORT_Strlen(errString) > 0)
    fprintf(out, ": %s\n", errString);
    else
    fprintf(out, ": error %d\n", (int)err);

    va_end(args);
}
Exemple #22
0
/**********************************************************************
 *
 * A d d M o d u l e
 *
 * Add the named module, with the given library file, ciphers, and
 * default mechanism flags
 */
Error
AddModule(char *moduleName, char *libFile, char *cipherString,
          char *mechanismString, char *modparms)
{
    unsigned long ciphers;
    unsigned long mechanisms;
    SECStatus status;

    mechanisms =
        getFlagsFromString(mechanismString, mechanismStrings,
                           numMechanismStrings);
    ciphers =
        getFlagsFromString(cipherString, cipherStrings, numCipherStrings);

    status =
        SECMOD_AddNewModuleEx(moduleName, libFile,
                              SECMOD_PubMechFlagstoInternal(mechanisms),
                              SECMOD_PubCipherFlagstoInternal(ciphers),
                              modparms, NULL);

    if (status != SECSuccess) {
        char *errtxt = NULL;
        PRInt32 copied = 0;
        if (PR_GetErrorTextLength()) {
            errtxt = PR_Malloc(PR_GetErrorTextLength() + 1);
            copied = PR_GetErrorText(errtxt);
        }
        if (copied && errtxt) {
            PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR],
                       moduleName, errtxt);
            PR_Free(errtxt);
        } else {
            PR_fprintf(PR_STDERR, errStrings[ADD_MODULE_FAILED_ERR],
                       moduleName, SECU_Strerror(PORT_GetError()));
        }
        return ADD_MODULE_FAILED_ERR;
    } else {
        PR_fprintf(PR_STDOUT, msgStrings[ADD_MODULE_SUCCESS_MSG], moduleName);
        return SUCCESS;
    }
}
Exemple #23
0
static SECStatus DeleteCRL (CERTCertDBHandle *certHandle, char *name, int type)
{
    CERTSignedCrl *crl = NULL;    
    SECStatus rv = SECFailure;

    crl = FindCRL (certHandle, name, type);
    if (!crl) {
	SECU_PrintError
		(progName, "could not find the issuer %s's CRL", name);
	return SECFailure;
    }
    rv = SEC_DeletePermCRL (crl);
    SEC_DestroyCrl(crl);
    if (rv != SECSuccess) {
	SECU_PrintError(progName, "fail to delete the issuer %s's CRL "
	                "from the perm database (reason: %s)",
	                name, SECU_Strerror(PORT_GetError()));
	return SECFailure;
    }
    return (rv);
}
Exemple #24
0
void
doDecode(char * dataString, FILE *outFile, FILE *logFile)
{
    int        strLen = strlen(dataString + 1);
    SECItem   *decoded;

    decoded = NSSBase64_DecodeBuffer(NULL, NULL, dataString + 1, strLen);
    if ((decoded == NULL) || (decoded->len == 0)) {
	if (logFile) {
	    int err = PORT_GetError();
	    fprintf(logFile,"Base 64 decode failed on <%s>\n", dataString + 1);
	    fprintf(logFile," Error %d: %s\n", err, SECU_Strerror(err));
	}
	fputs(dataString, outFile);
	if (decoded)
	    SECITEM_FreeItem(decoded, PR_TRUE);
	return;
    }
    fprintf(outFile, "Decoded: \"%.*s\"\n", decoded->len, decoded->data);
    SECITEM_ZfreeItem(decoded, PR_TRUE);
}
int main(int argc, char **argv)
{
    int rv, ascii;
    char *progName;
    FILE *outFile;
    PRFileDesc *inFile;
    SECItem der, data;
    char *typeTag;
    PLOptState *optstate;

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

    ascii = 0;
    inFile = 0;
    outFile = 0;
    typeTag = 0;
    optstate = PL_CreateOptState(argc, argv, "at:i:o:");
    while ( PL_GetNextOpt(optstate) == PL_OPT_OK ) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'a':
	    ascii = 1;
	    break;

	  case 'i':
	    inFile = PR_Open(optstate->value, PR_RDONLY, 0);
	    if (!inFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'o':
	    outFile = fopen(optstate->value, "w");
	    if (!outFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 't':
	    typeTag = strdup(optstate->value);
	    break;
	}
    }
    PL_DestroyOptState(optstate);
    if (!typeTag) Usage(progName);

    if (!inFile) inFile = PR_STDIN;
    if (!outFile) outFile = stdout;

    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_NoDB_Init(NULL);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: NSS_NoDB_Init failed (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
	exit(1);
    }
    SECU_RegisterDynamicOids();

    rv = SECU_ReadDERFromFile(&der, inFile, ascii, PR_FALSE);
    if (rv != SECSuccess) {
	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
	exit(1);
    }

    /* Data is untyped, using the specified type */
    data.data = der.data;
    data.len = der.len;

    /* Pretty print it */
    if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE) == 0) {
	rv = SECU_PrintSignedData(outFile, &data, "Certificate", 0,
			     SECU_PrintCertificate);
    } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_ID) == 0) {
        PRBool saveWrapeState = SECU_GetWrapEnabled();
        SECU_EnableWrap(PR_FALSE);
        rv = SECU_PrintSignedContent(outFile, &data, 0, 0,
                                     SECU_PrintDumpDerIssuerAndSerial);
        SECU_EnableWrap(saveWrapeState);
    } else if (PORT_Strcmp(typeTag, SEC_CT_CERTIFICATE_REQUEST) == 0) {
	rv = SECU_PrintSignedData(outFile, &data, "Certificate Request", 0,
			     SECU_PrintCertificateRequest);
    } else if (PORT_Strcmp (typeTag, SEC_CT_CRL) == 0) {
	rv = SECU_PrintSignedData (outFile, &data, "CRL", 0, SECU_PrintCrl);
#ifdef HAVE_EPV_TEMPLATE
    } else if (PORT_Strcmp(typeTag, SEC_CT_PRIVATE_KEY) == 0) {
	rv = SECU_PrintPrivateKey(outFile, &data, "Private Key", 0);
#endif
    } else if (PORT_Strcmp(typeTag, SEC_CT_PUBLIC_KEY) == 0) {
	rv = SECU_PrintSubjectPublicKeyInfo(outFile, &data, "Public Key", 0);
    } else if (PORT_Strcmp(typeTag, SEC_CT_PKCS7) == 0) {
	rv = SECU_PrintPKCS7ContentInfo(outFile, &data,
					"PKCS #7 Content Info", 0);
    } else if (PORT_Strcmp(typeTag, SEC_CT_NAME) == 0) {
	rv = SECU_PrintDERName(outFile, &data, "Name", 0);
    } else {
	fprintf(stderr, "%s: don't know how to print out '%s' files\n",
		progName, typeTag);
	SECU_PrintAny(outFile, &data, "File contains", 0);
	return -1;
    }

    if (inFile != PR_STDIN)
	PR_Close(inFile);
    PORT_Free(der.data);
    if (rv) {
	fprintf(stderr, "%s: problem converting data (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
    }
    if (NSS_Shutdown() != SECSuccess) {
	fprintf(stderr, "%s: NSS_Shutdown failed (%s)\n",
		progName, SECU_Strerror(PORT_GetError()));
	rv = SECFailure;
    }
    PR_Cleanup();
    return rv;
}
Exemple #26
0
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);
}
Exemple #27
0
/*
 * Decode the DER/BER-encoded item "data" as an OCSP response
 * and pretty-print the subfields.
 */
static SECStatus
print_response (FILE *out_file, SECItem *data, CERTCertDBHandle *handle)
{
    CERTOCSPResponse *response;
    int level = 0;

    PORT_Assert (out_file != NULL);
    PORT_Assert (data != NULL);
    if (out_file == NULL || data == NULL) {
	PORT_SetError (SEC_ERROR_INVALID_ARGS);
	return SECFailure;
    }

    response = CERT_DecodeOCSPResponse (data);
    if (response == NULL)
	return SECFailure;

    if (response->statusValue >= ocspResponse_min &&
	response->statusValue <= ocspResponse_max) {
	fprintf (out_file, "Response Status: %s\n",
		 responseStatusNames[response->statusValue]);
    } else {
	fprintf (out_file,
		 "Response Status: other (Status value %d out of defined range)\n",
		 (int)response->statusValue);
    }

    if (response->statusValue == ocspResponse_successful) {
	ocspResponseBytes *responseBytes = response->responseBytes;
	SECStatus sigStatus;
	CERTCertificate *signerCert = NULL;

	PORT_Assert (responseBytes != NULL);

	level++;
	fprintf (out_file, "Response Bytes:\n");
	SECU_PrintObjectID (out_file, &(responseBytes->responseType),
			    "Response Type", level);
	switch (response->responseBytes->responseTypeTag) {
	  case SEC_OID_PKIX_OCSP_BASIC_RESPONSE:
	    print_basic_response (out_file,
				  responseBytes->decodedResponse.basic,
				  level);
	    break;
	  default:
	    SECU_Indent (out_file, level);
	    fprintf (out_file, "Unknown response syntax\n");
	    break;
	}

	sigStatus = CERT_VerifyOCSPResponseSignature (response, handle,
						      NULL, &signerCert, NULL);
	SECU_Indent (out_file, level);
	fprintf (out_file, "Signature verification ");
	if (sigStatus != SECSuccess) {
	    fprintf (out_file, "failed: %s\n", SECU_Strerror (PORT_GetError()));
	} else {
	    fprintf (out_file, "succeeded.\n");
	    if (signerCert != NULL) {
		SECU_PrintName (out_file, &signerCert->subject, "Signer",
				level);
		CERT_DestroyCertificate (signerCert);
	    } else {
		SECU_Indent (out_file, level);
		fprintf (out_file, "No signer cert returned?\n");
	    }
	}
    } else {
	SECU_Indent (out_file, level);
	fprintf (out_file, "Unsuccessful response, no more information.\n");
    }

    CERT_DestroyOCSPResponse (response);
    return SECSuccess;
}
Exemple #28
0
/************************************************************************
 *
 * J a r W h o
 */
int
JarWho(char *filename)
{
    FILE *fp;

    JAR *jar;
    JAR_Context *ctx;

    int status;
    int retval = 0;

    JAR_Item *it;
    JAR_Cert *fing;

    CERTCertificate *cert, *prev = NULL;

    jar = JAR_new();

    if ((fp = fopen(filename, "r")) == NULL) {
        perror(filename);
        exit(ERRX);
    }
    fclose(fp);

    status = JAR_pass_archive(jar, jarArchGuess, filename, "some-url");

    if (status < 0 || jar->valid < 0) {
        PR_fprintf(outputFD,
                   "NOTE -- \"%s\" archive DID NOT PASS crypto verification.\n",
                   filename);
        retval = -1;
        if (jar->valid < 0 || status != -1) {
            const char *errtext;

            if (status >= JAR_BASE && status <= JAR_BASE_END) {
                errtext = JAR_get_error(status);
            } else {
                errtext = SECU_Strerror(PORT_GetError());
            }

            PR_fprintf(outputFD, "  (reported reason: %s)\n\n", errtext);
        }
    }

    PR_fprintf(outputFD, "\nSigner information:\n\n");

    ctx = JAR_find(jar, NULL, jarTypeSign);

    while (JAR_find_next(ctx, &it) >= 0) {
        fing = (JAR_Cert *)it->data;
        cert = fing->cert;

        if (cert) {
            if (prev == cert)
                break;

            if (cert->nickname)
                PR_fprintf(outputFD, "nickname: %s\n", cert->nickname);
            if (cert->subjectName)
                PR_fprintf(outputFD, "subject name: %s\n",
                           cert->subjectName);
            if (cert->issuerName)
                PR_fprintf(outputFD, "issuer name: %s\n", cert->issuerName);
        } else {
            PR_fprintf(outputFD, "no certificate could be found\n");
            retval = -1;
        }

        prev = cert;
    }

    JAR_find_end(ctx);

    JAR_destroy(jar);
    return retval;
}
Exemple #29
0
/*************************************************************************
 *
 * V e r i f y J a r
 */
int
VerifyJar(char *filename)
{
    FILE *fp;

    int ret;
    int status;
    int failed = 0;
    char *err;

    JAR *jar;
    JAR_Context *ctx;

    JAR_Item *it;

    jar = JAR_new();

    if ((fp = fopen(filename, "r")) == NULL) {
        perror(filename);
        exit(ERRX);
    } else
        fclose(fp);

    JAR_set_callback(JAR_CB_SIGNAL, jar, jar_cb);

    status = JAR_pass_archive(jar, jarArchGuess, filename, "some-url");

    if (status < 0 || jar->valid < 0) {
        failed = 1;
        PR_fprintf(outputFD,
                   "\nNOTE -- \"%s\" archive DID NOT PASS crypto verification.\n",
                   filename);
        if (status < 0) {
            const char *errtext;

            if (status >= JAR_BASE && status <= JAR_BASE_END) {
                errtext = JAR_get_error(status);
            } else {
                errtext = SECU_Strerror(PORT_GetError());
            }

            PR_fprintf(outputFD, "  (reported reason: %s)\n\n",
                       errtext);

            /* corrupt files should not have their contents listed */

            if (status == JAR_ERR_CORRUPT)
                return -1;
        }
        PR_fprintf(outputFD,
                   "entries shown below will have their digests checked only.\n");
        jar->valid = 0;
    } else
        PR_fprintf(outputFD,
                   "archive \"%s\" has passed crypto verification.\n", filename);

    if (verify_global(jar))
        failed = 1;

    PR_fprintf(outputFD, "\n");
    PR_fprintf(outputFD, "%16s   %s\n", "status", "path");
    PR_fprintf(outputFD, "%16s   %s\n", "------------", "-------------------");

    ctx = JAR_find(jar, NULL, jarTypeMF);

    while (JAR_find_next(ctx, &it) >= 0) {
        if (it && it->pathname) {
            rm_dash_r(TMP_OUTPUT);
            ret = JAR_verified_extract(jar, it->pathname, TMP_OUTPUT);
            /* if (ret < 0) printf ("error %d on %s\n", ret, it->pathname); */
            if (ret < 0)
                failed = 1;

            if (ret == JAR_ERR_PNF)
                err = "NOT PRESENT";
            else if (ret == JAR_ERR_HASH)
                err = "HASH FAILED";
            else
                err = "NOT VERIFIED";

            PR_fprintf(outputFD, "%16s   %s\n",
                       ret >= 0 ? "verified" : err, it->pathname);

            if (ret != 0 && ret != JAR_ERR_PNF && ret != JAR_ERR_HASH)
                PR_fprintf(outputFD, "      (reason: %s)\n",
                           JAR_get_error(ret));
        }
    }

    JAR_find_end(ctx);

    if (status < 0 || jar->valid < 0) {
        failed = 1;
        PR_fprintf(outputFD,
                   "\nNOTE -- \"%s\" archive DID NOT PASS crypto verification.\n",
                   filename);
        give_help(status);
    }

    JAR_destroy(jar);

    if (failed)
        return -1;
    return 0;
}
Exemple #30
0
char	*XP_GetString (int i)
{
    return SECU_Strerror (i);
}