Example #1
0
static Error
init_crypto(PRBool create, PRBool readOnly)
{

    PRUint32 flags = 0;
    SECStatus rv;
    Error retval;
    /* Open/create key database */

    if (readOnly)
        flags |= NSS_INIT_READONLY;
    if (nocertdb)
        flags |= NSS_INIT_NOCERTDB;
    rv = NSS_Initialize(SECU_ConfigDirectory(NULL), dbprefix, dbprefix,
                        secmodName, flags);
    if (rv != SECSuccess) {
        SECU_PrintPRandOSError(progName);
        retval = NSS_INITIALIZE_FAILED_ERR;
    } else
        retval = SUCCESS;

    return retval;
}
Example #2
0
int main(int argc, char **argv)
{
    CERTCertDBHandle *certHandle;
    PRFileDesc *inFile;
    PRFileDesc *inCrlInitFile = NULL;
    int generateCRL;
    int modifyCRL;
    int listCRL;
    int importCRL;
    int showFileCRL;
    int deleteCRL;
    int rv;
    char *nickName;
    char *url;
    char *dbPrefix = "";
    char *alg = NULL;
    char *outFile = NULL;
    char *slotName = NULL;
    int ascii = 0;
    int crlType;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus secstatus;
    PRInt32 decodeOptions = CRL_DECODE_DEFAULT_OPTIONS;
    PRInt32 importOptions = CRL_IMPORT_DEFAULT_OPTIONS;
    PRBool quiet = PR_FALSE;
    PRBool test = PR_FALSE;
    PRBool erase = PR_FALSE;
    PRInt32 i = 0;
    PRInt32 iterations = 1;
    PRBool readonly = PR_FALSE;

    secuPWData  pwdata          = { PW_NONE, 0 };

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

    rv = 0;
    deleteCRL = importCRL = listCRL = generateCRL = modifyCRL = showFileCRL = 0;
    inFile = NULL;
    nickName = url = NULL;
    certHandle = NULL;
    crlType = SEC_CRL_TYPE;
    /*
     * Parse command line arguments
     */
    optstate = PL_CreateOptState(argc, argv, "sqBCDGILMSTEP:f:d:i:h:n:p:t:u:r:aZ:o:c:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

          case 'T':
            test = PR_TRUE;
            break;

          case 'E':
            erase = PR_TRUE;
            break;

	  case 'B':
            importOptions |= CRL_IMPORT_BYPASS_CHECKS;
            break;

	  case 'G':
	    generateCRL = 1;
	    break;

          case 'M':
            modifyCRL = 1;
            break;

	  case 'D':
	      deleteCRL = 1;
	      break;

	  case 'I':
	      importCRL = 1;
	      break;
	      
	  case 'S':
	      showFileCRL = 1;
	      break;
	           
	  case 'C':
	  case 'L':
	      listCRL = 1;
	      break;

	  case 'P':
 	    dbPrefix = strdup(optstate->value);
 	    break;
              
	  case 'Z':
              alg = strdup(optstate->value);
              break;
              
	  case 'a':
	      ascii = 1;
	      break;

	  case 'c':
              inCrlInitFile = PR_Open(optstate->value, PR_RDONLY, 0);
              if (!inCrlInitFile) {
                  PR_fprintf(PR_STDERR, "%s: unable to open \"%s\" for reading\n",
                             progName, optstate->value);
                  PL_DestroyOptState(optstate);
                  return -1;
              }
              break;
	    
	  case 'd':
              SECU_ConfigDirectory(optstate->value);
              break;

	  case 'f':
	      pwdata.source = PW_FROMFILE;
	      pwdata.data = strdup(optstate->value);
	      break;

	  case 'h':
              slotName = strdup(optstate->value);
              break;

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

	  case 'o':
	    outFile = strdup(optstate->value);
	    break;
	    
	  case 'p':
	    decodeOptions |= CRL_DECODE_SKIP_ENTRIES;
	    break;

	  case 'r': {
	    const char* str = optstate->value;
	    if (str && atoi(str)>0)
		iterations = atoi(str);
	    }
	    break;
	    
	  case 't': {
	    crlType = atoi(optstate->value);
	    if (crlType != SEC_CRL_TYPE && crlType != SEC_KRL_TYPE) {
		PR_fprintf(PR_STDERR, "%s: invalid crl type\n", progName);
		PL_DestroyOptState(optstate);
		return -1;
	    }
	    break;

	  case 'q':
            quiet = PR_TRUE;
	    break;

	  case 'w':
	      pwdata.source = PW_PLAINTEXT;
	      pwdata.data = strdup(optstate->value);
	      break;

	  case 'u':
	    url = strdup(optstate->value);
	    break;

          }
	}
    }
    PL_DestroyOptState(optstate);

    if (deleteCRL && !nickName) Usage (progName);
    if (importCRL && !inFile) Usage (progName);
    if (showFileCRL && !inFile) Usage (progName);
    if ((generateCRL && !nickName) ||
        (modifyCRL && !inFile && !nickName)) Usage (progName);
    if (!(listCRL || deleteCRL || importCRL || showFileCRL || generateCRL ||
	  modifyCRL || test || erase)) Usage (progName);

    if (listCRL || showFileCRL) {
        readonly = PR_TRUE;
    }
    
    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);

    PK11_SetPasswordFunc(SECU_GetModulePassword);

    if (showFileCRL) {
	NSS_NoDB_Init(NULL);
    }
    else {
	secstatus = NSS_Initialize(SECU_ConfigDirectory(NULL), dbPrefix, dbPrefix,
				"secmod.db", readonly ? NSS_INIT_READONLY : 0);
	if (secstatus != SECSuccess) {
	    SECU_PrintPRandOSError(progName);
	    return -1;
	}
    }
    
    SECU_RegisterDynamicOids();

    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	SECU_PrintError(progName, "unable to open the cert db");	    	
	/*ignoring return value of NSS_Shutdown() as code returns -1*/
	(void) NSS_Shutdown();
	return (-1);
    }

    CRLGEN_InitCrlGenParserLock();

    for (i=0; i<iterations; i++) {
	/* Read in the private key info */
	if (deleteCRL) 
	    DeleteCRL (certHandle, nickName, crlType);
	else if (listCRL) {
	    rv = ListCRL (certHandle, nickName, crlType);
	}
	else if (importCRL) {
	    rv = ImportCRL (certHandle, url, crlType, inFile, importOptions,
			    decodeOptions, &pwdata);
	}
	else if (showFileCRL) {
	    rv = DumpCRL (inFile);
	} else if (generateCRL || modifyCRL) {
	    if (!inCrlInitFile)
		inCrlInitFile = PR_STDIN;
	    rv = GenerateCRL (certHandle, nickName, inCrlInitFile,
			      inFile, outFile, ascii,  slotName,
			      importOptions, alg, quiet,
			      decodeOptions, url, &pwdata,
			      modifyCRL);
	}
	else if (erase) {
	    /* list and delete all CRLs */
	    ListCRLNames (certHandle, crlType, PR_TRUE);
	}
#ifdef DEBUG
	else if (test) {
	    /* list and delete all CRLs */
	    ListCRLNames (certHandle, crlType, PR_TRUE);
	    /* list CRLs */
	    ListCRLNames (certHandle, crlType, PR_FALSE);
	    /* import CRL as a blob */
	    rv = ImportCRL (certHandle, url, crlType, inFile, importOptions,
			    decodeOptions, &pwdata);
	    /* list CRLs */
	    ListCRLNames (certHandle, crlType, PR_FALSE);
	}
#endif    
    }

    CRLGEN_DestroyCrlGenParserLock();

    if (NSS_Shutdown() != SECSuccess) {
        rv = SECFailure;
    }

    return (rv != SECSuccess);
}
Example #3
0
int
main (int argc, char **argv)
{
    int		 retval;
    PRFileDesc	*in_file;
    FILE	*out_file;	/* not PRFileDesc until SECU accepts it */
    int		 crequest, dresponse;
    int		 prequest, presponse;
    int		 ccert, vcert;
    const char	*db_dir, *date_str, *cert_usage_str, *name;
    const char	*responder_name, *responder_url, *signer_name;
    PRBool	 add_acceptable_responses, add_service_locator;
    SECItem	*data = NULL;
    PLOptState	*optstate;
    SECStatus	 rv;
    CERTCertDBHandle *handle = NULL;
    SECCertUsage cert_usage;
    PRTime	 verify_time;
    CERTCertificate *cert = NULL;
    PRBool ascii = PR_FALSE;

    retval = -1;		/* what we return/exit with on error */

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    in_file = PR_STDIN;
    out_file = stdout;

    crequest = 0;
    dresponse = 0;
    prequest = 0;
    presponse = 0;
    ccert = 0;
    vcert = 0;

    db_dir = NULL;
    date_str = NULL;
    cert_usage_str = NULL;
    name = NULL;
    responder_name = NULL;
    responder_url = NULL;
    signer_name = NULL;

    add_acceptable_responses = PR_FALSE;
    add_service_locator = PR_FALSE;

    optstate = PL_CreateOptState (argc, argv, "AHLPR:S:V:d:l:pr:s:t:u:w:");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return retval;
    }

    while (PL_GetNextOpt (optstate) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return retval;

	  case 'A':
	    add_acceptable_responses = PR_TRUE;
	    break;

	  case 'H':
	    long_usage (program_name);
	    return retval;

	  case 'L':
	    add_service_locator = PR_TRUE;
	    break;

	  case 'P':
	    presponse = 1;
	    break;

	  case 'R':
	    dresponse = 1;
	    name = optstate->value;
	    break;

	  case 'S':
	    ccert = 1;
	    name = optstate->value;
	    break;

	  case 'V':
	    vcert = 1;
	    name = optstate->value;
	    break;

	  case 'a':
	    ascii = PR_TRUE;
	    break;

	  case 'd':
	    db_dir = optstate->value;
	    break;

	  case 'l':
	    responder_url = optstate->value;
	    break;

	  case 'p':
	    prequest = 1;
	    break;

	  case 'r':
	    crequest = 1;
	    name = optstate->value;
	    break;

	  case 's':
	    signer_name = optstate->value;
	    break;

	  case 't':
	    responder_name = optstate->value;
	    break;

	  case 'u':
	    cert_usage_str = optstate->value;
	    break;

	  case 'w':
	    date_str = optstate->value;
	    break;
	}
    }

    PL_DestroyOptState(optstate);

    if ((crequest + dresponse + prequest + presponse + ccert + vcert) != 1) {
	PR_fprintf (PR_STDERR, "%s: must specify exactly one command\n\n",
		    program_name);
	short_usage (program_name);
	return retval;
    }

    if (vcert) {
	if (cert_usage_str == NULL) {
	    PR_fprintf (PR_STDERR, "%s: verification requires cert usage\n\n",
			program_name);
	    short_usage (program_name);
	    return retval;
	}

	rv = cert_usage_from_char (cert_usage_str, &cert_usage);
	if (rv != SECSuccess) {
	    PR_fprintf (PR_STDERR, "%s: invalid cert usage (\"%s\")\n\n",
			program_name, cert_usage_str);
	    long_usage (program_name);
	    return retval;
	}
    }

    if (ccert + vcert) {
	if (responder_url != NULL || responder_name != NULL) {
	    /*
	     * To do a full status check, both the URL and the cert name
	     * of the responder must be specified if either one is.
	     */
	    if (responder_url == NULL || responder_name == NULL) {
		if (responder_url == NULL)
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder location\n\n",
				program_name);
		else
		    PR_fprintf (PR_STDERR,
				"%s: must also specify responder name\n\n",
				program_name);
		short_usage (program_name);
		return retval;
	    }
	}

	if (date_str != NULL) {
	    rv = DER_AsciiToTime (&verify_time, (char *) date_str);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error converting time string");
		PR_fprintf (PR_STDERR, "\n");
		long_usage (program_name);
		return retval;
	    }
	} else {
	    verify_time = PR_Now();
	}
    }

    retval = -2;		/* errors change from usage to runtime */

    /*
     * Initialize the NSPR and Security libraries.
     */
    PR_Init (PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    db_dir = SECU_ConfigDirectory (db_dir);
    rv = NSS_Init (db_dir);
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	goto prdone;
    }
    SECU_RegisterDynamicOids();

    if (prequest + presponse) {
	MAKE_FILE_BINARY(stdin);
	data = read_file_into_item (in_file, siBuffer);
	if (data == NULL) {
	    SECU_PrintError (program_name, "problem reading input");
	    goto nssdone;
	}
    }

    if (crequest + dresponse + presponse + ccert + vcert) {
	handle = CERT_GetDefaultCertDB();
	if (handle == NULL) {
	    SECU_PrintError (program_name, "problem getting certdb handle");
	    goto nssdone;
	}

	/*
	 * It would be fine to do the enable for all of these commands,
	 * but this way we check that everything but an overall verify
	 * can be done without it.  That is, that the individual pieces
	 * work on their own.
	 */
	if (vcert) {
	    rv = CERT_EnableOCSPChecking (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name, "error enabling OCSP checking");
		goto nssdone;
	    }
	}

	if ((ccert + vcert) && (responder_name != NULL)) {
	    rv = CERT_SetOCSPDefaultResponder (handle, responder_url,
					       responder_name);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error setting default responder");
		goto nssdone;
	    }

	    rv = CERT_EnableOCSPDefaultResponder (handle);
	    if (rv != SECSuccess) {
		SECU_PrintError (program_name,
				 "error enabling default responder");
		goto nssdone;
	    }
	}
    }

#define NOTYET(opt)							\
	{								\
	    PR_fprintf (PR_STDERR, "%s not yet working\n", opt);	\
	    exit (-1);							\
	}

    if (name) {
        cert = find_certificate(handle, name, ascii);
    }

    if (crequest) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = create_request (out_file, handle, cert, add_service_locator,
			     add_acceptable_responses);
    } else if (dresponse) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = dump_response (out_file, handle, cert, responder_url);
    } else if (prequest) {
	rv = print_request (out_file, data);
    } else if (presponse) {
	rv = print_response (out_file, data, handle);
    } else if (ccert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = get_cert_status (out_file, handle, cert, name, verify_time);
    } else if (vcert) {
	if (signer_name != NULL) {
	    NOTYET("-s");
	}
	rv = verify_cert (out_file, handle, cert, name, cert_usage, verify_time);
    }

    if (rv != SECSuccess)
	SECU_PrintError (program_name, "error performing requested operation");
    else
	retval = 0;

nssdone:
    if (cert) {
        CERT_DestroyCertificate(cert);
    }

    if (data != NULL) {
	SECITEM_FreeItem (data, PR_TRUE);
    }

    if (handle != NULL) {
 	CERT_DisableOCSPDefaultResponder(handle);        
 	CERT_DisableOCSPChecking (handle);
    }

    if (NSS_Shutdown () != SECSuccess) {
	retval = 1;
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Example #4
0
int
main(int argc, char **argv)
{
    char *progName;
    FILE *inFile, *outFile;
    char *certName;
    CERTCertDBHandle *certHandle;
    struct recipient *recipients, *rcpt;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

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

    inFile = NULL;
    outFile = NULL;
    certName = NULL;
    recipients = NULL;
    rcpt = NULL;

    /*
     * Parse command line arguments
     * XXX This needs to be enhanced to allow selection of algorithms
     * and key sizes (or to look up algorithms and key sizes for each
     * recipient in the magic database).
     */
    optstate = PL_CreateOptState(argc, argv, "d:i:o:r:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

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

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

	  case 'r':
	    if (rcpt == NULL) {
		recipients = rcpt = PORT_Alloc (sizeof(struct recipient));
	    } else {
		rcpt->next = PORT_Alloc (sizeof(struct recipient));
		rcpt = rcpt->next;
	    }
	    if (rcpt == NULL) {
		fprintf(stderr, "%s: unable to allocate recipient struct\n",
			progName);
		return -1;
	    }
	    rcpt->nickname = strdup(optstate->value);
	    rcpt->cert = NULL;
	    rcpt->next = NULL;
	    break;
	}
    }

    if (!recipients) Usage(progName);

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

    /* Call the NSS initialization routines */
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
    	SECU_PrintPRandOSError(progName);
	return -1;
    }

    /* open cert database */
    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	return -1;
    }

    /* find certs */
    for (rcpt = recipients; rcpt != NULL; rcpt = rcpt->next) {
	rcpt->cert = CERT_FindCertByNickname(certHandle, rcpt->nickname);
	if (rcpt->cert == NULL) {
	    SECU_PrintError(progName,
			    "the cert for name \"%s\" not found in database",
			    rcpt->nickname);
	    return -1;
	}
    }

    if (EncryptFile(outFile, inFile, recipients, progName)) {
	SECU_PrintError(progName, "problem encrypting data");
	return -1;
    }

    return 0;
}
int
main(int argc, char **argv)
{
    char *progName;
    FILE *contentFile, *outFile;
    PRFileDesc *signatureFile;
    SECCertUsage certUsage = certUsageEmailSigner;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

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

    contentFile = NULL;
    signatureFile = NULL;
    outFile = NULL;

    /*
     * Parse command line arguments
     */
    optstate = PL_CreateOptState(argc, argv, "c:d:o:s:u:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

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

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    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 's':
	    signatureFile = PR_Open(optstate->value, PR_RDONLY, 0);
	    if (!signatureFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for reading\n",
			progName, optstate->value);
		return -1;
	    }
	    break;

	  case 'u': {
	    int usageType;

	    usageType = atoi (strdup(optstate->value));
	    if (usageType < certUsageSSLClient || usageType > certUsageAnyCA)
		return -1;
	    certUsage = (SECCertUsage)usageType;
	    break;
	  }
	      
	}
    }

    if (!contentFile) Usage (progName);
    if (!signatureFile) Usage (progName);
    if (!outFile) outFile = stdout;

    /* Call the NSS initialization routines */
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
    	SECU_PrintPRandOSError(progName);
	return -1;
    }

    if (HashDecodeAndVerify(outFile, contentFile, signatureFile,
			    certUsage, progName)) {
	SECU_PrintError(progName, "problem decoding/verifying signature");
	return -1;
    }

    if (NSS_Shutdown() != SECSuccess) {
        exit(1);
    }

    return 0;
}
Example #6
0
int
main(int argc, char **argv)
{
    char *progName;
    FILE *outFile;
    PRFileDesc *inFile;
    char *keyName = NULL;
    CERTCertDBHandle *certHandle;
    CERTCertificate *cert;
    PLOptState *optstate;
    PLOptStatus status;
    SECStatus rv;

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

    inFile = NULL;
    outFile = NULL;
    keyName = NULL;

    /*
     * Parse command line arguments
     */
    optstate = PL_CreateOptState(argc, argv, "ed:k:i:o:p:f:");
    while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    Usage(progName);
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    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 'k':
	    keyName = strdup(optstate->value);
	    break;

	  case 'o':
	    outFile = fopen(optstate->value, "wb");
	    if (!outFile) {
		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
			progName, optstate->value);
		return -1;
	    }
	    break;
	  case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = strdup (optstate->value);
            break;

	  case 'f':
              pwdata.source = PW_FROMFILE;
              pwdata.data = PORT_Strdup (optstate->value);
              break;
	}
    }

    if (!keyName) Usage(progName);

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

    /* Call the initialization routines */
    PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
	SECU_PrintPRandOSError(progName);
	goto loser;
    }

    PK11_SetPasswordFunc(SECU_GetModulePassword);

    /* open cert database */
    certHandle = CERT_GetDefaultCertDB();
    if (certHandle == NULL) {
	rv = SECFailure;
	goto loser;
    }

    /* find cert */
    cert = CERT_FindCertByNickname(certHandle, keyName);
    if (cert == NULL) {
	SECU_PrintError(progName,
		        "the corresponding cert for key \"%s\" does not exist",
			keyName);
	rv = SECFailure;
	goto loser;
    }

    if (SignFile(outFile, inFile, cert)) {
	SECU_PrintError(progName, "problem signing data");
	rv = SECFailure;
	goto loser;
    }

loser:
    if (pwdata.data) {
        PORT_Free(pwdata.data);
    }
    if (keyName) {
        PORT_Free(keyName);
    }
    if (cert) {
        CERT_DestroyCertificate(cert);
    }
    if (inFile && inFile != PR_STDIN) {
        PR_Close(inFile);
    }
    if (outFile && outFile != stdout) {
        fclose(outFile);
    }
    if (NSS_Shutdown() != SECSuccess) {
        SECU_PrintError(progName, "NSS shutdown:");
        exit(1);
    }

    return (rv != SECSuccess);
}
int main(int argc, char **argv)
{
    PRFileDesc *contentFile = NULL;
    PRFileDesc *signFile = PR_STDIN;
    FILE *	outFile  = stdout;
    char *	progName;
    SECStatus	rv;
    int 	result	 = 1;
    SECItem	pkcs7der, content;
    secuCommand signver;

    pkcs7der.data  = NULL;
    content.data = NULL;

    signver.numCommands = sizeof(signver_commands) /sizeof(secuCommandFlag);
    signver.numOptions = sizeof(signver_options) / sizeof(secuCommandFlag);
    signver.commands = signver_commands;
    signver.options = signver_options;

#ifdef XP_PC
    progName = strrchr(argv[0], '\\');
#else
    progName = strrchr(argv[0], '/');
#endif
    progName = progName ? progName+1 : argv[0];

    rv = SECU_ParseCommandLine(argc, argv, progName, &signver);
    if (SECSuccess != rv) {
	Usage(progName, outFile);
    }
    debugInfo = signver.options[opt_DebugInfo	    ].activated;
    verbose   = signver.options[opt_PrintWhyFailure ].activated;
    doVerify  = signver.commands[cmd_VerifySignedObj].activated;
    displayAll= signver.commands[cmd_DisplayAllPCKS7Info].activated;
    if (!doVerify && !displayAll)
	doVerify = PR_TRUE;

    /*	Set the certdb directory (default is ~/.netscape) */
    rv = NSS_Init(SECU_ConfigDirectory(signver.options[opt_CertDir].arg));
    if (rv != SECSuccess) {
	SECU_PrintPRandOSError(progName);
	return result;
    }
    /* below here, goto cleanup */
    SECU_RegisterDynamicOids();

    /*	Open the input content file. */
    if (signver.options[opt_InputDataFile].activated &&
	signver.options[opt_InputDataFile].arg) {
	if (PL_strcmp("-", signver.options[opt_InputDataFile].arg)) {
	    contentFile = PR_Open(signver.options[opt_InputDataFile].arg,
			       PR_RDONLY, 0);
	    if (!contentFile) {
		PR_fprintf(PR_STDERR,
			   "%s: unable to open \"%s\" for reading.\n",
			   progName, signver.options[opt_InputDataFile].arg);
		goto cleanup;
	    }
	} else
	    contentFile = PR_STDIN;
    }

    /*	Open the input signature file.	*/
    if (signver.options[opt_InputSigFile].activated &&
	signver.options[opt_InputSigFile].arg) {
	if (PL_strcmp("-", signver.options[opt_InputSigFile].arg)) {
	    signFile = PR_Open(signver.options[opt_InputSigFile].arg,
			       PR_RDONLY, 0);
	    if (!signFile) {
		PR_fprintf(PR_STDERR,
			   "%s: unable to open \"%s\" for reading.\n",
			   progName, signver.options[opt_InputSigFile].arg);
		goto cleanup;
	    }
	}
    }

    if (contentFile == PR_STDIN && signFile == PR_STDIN && doVerify) {
	PR_fprintf(PR_STDERR,
	    "%s: cannot read both content and signature from standard input\n",
		   progName);
	goto cleanup;
    }

    /*	Open|Create the output file.  */
    if (signver.options[opt_OutputFile].activated) {
	outFile = fopen(signver.options[opt_OutputFile].arg, "w");
	if (!outFile) {
	    PR_fprintf(PR_STDERR, "%s: unable to open \"%s\" for writing.\n",
		       progName, signver.options[opt_OutputFile].arg);
	    goto cleanup;
	}
    }

    /* read in the input files' contents */
    rv = SECU_ReadDERFromFile(&pkcs7der, signFile,
			      signver.options[opt_ASCII].activated);
    if (signFile != PR_STDIN)
	PR_Close(signFile);
    if (rv != SECSuccess) {
	SECU_PrintError(progName, "problem reading PKCS7 input");
	goto cleanup;
    }
    if (contentFile) {
	rv = SECU_FileToItem(&content, contentFile);
	if (contentFile != PR_STDIN)
	    PR_Close(contentFile);
	if (rv != SECSuccess)
	    content.data = NULL;
    }

    /* Signature Verification */
    if (doVerify) {
	SEC_PKCS7ContentInfo *cinfo;
	SEC_PKCS7SignedData *signedData;
	HASH_HashType digestType;
	PRBool contentIsSigned;

	cinfo = SEC_PKCS7DecodeItem(&pkcs7der, NULL, NULL, NULL, NULL,
				    NULL, NULL, NULL);
	if (cinfo == NULL) {
	    PR_fprintf(PR_STDERR, "Unable to decode PKCS7 data\n");
	    goto cleanup;
	}
	/* below here, goto done */

	contentIsSigned = SEC_PKCS7ContentIsSigned(cinfo);
	if (debugInfo) {
	    PR_fprintf(PR_STDERR, "Content is%s encrypted.\n",
		       SEC_PKCS7ContentIsEncrypted(cinfo) ? "" : " not");
	}
	if (debugInfo || !contentIsSigned) {
	    PR_fprintf(PR_STDERR, "Content is%s signed.\n",
		       contentIsSigned ? "" : " not");
	}

	if (!contentIsSigned)
	    goto done;

	signedData = cinfo->content.signedData;

	/* assume that there is only one digest algorithm for now */
	digestType = AlgorithmToHashType(signedData->digestAlgorithms[0]);
	if (digestType == HASH_AlgNULL) {
	    PR_fprintf(PR_STDERR, "Invalid hash algorithmID\n");
	    goto done;
	}
	if (content.data) {
	    SECCertUsage   usage = certUsageEmailSigner;
	    SECItem	   digest;
	    unsigned char  digestBuffer[HASH_LENGTH_MAX];

	    if (debugInfo)
		PR_fprintf(PR_STDERR, "contentToVerify=%s\n", content.data);

	    digest.data = digestBuffer;
	    digest.len	= sizeof digestBuffer;

	    if (DigestContent(&digest, &content, digestType)) {
		SECU_PrintError(progName, "Message digest computation failure");
		goto done;
	    }

	    if (debugInfo) {
		unsigned int i;
		PR_fprintf(PR_STDERR, "Data Digest=:");
		for (i = 0; i < digest.len; i++)
		    PR_fprintf(PR_STDERR, "%02x:", digest.data[i]);
		PR_fprintf(PR_STDERR, "\n");
	    }

	    fprintf(outFile, "signatureValid=");
	    PORT_SetError(0);
	    if (SEC_PKCS7VerifyDetachedSignature (cinfo, usage,
				   &digest, digestType, PR_FALSE)) {
		fprintf(outFile, "yes");
	    } else {
		fprintf(outFile, "no");
		if (verbose) {
		    fprintf(outFile, ":%s",
			    SECU_Strerror(PORT_GetError()));
		}
	    }
	    fprintf(outFile, "\n");
	    result = 0;
	}
done:
	SEC_PKCS7DestroyContentInfo(cinfo);
    }

    if (displayAll) {
	if (SV_PrintPKCS7ContentInfo(outFile, &pkcs7der))
	    result = 1;
    }

cleanup:
    SECITEM_FreeItem(&pkcs7der, PR_FALSE);
    SECITEM_FreeItem(&content, PR_FALSE);

    if (NSS_Shutdown() != SECSuccess) {
	result = 1;
    }

    return result;
}
Example #8
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    char	*program_name;
    char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    char  *output_file = NULL;	/* write new encrypted data here */
    char  *log_file = NULL;	/* write new encrypted data here */
    FILE	*inFile = stdin;
    FILE	*outFile = stdout;
    FILE	*logFile = NULL;
    PLOptStatus optstatus;
    SECItem	result;
    int		c;
    secuPWData  pwdata = { PW_NONE, NULL };

    result.data = 0;

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
    if (optstate == NULL) {
        SECU_PrintError (program_name, "PL_CreateOptState failed");
        return 1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
        switch (optstate->option) {
        case '?':
            short_usage (program_name);
            return 1;

        case 'H':
            long_usage (program_name);
            return 1;

        case 'd':
            SECU_ConfigDirectory(optstate->value);
            break;

        case 'i':
            input_file = PL_strdup(optstate->value);
            break;

        case 'o':
            output_file = PL_strdup(optstate->value);
            break;

        case 'l':
            log_file = PL_strdup(optstate->value);
            break;

        case 'f':
            pwdata.source = PW_FROMFILE;
            pwdata.data = PL_strdup(optstate->value);
            break;

        case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PL_strdup(optstate->value);
            break;

        }
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
        short_usage (program_name);
        return 1;
    }

    if (input_file) {
        inFile = fopen(input_file,"r");
        if (inFile == NULL) {
            perror(input_file);
            return 1;
        }
        PR_Free(input_file);
    }
    if (output_file) {
        outFile = fopen(output_file,"w+");
        if (outFile == NULL) {
            perror(output_file);
            return 1;
        }
        PR_Free(output_file);
    }
    if (log_file) {
        logFile = fopen(log_file,"w+");
        if (logFile == NULL) {
            perror(log_file);
            return 1;
        }
        PR_Free(log_file);
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
        SECU_PrintError (program_name, "NSS_Init failed");
        retval = 1;
        goto prdone;
    }

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */

    while ((c = getc(inFile)) != EOF) {
        if (c == 'M') {
            char *dataString = NULL;
            SECItem *inText;

            rv = getData(inFile, &dataString);
            if (!rv) {
                fputs(dataString,outFile);
                free(dataString);
                continue;
            }
            inText = NSSBase64_DecodeBuffer(NULL, NULL, dataString,
                                            strlen(dataString));
            if ((inText == NULL) || (inText->len == 0)) {
                if (logFile) {
                    fprintf(logFile,"Base 64 decode failed on <%s>\n",
                            dataString);
                    fprintf(logFile," Error %x: %s\n",PORT_GetError(),
                            SECU_Strerror(PORT_GetError()));
                }
                fputs(dataString,outFile);
                free(dataString);
                continue;
            }
            result.data = NULL;
            result.len  = 0;
            rv = PK11SDR_Decrypt(inText, &result, &pwdata);
            SECITEM_FreeItem(inText, PR_TRUE);
            if (rv != SECSuccess) {
                if (logFile) {
                    fprintf(logFile,"SDR decrypt failed on <%s>\n",
                            dataString);
                    fprintf(logFile," Error %x: %s\n",PORT_GetError(),
                            SECU_Strerror(PORT_GetError()));
                }
                fputs(dataString,outFile);
                free(dataString);
                SECITEM_ZfreeItem(&result, PR_FALSE);
                continue;
            }
            /* result buffer has no extra space for a NULL */
            fprintf(outFile, "%.*s", result.len, result.data);
            SECITEM_ZfreeItem(&result, PR_FALSE);
        } else {
            putc(c,outFile);
        }
    }

    fclose(outFile);
    fclose(inFile);
    if (logFile) {
        fclose(logFile);
    }

    if (NSS_Shutdown() != SECSuccess) {
        SECU_PrintError (program_name, "NSS_Shutdown failed");
        exit(1);
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Example #9
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    char	*program_name;
    char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    char  *output_file = NULL;	/* write new encrypted data here */
    char  *log_file = NULL;	/* write new encrypted data here */
    FILE	*inFile = stdin;
    FILE	*outFile = stdout;
    FILE	*logFile = NULL;
    PLOptStatus optstatus;
    secuPWData  pwdata = { PW_NONE, NULL };


    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return 1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return 1;

	  case 'H':
	    long_usage (program_name);
	    return 1;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

          case 'i':
            input_file = PL_strdup(optstate->value);
            break;

          case 'o':
            output_file = PL_strdup(optstate->value);
            break;

          case 'l':
            log_file = PL_strdup(optstate->value);
            break;

          case 'f':
            pwdata.source = PW_FROMFILE;
            pwdata.data = PL_strdup(optstate->value);
            break;

          case 'p':
            pwdata.source = PW_PLAINTEXT;
            pwdata.data = PL_strdup(optstate->value);
            break;

	}
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
	short_usage (program_name);
	return 1;
    }

    if (input_file) {
        inFile = fopen(input_file,"r");
        if (inFile == NULL) {
	    perror(input_file);
	    return 1;
        }
        PR_Free(input_file);
    }
    if (output_file) {
        outFile = fopen(output_file,"w+");
        if (outFile == NULL) {
	    perror(output_file);
	    return 1;
        }
        PR_Free(output_file);
    }
    if (log_file) {
	if (log_file[0] == '-')
	    logFile = stderr;
	else
	    logFile = fopen(log_file,"w+");
	if (logFile == NULL) {
	    perror(log_file);
	    return 1;
	}
        PR_Free(log_file);
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);
    rv = NSS_Init(SECU_ConfigDirectory(NULL));
    if (rv != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Init failed");
	retval = 1;
	goto prdone;
    }

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */
    while (fgets(dataString, sizeof dataString, inFile)) {
	unsigned char c = dataString[0];

	if (c == 'M' && isBase64(dataString)) {
	    doDecrypt(dataString, outFile, logFile, &pwdata);
        } else if (c == '~' && isBase64(dataString + 1)) {
	    doDecode(dataString, outFile, logFile);
	} else {
	    fputs(dataString, outFile);
	}
    }
    if (pwdata.data)
    	PR_Free(pwdata.data);

    fclose(outFile);
    fclose(inFile);
    if (logFile && logFile != stderr) {
	fclose(logFile);
    }

    if (NSS_Shutdown() != SECSuccess) {
	SECU_PrintError (program_name, "NSS_Shutdown failed");
        exit(1);
    }

prdone:
    PR_Cleanup ();
    return retval;
}
Example #10
0
/*************************************************************************
 *
 * m a i n
 */
int
main(int argc, char* argv[])
{
    int errcode = SUCCESS;
    PRBool createdb, readOnly;
#define STDINBUF_SIZE 80
    char stdinbuf[STDINBUF_SIZE];

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

    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);

    if (parse_args(argc, argv) != SUCCESS) {
        usage();
        errcode = INVALID_USAGE_ERR;
        goto loser;
    }

    if (verify_params() != SUCCESS) {
        usage();
        errcode = INVALID_USAGE_ERR;
        goto loser;
    }

    if (command == NO_COMMAND) {
        PR_fprintf(PR_STDERR, errStrings[NO_COMMAND_ERR]);
        usage();
        errcode = INVALID_USAGE_ERR;
        goto loser;
    }

    /* Set up crypto stuff */
    createdb = command == CREATE_COMMAND;
    readOnly = ((command == LIST_COMMAND) ||
                (command == CHKFIPS_COMMAND) ||
                (command == RAW_LIST_COMMAND));

    /* Make sure browser is not running if we're writing to a database */
    /* Do this before initializing crypto */
    if (!readOnly && !force) {
        char* response;

        PR_fprintf(PR_STDOUT, msgStrings[BROWSER_RUNNING_MSG]);
        if (!PR_fgets(stdinbuf, STDINBUF_SIZE, PR_STDIN)) {
            PR_fprintf(PR_STDERR, errStrings[STDIN_READ_ERR]);
            errcode = STDIN_READ_ERR;
            goto loser;
        }
        if ((response = strtok(stdinbuf, " \r\n\t"))) {
            if (!PL_strcasecmp(response, "q")) {
                PR_fprintf(PR_STDOUT, msgStrings[ABORTING_MSG]);
                errcode = SUCCESS;
                goto loser;
            }
        }
        PR_fprintf(PR_STDOUT, "\n");
    }

    errcode = check_crypto(createdb, readOnly);
    if (errcode != SUCCESS) {
        goto loser;
    }

    if ((command == RAW_LIST_COMMAND) || (command == RAW_ADD_COMMAND)) {
        if (!moduleName) {
            char *readOnlyStr, *noCertDBStr, *sep;
            if (!secmodName)
                secmodName = "secmod.db";
            if (!dbprefix)
                dbprefix = "";
            sep = ((command == RAW_LIST_COMMAND) && nocertdb) ? "," : " ";
            readOnlyStr = (command == RAW_LIST_COMMAND) ? "readOnly" : "";
            noCertDBStr = nocertdb ? "noCertDB" : "";
            SECU_ConfigDirectory(dbdir);

            moduleName = PR_smprintf(
                "name=\"NSS default Module DB\" parameters=\"configdir=%s certPrefix=%s "
                "keyPrefix=%s secmod=%s flags=%s%s%s\" NSS=\"flags=internal,moduleDB,"
                "moduleDBOnly,critical\"",
                SECU_ConfigDirectory(NULL), dbprefix, dbprefix,
                secmodName, readOnlyStr, sep, noCertDBStr);
        }
        if (command == RAW_LIST_COMMAND) {
            errcode = RawListModule(moduleName);
        } else {
            PORT_Assert(moduleSpec);
            errcode = RawAddModule(moduleName, moduleSpec);
        }
        goto loser;
    }

    errcode = init_crypto(createdb, readOnly);
    if (errcode != SUCCESS) {
        goto loser;
    }

    errcode = LoadMechanismList();
    if (errcode != SUCCESS) {
        goto loser;
    }

    /* Execute the command */
    switch (command) {
        case ADD_COMMAND:
            errcode = AddModule(moduleName, libFile, ciphers, mechanisms, secmodString);
            break;
        case CHANGEPW_COMMAND:
            errcode = ChangePW(tokenName, pwFile, newpwFile);
            break;
        case CREATE_COMMAND:
            /* The work was already done in init_crypto() */
            break;
        case DEFAULT_COMMAND:
            errcode = SetDefaultModule(moduleName, slotName, mechanisms);
            break;
        case DELETE_COMMAND:
            errcode = DeleteModule(moduleName);
            break;
        case DISABLE_COMMAND:
            errcode = EnableModule(moduleName, slotName, PR_FALSE);
            break;
        case ENABLE_COMMAND:
            errcode = EnableModule(moduleName, slotName, PR_TRUE);
            break;
        case FIPS_COMMAND:
            errcode = FipsMode(fipsArg);
            break;
        case CHKFIPS_COMMAND:
            errcode = ChkFipsMode(fipsArg);
            break;
        case JAR_COMMAND:
            Pk11Install_SetErrorHandler(install_error);
            errcode = Pk11Install_DoInstall(jarFile, installDir, tempDir,
                                            PR_STDOUT, force, nocertdb);
            break;
        case LIST_COMMAND:
            if (moduleName) {
                errcode = ListModule(moduleName);
            } else {
                errcode = ListModules();
            }
            break;
        case UNDEFAULT_COMMAND:
            errcode = UnsetDefaultModule(moduleName, slotName, mechanisms);
            break;
        default:
            PR_fprintf(PR_STDERR, "This command is not supported yet.\n");
            errcode = INVALID_USAGE_ERR;
            break;
    }

    if (NSS_Shutdown() != SECSuccess) {
        exit(1);
    }

loser:
    PR_Cleanup();
    return errcode;
}
Example #11
0
/********************************************************************
 *
 * i n i t _ c r y p t o
 *
 * Does crypto initialization that all commands will require.
 * If -nocertdb option is specified, don't open key or cert db (we don't
 * need them if we aren't going to be verifying signatures).  This is
 * because serverland doesn't always have cert and key database files
 * available.
 *
 * This function is ill advised. Names and locations of databases are
 * private to NSS proper. Such functions only confuse other users.
 *
 */
static Error
check_crypto(PRBool create, PRBool readOnly)
{
    char* dir;
    char* moddbname = NULL;
    Error retval;
    static const char multiaccess[] = { "multiaccess:" };

    dir = SECU_ConfigDirectory(dbdir); /* dir is never NULL */
    if (dir[0] == '\0') {
        PR_fprintf(PR_STDERR, errStrings[NO_DBDIR_ERR]);
        retval = NO_DBDIR_ERR;
        goto loser;
    }
    if (strncmp(dir, multiaccess, sizeof multiaccess - 1) == 0) {
        /* won't attempt to handle the multiaccess case. */
        return SUCCESS;
    }
#ifdef notdef
    /* Make sure db directory exists and is readable */
    if (PR_Access(dir, PR_ACCESS_EXISTS) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dir);
        retval = DIR_DOESNT_EXIST_ERR;
        goto loser;
    } else if (PR_Access(dir, PR_ACCESS_READ_OK) != PR_SUCCESS) {
        PR_fprintf(PR_STDERR, errStrings[DIR_NOT_READABLE_ERR], dir);
        retval = DIR_NOT_READABLE_ERR;
        goto loser;
    }

    if (secmodName == NULL) {
        secmodName = "secmod.db";
    }

    moddbname = PR_smprintf("%s/%s", dir, secmodName);
    if (!moddbname)
        return OUT_OF_MEM_ERR;

    /* Check for the proper permissions on databases */
    if (create) {
        /* Make sure dbs don't already exist, and the directory is
            writeable */
        if (PR_Access(moddbname, PR_ACCESS_EXISTS) == PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[FILE_ALREADY_EXISTS_ERR],
                       moddbname);
            retval = FILE_ALREADY_EXISTS_ERR;
            goto loser;
        } else if (PR_Access(dir, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[DIR_NOT_WRITEABLE_ERR], dir);
            retval = DIR_NOT_WRITEABLE_ERR;
            goto loser;
        }
    } else {
        /* Make sure dbs are readable and writeable */
        if (PR_Access(moddbname, PR_ACCESS_READ_OK) != PR_SUCCESS) {
            PR_fprintf(PR_STDERR, errStrings[FILE_NOT_READABLE_ERR], moddbname);
            retval = FILE_NOT_READABLE_ERR;
            goto loser;
        }

        /* Check for write access if we'll be making changes */
        if (!readOnly) {
            if (PR_Access(moddbname, PR_ACCESS_WRITE_OK) != PR_SUCCESS) {
                PR_fprintf(PR_STDERR, errStrings[FILE_NOT_WRITEABLE_ERR],
                           moddbname);
                retval = FILE_NOT_WRITEABLE_ERR;
                goto loser;
            }
        }
        PR_fprintf(PR_STDOUT, msgStrings[USING_DBDIR_MSG],
                   SECU_ConfigDirectory(NULL));
    }
#endif
    retval = SUCCESS;
loser:
    if (moddbname) {
        PR_Free(moddbname);
    }
    return retval;
}
Example #12
0
int
main (int argc, char **argv)
{
    int		 retval = 0;  /* 0 - test succeeded.  -1 - test failed */
    SECStatus	 rv;
    PLOptState	*optstate;
    PLOptStatus  optstatus;
    char	*program_name;
    const char  *input_file = NULL; 	/* read encrypted data from here (or create) */
    const char  *output_file = NULL;	/* write new encrypted data here */
    const char  *value = default_value;	/* Use this for plaintext */
    SECItem     data;
    SECItem     result = {0, 0, 0};
    SECItem     text;
    PRBool      ascii = PR_FALSE;
    secuPWData  pwdata = { PW_NONE, 0 };

    pr_stderr = PR_STDERR;
    result.data = 0;
    text.data = 0; text.len = 0;

    program_name = PL_strrchr(argv[0], '/');
    program_name = program_name ? (program_name + 1) : argv[0];

    optstate = PL_CreateOptState (argc, argv, "?Had:i:o:t:vf:p:");
    if (optstate == NULL) {
	SECU_PrintError (program_name, "PL_CreateOptState failed");
	return -1;
    }

    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
	switch (optstate->option) {
	  case '?':
	    short_usage (program_name);
	    return retval;

	  case 'H':
	    long_usage (program_name);
	    return retval;

	  case 'a':
	    ascii = PR_TRUE;
	    break;

	  case 'd':
	    SECU_ConfigDirectory(optstate->value);
	    break;

          case 'i':
            input_file = optstate->value;
            break;

          case 'o':
            output_file = optstate->value;
            break;

          case 't':
            value = optstate->value;
            break;

	  case 'f':
	    if (pwdata.data) {
		PORT_Free(pwdata.data);
		short_usage(program_name);
		return -1;
	    }
	    pwdata.source = PW_FROMFILE;
	    pwdata.data = PORT_Strdup(optstate->value);
	    break;

	  case 'p':
	    if (pwdata.data) {
		PORT_Free(pwdata.data);
		short_usage(program_name);
		return -1;
	    }
	    pwdata.source = PW_PLAINTEXT;
	    pwdata.data = PORT_Strdup(optstate->value);
	    break;

          case 'v':
            verbose = PR_TRUE;
            break;
	}
    }
    PL_DestroyOptState(optstate);
    if (optstatus == PL_OPT_BAD) {
	short_usage (program_name);
	return -1;
    }
    if (!output_file && !input_file && value == default_value) {
	short_usage (program_name);
	PR_fprintf (pr_stderr, "Must specify at least one of -t, -i or -o \n");
	return -1;
    }

    /*
     * Initialize the Security libraries.
     */
    PK11_SetPasswordFunc(SECU_GetModulePassword);

    if (output_file) {
	rv = NSS_InitReadWrite(SECU_ConfigDirectory(NULL));
    } else {
	rv = NSS_Init(SECU_ConfigDirectory(NULL));
    }
    if (rv != SECSuccess) {
	SECU_PrintError(program_name, "NSS_Init failed");
	retval = -1;
	goto prdone;
    }

    /* Convert value into an item */
    data.data = (unsigned char *)value;
    data.len = strlen(value);

    /* Get the encrypted result, either from the input file
     * or from encrypting the plaintext value
     */
    if (input_file)
    {
      if (verbose) printf("Reading data from %s\n", input_file);

      if (!strcmp(input_file, "-")) {
	retval = readStdin(&result);
        ascii = PR_TRUE;
      } else {
        retval = readInputFile(input_file, &result);
      }
      if (retval != 0) 
	goto loser;
      if (ascii) {
	/* input was base64 encoded.  Decode it. */
	SECItem newResult = {0, 0, 0};
	SECItem *ok = NSSBase64_DecodeBuffer(NULL, &newResult, 
	                       (const char *)result.data, result.len);
	if (!ok) {
	  SECU_PrintError(program_name, "Base 64 decode failed");
	  retval = -1;
	  goto loser;
	}
	SECITEM_ZfreeItem(&result, PR_FALSE);
	result = *ok;
      }
    }
    else
    {
      SECItem keyid = { 0, 0, 0 };
      SECItem outBuf = { 0, 0, 0 };
      PK11SlotInfo *slot = NULL;

      /* sigh, initialize the key database */
      slot = PK11_GetInternalKeySlot();
      if (slot && PK11_NeedUserInit(slot)) {
	switch (pwdata.source) {
	case PW_FROMFILE:
	    rv = SECU_ChangePW(slot, 0, pwdata.data);
	    break;
	case PW_PLAINTEXT:
	    rv = SECU_ChangePW(slot, pwdata.data, 0);
	    break;
	default:
            rv = SECU_ChangePW(slot, "", 0);
	    break;
	}
        if (rv != SECSuccess) {
            SECU_PrintError(program_name, "Failed to initialize slot \"%s\"",
                                    PK11_GetSlotName(slot));
            return SECFailure;
        }
      }
      if (slot) {
	PK11_FreeSlot(slot);
      }

      rv = PK11SDR_Encrypt(&keyid, &data, &result, &pwdata);
      if (rv != SECSuccess) {
        if (verbose) 
	  SECU_PrintError(program_name, "Encrypt operation failed\n");
        retval = -1;
        goto loser;
      }

      if (verbose) printf("Encrypted result is %d bytes long\n", result.len);

      if (!strcmp(output_file, "-")) {
        ascii = PR_TRUE;
      }

      if (ascii) {
      	/* base64 encode output. */
	char * newResult = NSSBase64_EncodeItem(NULL, NULL, 0, &result);
	if (!newResult) {
	  SECU_PrintError(program_name, "Base 64 encode failed\n");
	  retval = -1;
	  goto loser;
	}
	outBuf.data = (unsigned char *)newResult;
	outBuf.len  = strlen(newResult);
	if (verbose) 
	  printf("Base 64 encoded result is %d bytes long\n", outBuf.len);
      } else {
	outBuf = result;
      }

      /* -v printf("Result is %.*s\n", text.len, text.data); */
      if (output_file) {
         PRFileDesc *file;
         PRInt32 count;

         if (verbose) printf("Writing result to %s\n", output_file);
	 if (!strcmp(output_file, "-")) {
	   file = PR_STDOUT;
	 } else {
	   /* Write to file */
	   file = PR_Open(output_file, PR_CREATE_FILE|PR_WRONLY, 0666);
	 }
         if (!file) {
            if (verbose) 
		SECU_PrintError(program_name, 
                                "Open of output file %s failed\n",
                                output_file);
            retval = -1;
            goto loser;
         }

         count = PR_Write(file, outBuf.data, outBuf.len);

	 if (file == PR_STDOUT) {
	   puts("");
	 } else {
	   PR_Close(file);
	 }

         if (count != outBuf.len) {
           if (verbose) SECU_PrintError(program_name, "Write failed\n");
           retval = -1;
           goto loser;
         }
	 if (ascii) {
	   free(outBuf.data);
	 }
      }
    }

    /* Decrypt the value */
    rv = PK11SDR_Decrypt(&result, &text, &pwdata);
    if (rv != SECSuccess) {
      if (verbose) SECU_PrintError(program_name, "Decrypt operation failed\n");
      retval = -1; 
      goto loser;
    }

    if (verbose) printf("Decrypted result is \"%.*s\"\n", text.len, text.data);

    /* Compare to required value */
    if (text.len != data.len || memcmp(data.data, text.data, text.len) != 0)
    {
      if (verbose) PR_fprintf(pr_stderr, "Comparison failed\n");
      retval = -1;
      goto loser;
    }

loser:
    if (text.data) SECITEM_ZfreeItem(&text, PR_FALSE);
    if (result.data) SECITEM_ZfreeItem(&result, PR_FALSE);
    if (NSS_Shutdown() != SECSuccess) {
       exit(1);
    }

prdone:
    PR_Cleanup ();
    if (pwdata.data) {
	PORT_Free(pwdata.data);
    }
    return retval;
}
Example #13
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;
}