コード例 #1
0
int main(int argc, char** argv)
{
    int ret;
    int encryptedSz, decryptedSz;
    word32 certSz, keySz;

    byte cert[2048];
    byte key[2048];
    byte encrypted[2048];
    byte decrypted[2048];
    
#ifdef DEBUG_WOLFSSL
    wolfSSL_Debugging_ON();
#endif

    certSz = sizeof(cert);
    keySz = sizeof(key);
    ret = load_certs(cert, &certSz, key, &keySz);
    if (ret != 0)
        return -1;

    /* no attributes */
    encryptedSz = signedData_sign_noattrs(cert, certSz, key, keySz,
                                          encrypted, sizeof(encrypted));
    if (encryptedSz < 0)
        return -1;

    decryptedSz = signedData_verify(encrypted, encryptedSz,
                                    cert, certSz, key, keySz,
                                    decrypted, sizeof(decrypted));
    if (decryptedSz < 0)
        return -1;

    /* default attributes + messageType attribute */
    encryptedSz = signedData_sign_attrs(cert, certSz, key, keySz,
                                        encrypted, sizeof(encrypted));
    if (encryptedSz < 0)
        return -1;

    decryptedSz = signedData_verify(encrypted, encryptedSz,
                                    cert, certSz, key, keySz,
                                    decrypted, sizeof(decrypted));
    if (decryptedSz < 0)
        return -1;

    (void)argc;
    (void)argv;

    return 0;
}
コード例 #2
0
int main(int argc, char** argv)
{
    int ret;
    int encryptedSz, decryptedSz;
    word32 certSz, keySz;

    byte cert[2048];
    byte key[2048];
    byte encrypted[1024];
    byte decrypted[1024];
    
#ifdef DEBUG_WOLFSSL
    wolfSSL_Debugging_ON();
#endif

    certSz = sizeof(cert);
    keySz = sizeof(key);
    ret = load_certs(cert, &certSz, key, &keySz);
    if (ret != 0)
        return -1;

    encryptedSz = authEnvelopedData_encrypt(cert, certSz, key, keySz,
                                            encrypted, sizeof(encrypted));
    if (encryptedSz < 0)
        return -1;

#ifdef DEBUG_WOLFSSL
    printf("AuthEnvelopedData DER (%d byte):\n", encryptedSz);
    WOLFSSL_BUFFER(encrypted, encryptedSz);
#endif

    decryptedSz = authEnvelopedData_decrypt(encrypted, encryptedSz,
                                            cert, certSz, key, keySz,
                                            decrypted, sizeof(decrypted));
    if (decryptedSz < 0)
        return -1;

#ifdef DEBUG_WOLFSSL
    printf("Decrypted content (%d byte):\n", decryptedSz);
    WOLFSSL_BUFFER(decrypted, decryptedSz);
#endif

    (void)argc;
    (void)argv;

    return 0;
}
コード例 #3
0
CONN *establish_connection(char *addr, char *port)
{
    // Blank connection structure
    CONN *conn = malloc(sizeof (CONN));
    // Initialise connection
    init_conn(conn);
    // Load certificates
    load_certs(conn);
    // Create new SSL structure
    conn->ssl = SSL_new(conn->ctx);
    
    struct addrinfo hints, *res;
    
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    
    getaddrinfo(addr, port, &hints, &res);
    
    conn->sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    
    // Connect to server
    if(connect(conn->sd, res->ai_addr, res->ai_addrlen) != 0) {
        perror("connection");
    }
    
    // Set BIO into SSL structure
    conn->bio = BIO_new_socket(conn->sd, BIO_NOCLOSE);
    SSL_set_bio(conn->ssl, conn->bio, conn->bio);
    
    // Perform handshake
    if(SSL_connect(conn->ssl) != 1) {
        perror("handshake\n");
    }
    
    printf("Connection Established\n");
    return conn;
}
コード例 #4
0
char *Pem2Pfx(char *pemFile, char *pemPass)
{
    BIO *in=NULL, *out = NULL;
	char tempDirPath[MAX_PATH];
	char baseFileName[MAX_PATH];
	char *retFileName = NULL;
	EVP_PKEY *key = NULL;
	STACK_OF(PKCS12_SAFEBAG) *bags = NULL;
	STACK_OF(PKCS7) *safes = NULL;
	PKCS12_SAFEBAG *bag = NULL;
	PKCS8_PRIV_KEY_INFO *p8 = NULL;
	PKCS7 *authsafe = NULL;
	X509 *ucert = NULL;
	STACK_OF(X509) *certs=NULL;
	char *catmp = NULL;
	int i;
	unsigned char keyid[EVP_MAX_MD_SIZE];
	unsigned int keyidlen = 0;
	char *name = NULL;
    STACK *canames = NULL;
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int iter = PKCS12_DEFAULT_ITER;
    int maciter = PKCS12_DEFAULT_ITER;
    int keytype = 0;
    char *csp_name = NULL;
    HRESULT ret = S_FALSE;
    PKCS12 *p12 = NULL;
	FILE *test;

    apps_startup();

    enc = EVP_des_ede3_cbc();

	app_RAND_load_file(NULL, bio_err, FALSE);
    ERR_load_crypto_strings();

	in = BIO_new_file(pemFile, "rb");
    if (!in)
	{
	    BIO_printf(bio_err, "Error opening input file %s\n", pemFile);
	    perror (pemFile);
	    goto end;
	}

	// Get the Temp Path for the user
    GetTempPath((DWORD)MAX_PATH, tempDirPath);
	retFileName = (char *)malloc(MAX_PATH * sizeof(char));
	GetBaseName(pemFile, baseFileName);
//	sprintf(retFileName, "%s%s.pfx", "C:\\Temp\\Debug\\", baseFileName);
	sprintf(retFileName, "%s%s.pfx", tempDirPath, baseFileName);

	out = BIO_new_file(retFileName, "wb");
	if (!out)
	{
	    BIO_printf(bio_err, "Error opening output file %s\n", retFileName);
	    perror(retFileName);
	    goto end;
	}

	key = load_key(bio_err, pemFile, FORMAT_PEM, 1, pemPass, NULL, "private key");
	if (!key)
		goto end;

	/* Load in all certs in input file */
	if(!(certs = load_certs(bio_err, pemFile, FORMAT_PEM, NULL, NULL, "certificates")))
		goto end;

	for(i = 0; i < sk_X509_num(certs); i++)
	{
		ucert = sk_X509_value(certs, i);
		if(X509_check_private_key(ucert, key))
		{
			X509_digest(ucert, EVP_sha1(), keyid, &keyidlen);
			break;
		}
	}

	if(!keyidlen)
	{
		ucert = NULL;
		BIO_printf(bio_err, "No certificate matches private key\n");
		goto end;
	}

	bags = sk_PKCS12_SAFEBAG_new_null();

	/* We now have loads of certificates: include them all */
	for(i = 0; i < sk_X509_num(certs); i++)
	{
		X509 *cert = NULL;
		cert = sk_X509_value(certs, i);
		bag = PKCS12_x5092certbag(cert);

		/* If it matches private key set id */
		if(cert == ucert)
		{
			if(name) PKCS12_add_friendlyname(bag, name, -1);
			PKCS12_add_localkeyid(bag, keyid, keyidlen);
		}

		else if((catmp = sk_shift(canames))) 
			PKCS12_add_friendlyname(bag, catmp, -1);

		sk_PKCS12_SAFEBAG_push(bags, bag);
	}

	sk_X509_pop_free(certs, X509_free);
	certs = NULL;

	/* Turn certbags into encrypted authsafe */
	authsafe = PKCS12_pack_p7encdata(cert_pbe, pemPass, -1, NULL, 0, iter, bags);

	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;

	if (!authsafe)
	{
		ERR_print_errors(bio_err);
		goto end;
	}

	safes = sk_PKCS7_new_null();
	sk_PKCS7_push(safes, authsafe);

	/* Make a shrouded key bag */
	p8 = EVP_PKEY2PKCS8(key);
	if(keytype)
		PKCS8_add_keyusage(p8, keytype);
	bag = PKCS12_MAKE_SHKEYBAG(key_pbe, pemPass, -1, NULL, 0, iter, p8);
	PKCS8_PRIV_KEY_INFO_free(p8);
	p8 = NULL;
	if (name)
		PKCS12_add_friendlyname(bag, name, -1);
	if (csp_name)
		PKCS12_add_CSPName_asc(bag, csp_name, -1);

	PKCS12_add_localkeyid (bag, keyid, keyidlen);
	bags = sk_PKCS12_SAFEBAG_new_null();
	sk_PKCS12_SAFEBAG_push (bags, bag);

	/* Turn it into unencrypted safe bag */
	authsafe = PKCS12_pack_p7data(bags);
	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;
	sk_PKCS7_push(safes, authsafe);

	p12 = PKCS12_init(NID_pkcs7_data);

	PKCS12_pack_authsafes(p12, safes);

	sk_PKCS7_pop_free(safes, PKCS7_free);
	safes = NULL;

	PKCS12_set_mac(p12, pemPass, -1, NULL, 0, maciter, NULL);

	i2d_PKCS12_bio (out, p12);

	ret = S_OK;

end:

	if (key)
		EVP_PKEY_free(key);
	if (certs)
		sk_X509_pop_free(certs, X509_free);
	if (safes)
		sk_PKCS7_pop_free(safes, PKCS7_free);
	if (bags)
		sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
    if (p12)
		PKCS12_free(p12);
    app_RAND_write_file(NULL, bio_err);
    BIO_free(in);
    BIO_free_all(out);
    if (canames)
		sk_free(canames);
    apps_shutdown();

	if (ret != S_OK)
		return NULL;

	return retFileName;
}
コード例 #5
0
ファイル: verify.c プロジェクト: 274914765/C
int MAIN (int argc, char **argv)
{
    ENGINE *e = NULL;

    int i, ret = 1, badarg = 0;

    char *CApath = NULL, *CAfile = NULL;

    char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;

    STACK_OF (X509) * untrusted = NULL, *trusted = NULL;
    STACK_OF (X509_CRL) * crls = NULL;
    X509_STORE *cert_ctx = NULL;

    X509_LOOKUP *lookup = NULL;

    X509_VERIFY_PARAM *vpm = NULL;

#ifndef OPENSSL_NO_ENGINE
    char *engine = NULL;
#endif

    cert_ctx = X509_STORE_new ();
    if (cert_ctx == NULL)
        goto end;
    X509_STORE_set_verify_cb (cert_ctx, cb);

    ERR_load_crypto_strings ();

    apps_startup ();

    if (bio_err == NULL)
        if ((bio_err = BIO_new (BIO_s_file ())) != NULL)
            BIO_set_fp (bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    if (!load_config (bio_err, NULL))
        goto end;

    argc--;
    argv++;
    for (;;)
    {
        if (argc >= 1)
        {
            if (strcmp (*argv, "-CApath") == 0)
            {
                if (argc-- < 1)
                    goto end;
                CApath = *(++argv);
            }
            else if (strcmp (*argv, "-CAfile") == 0)
            {
                if (argc-- < 1)
                    goto end;
                CAfile = *(++argv);
            }
            else if (args_verify (&argv, &argc, &badarg, bio_err, &vpm))
            {
                if (badarg)
                    goto end;
                continue;
            }
            else if (strcmp (*argv, "-untrusted") == 0)
            {
                if (argc-- < 1)
                    goto end;
                untfile = *(++argv);
            }
            else if (strcmp (*argv, "-trusted") == 0)
            {
                if (argc-- < 1)
                    goto end;
                trustfile = *(++argv);
            }
            else if (strcmp (*argv, "-CRLfile") == 0)
            {
                if (argc-- < 1)
                    goto end;
                crlfile = *(++argv);
            }
#ifndef OPENSSL_NO_ENGINE
            else if (strcmp (*argv, "-engine") == 0)
            {
                if (--argc < 1)
                    goto end;
                engine = *(++argv);
            }
#endif
            else if (strcmp (*argv, "-help") == 0)
                goto end;
            else if (strcmp (*argv, "-verbose") == 0)
                v_verbose = 1;
            else if (argv[0][0] == '-')
                goto end;
            else
                break;
            argc--;
            argv++;
        }
        else
            break;
    }

#ifndef OPENSSL_NO_ENGINE
    e = setup_engine (bio_err, engine, 0);
#endif

    if (vpm)
        X509_STORE_set1_param (cert_ctx, vpm);

    lookup = X509_STORE_add_lookup (cert_ctx, X509_LOOKUP_file ());
    if (lookup == NULL)
        abort ();
    if (CAfile)
    {
        i = X509_LOOKUP_load_file (lookup, CAfile, X509_FILETYPE_PEM);
        if (!i)
        {
            BIO_printf (bio_err, "Error loading file %s\n", CAfile);
            ERR_print_errors (bio_err);
            goto end;
        }
    }
    else
        X509_LOOKUP_load_file (lookup, NULL, X509_FILETYPE_DEFAULT);

    lookup = X509_STORE_add_lookup (cert_ctx, X509_LOOKUP_hash_dir ());
    if (lookup == NULL)
        abort ();
    if (CApath)
    {
        i = X509_LOOKUP_add_dir (lookup, CApath, X509_FILETYPE_PEM);
        if (!i)
        {
            BIO_printf (bio_err, "Error loading directory %s\n", CApath);
            ERR_print_errors (bio_err);
            goto end;
        }
    }
    else
        X509_LOOKUP_add_dir (lookup, NULL, X509_FILETYPE_DEFAULT);

    ERR_clear_error ();

    if (untfile)
    {
        untrusted = load_certs (bio_err, untfile, FORMAT_PEM, NULL, e, "untrusted certificates");
        if (!untrusted)
            goto end;
    }

    if (trustfile)
    {
        trusted = load_certs (bio_err, trustfile, FORMAT_PEM, NULL, e, "trusted certificates");
        if (!trusted)
            goto end;
    }

    if (crlfile)
    {
        crls = load_crls (bio_err, crlfile, FORMAT_PEM, NULL, e, "other CRLs");
        if (!crls)
            goto end;
    }

    ret = 0;
    if (argc < 1)
    {
        if (1 != check (cert_ctx, NULL, untrusted, trusted, crls, e))
            ret = -1;
    }
    else
    {
        for (i = 0; i < argc; i++)
            if (1 != check (cert_ctx, argv[i], untrusted, trusted, crls, e))
                ret = -1;
    }

  end:
    if (ret == 1)
    {
        BIO_printf (bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]");
        BIO_printf (bio_err, " [-attime timestamp]");
#ifndef OPENSSL_NO_ENGINE
        BIO_printf (bio_err, " [-engine e]");
#endif
        BIO_printf (bio_err, " cert1 cert2 ...\n");

        BIO_printf (bio_err, "recognized usages:\n");
        for (i = 0; i < X509_PURPOSE_get_count (); i++)
        {
            X509_PURPOSE *ptmp;

            ptmp = X509_PURPOSE_get0 (i);
            BIO_printf (bio_err, "\t%-10s\t%s\n", X509_PURPOSE_get0_sname (ptmp), X509_PURPOSE_get0_name (ptmp));
        }
    }
    if (vpm)
        X509_VERIFY_PARAM_free (vpm);
    if (cert_ctx != NULL)
        X509_STORE_free (cert_ctx);
    sk_X509_pop_free (untrusted, X509_free);
    sk_X509_pop_free (trusted, X509_free);
    sk_X509_CRL_pop_free (crls, X509_CRL_free);
    apps_shutdown ();
    OPENSSL_EXIT (ret < 0 ? 2 : ret);
}
コード例 #6
0
ファイル: conftest.c プロジェクト: agimsn/strongswan
/**
 * Main function, starts the conftest daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int status = 0;
	sigset_t set;
	int sig;
	char *suite_file = "suite.conf", *test_file = NULL;
	file_logger_t *logger;

	if (!library_init(NULL))
	{
		library_deinit();
		return SS_RC_LIBSTRONGSWAN_INTEGRITY;
	}
	if (!libhydra_init("conftest"))
	{
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}
	if (!libcharon_init("conftest"))
	{
		libcharon_deinit();
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}

	INIT(conftest,
		.creds = mem_cred_create(),
		.config = config_create(),
		.hooks = linked_list_create(),
		.loggers = linked_list_create(),
	);
	lib->credmgr->add_set(lib->credmgr, &conftest->creds->set);

	logger = file_logger_create("stdout");
	logger->set_options(logger, NULL, FALSE);
	logger->open(logger, FALSE, FALSE);
	logger->set_level(logger, DBG_ANY, LEVEL_CTRL);
	charon->bus->add_logger(charon->bus, &logger->logger);
	conftest->loggers->insert_last(conftest->loggers, logger);

	atexit(cleanup);

	while (TRUE)
	{
		struct option long_opts[] = {
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "suite", required_argument, NULL, 's' },
			{ "test", required_argument, NULL, 't' },
			{ 0,0,0,0 }
		};
		switch (getopt_long(argc, argv, "", long_opts, NULL))
		{
			case EOF:
				break;
			case 'h':
				usage(stdout);
				return 0;
			case 'v':
				printf("strongSwan %s conftest\n", VERSION);
				return 0;
			case 's':
				suite_file = optarg;
				continue;
			case 't':
				test_file = optarg;
				continue;
			default:
				usage(stderr);
				return 1;
		}
		break;
	}

	if (!load_configs(suite_file, test_file))
	{
		return 1;
	}
	load_loggers(logger);

	if (!lib->plugins->load(lib->plugins, NULL,
			conftest->test->get_str(conftest->test, "preload", "")))
	{
		return 1;
	}
	if (!charon->initialize(charon, PLUGINS))
	{
		return 1;
	}
	if (!load_certs(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	if (!load_keys(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	load_cdps(conftest->test);
	if (!load_hooks())
	{
		return 1;
	}
	charon->backends->add_backend(charon->backends, &conftest->config->backend);
	conftest->config->load(conftest->config, conftest->test);
	conftest->actions = actions_create();

	/* set up thread specific handlers */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);
	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start thread pool */
	charon->start(charon);

	/* handle SIGINT/SIGTERM in main thread */
	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGTERM);
	sigprocmask(SIG_BLOCK, &set, NULL);

	while (sigwait(&set, &sig) == 0)
	{
		switch (sig)
		{
			case SIGINT:
			case SIGTERM:
				fprintf(stderr, "\nshutting down...\n");
				break;
			default:
				continue;
		}
		break;
	}
	return status;
}
コード例 #7
0
ファイル: pkcs12.c プロジェクト: xyzy/mips-openssl_0.9.7
int MAIN(int argc, char **argv)
{
    ENGINE *e = NULL;
    char *infile=NULL, *outfile=NULL, *keyname = NULL;	
    char *certfile=NULL;
    BIO *in=NULL, *out = NULL;
    char **args;
    char *name = NULL;
    char *csp_name = NULL;
    PKCS12 *p12 = NULL;
    char pass[50], macpass[50];
    int export_cert = 0;
    int options = 0;
    int chain = 0;
    int badarg = 0;
    int iter = PKCS12_DEFAULT_ITER;
    int maciter = PKCS12_DEFAULT_ITER;
    int twopass = 0;
    int keytype = 0;
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int ret = 1;
    int macver = 1;
    int noprompt = 0;
    STACK *canames = NULL;
    char *cpass = NULL, *mpass = NULL;
    char *passargin = NULL, *passargout = NULL, *passarg = NULL;
    char *passin = NULL, *passout = NULL;
    char *inrand = NULL;
    char *CApath = NULL, *CAfile = NULL;
    char *engine=NULL;

    apps_startup();

    enc = EVP_des_ede3_cbc();
    if (bio_err == NULL ) bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;

    args = argv + 1;


    while (*args) {
	if (*args[0] == '-') {
		if (!strcmp (*args, "-nokeys")) options |= NOKEYS;
		else if (!strcmp (*args, "-keyex")) keytype = KEY_EX;
		else if (!strcmp (*args, "-keysig")) keytype = KEY_SIG;
		else if (!strcmp (*args, "-nocerts")) options |= NOCERTS;
		else if (!strcmp (*args, "-clcerts")) options |= CLCERTS;
		else if (!strcmp (*args, "-cacerts")) options |= CACERTS;
		else if (!strcmp (*args, "-noout")) options |= (NOKEYS|NOCERTS);
		else if (!strcmp (*args, "-info")) options |= INFO;
		else if (!strcmp (*args, "-chain")) chain = 1;
		else if (!strcmp (*args, "-twopass")) twopass = 1;
		else if (!strcmp (*args, "-nomacver")) macver = 0;
		else if (!strcmp (*args, "-descert"))
    			cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
		else if (!strcmp (*args, "-export")) export_cert = 1;
		else if (!strcmp (*args, "-des")) enc=EVP_des_cbc();
#ifndef OPENSSL_NO_IDEA
		else if (!strcmp (*args, "-idea")) enc=EVP_idea_cbc();
#endif
		else if (!strcmp (*args, "-des3")) enc = EVP_des_ede3_cbc();
#ifndef OPENSSL_NO_AES
		else if (!strcmp(*args,"-aes128")) enc=EVP_aes_128_cbc();
		else if (!strcmp(*args,"-aes192")) enc=EVP_aes_192_cbc();
		else if (!strcmp(*args,"-aes256")) enc=EVP_aes_256_cbc();
#endif
		else if (!strcmp (*args, "-noiter")) iter = 1;
		else if (!strcmp (*args, "-maciter"))
					 maciter = PKCS12_DEFAULT_ITER;
		else if (!strcmp (*args, "-nomaciter"))
					 maciter = 1;
		else if (!strcmp (*args, "-nodes")) enc=NULL;
		else if (!strcmp (*args, "-certpbe")) {
			if (args[1]) {
				args++;
				cert_pbe=OBJ_txt2nid(*args);
				if(cert_pbe == NID_undef) {
					BIO_printf(bio_err,
						 "Unknown PBE algorithm %s\n", *args);
					badarg = 1;
				}
			} else badarg = 1;
		} else if (!strcmp (*args, "-keypbe")) {
			if (args[1]) {
				args++;
				key_pbe=OBJ_txt2nid(*args);
				if(key_pbe == NID_undef) {
					BIO_printf(bio_err,
						 "Unknown PBE algorithm %s\n", *args);
					badarg = 1;
				}
			} else badarg = 1;
		} else if (!strcmp (*args, "-rand")) {
		    if (args[1]) {
			args++;	
			inrand = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-inkey")) {
		    if (args[1]) {
			args++;	
			keyname = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-certfile")) {
		    if (args[1]) {
			args++;	
			certfile = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-name")) {
		    if (args[1]) {
			args++;	
			name = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-CSP")) {
		    if (args[1]) {
			args++;	
			csp_name = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-caname")) {
		    if (args[1]) {
			args++;	
			if (!canames) canames = sk_new_null();
			sk_push(canames, *args);
		    } else badarg = 1;
		} else if (!strcmp (*args, "-in")) {
		    if (args[1]) {
			args++;	
			infile = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-out")) {
		    if (args[1]) {
			args++;	
			outfile = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-passin")) {
		    if (args[1]) {
			args++;	
			passargin = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-passout")) {
		    if (args[1]) {
			args++;	
			passargout = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-password")) {
		    if (args[1]) {
			args++;	
			passarg = *args;
		    	noprompt = 1;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-CApath")) {
		    if (args[1]) {
			args++;	
			CApath = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-CAfile")) {
		    if (args[1]) {
			args++;	
			CAfile = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-engine")) {
		    if (args[1]) {
			args++;	
			engine = *args;
		    } else badarg = 1;
		} else badarg = 1;

	} else badarg = 1;
	args++;
    }

    if (badarg) {
	BIO_printf (bio_err, "Usage: pkcs12 [options]\n");
	BIO_printf (bio_err, "where options are\n");
	BIO_printf (bio_err, "-export       output PKCS12 file\n");
	BIO_printf (bio_err, "-chain        add certificate chain\n");
	BIO_printf (bio_err, "-inkey file   private key if not infile\n");
	BIO_printf (bio_err, "-certfile f   add all certs in f\n");
	BIO_printf (bio_err, "-CApath arg   - PEM format directory of CA's\n");
	BIO_printf (bio_err, "-CAfile arg   - PEM format file of CA's\n");
	BIO_printf (bio_err, "-name \"name\"  use name as friendly name\n");
	BIO_printf (bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
	BIO_printf (bio_err, "-in  infile   input filename\n");
	BIO_printf (bio_err, "-out outfile  output filename\n");
	BIO_printf (bio_err, "-noout        don't output anything, just verify.\n");
	BIO_printf (bio_err, "-nomacver     don't verify MAC.\n");
	BIO_printf (bio_err, "-nocerts      don't output certificates.\n");
	BIO_printf (bio_err, "-clcerts      only output client certificates.\n");
	BIO_printf (bio_err, "-cacerts      only output CA certificates.\n");
	BIO_printf (bio_err, "-nokeys       don't output private keys.\n");
	BIO_printf (bio_err, "-info         give info about PKCS#12 structure.\n");
	BIO_printf (bio_err, "-des          encrypt private keys with DES\n");
	BIO_printf (bio_err, "-des3         encrypt private keys with triple DES (default)\n");
#ifndef OPENSSL_NO_IDEA
	BIO_printf (bio_err, "-idea         encrypt private keys with idea\n");
#endif
#ifndef OPENSSL_NO_AES
	BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
	BIO_printf (bio_err, "              encrypt PEM output with cbc aes\n");
#endif
	BIO_printf (bio_err, "-nodes        don't encrypt private keys\n");
	BIO_printf (bio_err, "-noiter       don't use encryption iteration\n");
	BIO_printf (bio_err, "-maciter      use MAC iteration\n");
	BIO_printf (bio_err, "-twopass      separate MAC, encryption passwords\n");
	BIO_printf (bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
	BIO_printf (bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
	BIO_printf (bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
	BIO_printf (bio_err, "-keyex        set MS key exchange type\n");
	BIO_printf (bio_err, "-keysig       set MS key signature type\n");
	BIO_printf (bio_err, "-password p   set import/export password source\n");
	BIO_printf (bio_err, "-passin p     input file pass phrase source\n");
	BIO_printf (bio_err, "-passout p    output file pass phrase source\n");
	BIO_printf (bio_err, "-engine e     use engine e, possibly a hardware device.\n");
	BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
	BIO_printf(bio_err,  "              load the file (or the files in the directory) into\n");
	BIO_printf(bio_err,  "              the random number generator\n");
    	goto end;
    }

    e = setup_engine(bio_err, engine, 0);

    if(passarg) {
	if(export_cert) passargout = passarg;
	else passargin = passarg;
    }

    if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
	BIO_printf(bio_err, "Error getting passwords\n");
	goto end;
    }

    if(!cpass) {
    	if(export_cert) cpass = passout;
    	else cpass = passin;
    }

    if(cpass) {
	mpass = cpass;
	noprompt = 1;
    } else {
	cpass = pass;
	mpass = macpass;
    }

    if(export_cert || inrand) {
    	app_RAND_load_file(NULL, bio_err, (inrand != NULL));
        if (inrand != NULL)
		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
			app_RAND_load_files(inrand));
    }
    ERR_load_crypto_strings();

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read files");
#endif

    if (!infile) in = BIO_new_fp(stdin, BIO_NOCLOSE);
    else in = BIO_new_file(infile, "rb");
    if (!in) {
	    BIO_printf(bio_err, "Error opening input file %s\n",
						infile ? infile : "<stdin>");
	    perror (infile);
	    goto end;
   }

#if 0
   if (certfile) {
    	if(!(certsin = BIO_new_file(certfile, "r"))) {
	    BIO_printf(bio_err, "Can't open certificate file %s\n", certfile);
	    perror (certfile);
	    goto end;
	}
    }

    if (keyname) {
    	if(!(inkey = BIO_new_file(keyname, "r"))) {
	    BIO_printf(bio_err, "Can't key certificate file %s\n", keyname);
	    perror (keyname);
	    goto end;
	}
     }
#endif

#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
    CRYPTO_push_info("write files");
#endif

    if (!outfile) {
	out = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
	{
	    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
	    out = BIO_push(tmpbio, out);
	}
#endif
    } else out = BIO_new_file(outfile, "wb");
    if (!out) {
	BIO_printf(bio_err, "Error opening output file %s\n",
						outfile ? outfile : "<stdout>");
	perror (outfile);
	goto end;
    }
    if (twopass) {
#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read MAC password");
#endif
	if(EVP_read_pw_string (macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
    	    goto end;
       	}
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    }

    if (export_cert) {
	EVP_PKEY *key = NULL;
	STACK_OF(PKCS12_SAFEBAG) *bags = NULL;
	STACK_OF(PKCS7) *safes = NULL;
	PKCS12_SAFEBAG *bag = NULL;
	PKCS8_PRIV_KEY_INFO *p8 = NULL;
	PKCS7 *authsafe = NULL;
	X509 *ucert = NULL;
	STACK_OF(X509) *certs=NULL;
	char *catmp = NULL;
	int i;
	unsigned char keyid[EVP_MAX_MD_SIZE];
	unsigned int keyidlen = 0;

#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("process -export_cert");
	CRYPTO_push_info("reading private key");
#endif
	key = load_key(bio_err, keyname ? keyname : infile, FORMAT_PEM, 1,
		passin, e, "private key");
	if (!key) {
		goto export_end;
	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from input");
#endif

	/* Load in all certs in input file */
	if(!(certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
		"certificates"))) {
		goto export_end;
	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from input 2");
#endif

	for(i = 0; i < sk_X509_num(certs); i++) {
		ucert = sk_X509_value(certs, i);
		if(X509_check_private_key(ucert, key)) {
			X509_digest(ucert, EVP_sha1(), keyid, &keyidlen);
			break;
		}
	}
	if(!keyidlen) {
		ucert = NULL;
		BIO_printf(bio_err, "No certificate matches private key\n");
		goto export_end;
	}
	
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from certfile");
#endif

	bags = sk_PKCS12_SAFEBAG_new_null ();

	/* Add any more certificates asked for */
	if (certfile) {
		STACK_OF(X509) *morecerts=NULL;
		if(!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
					    NULL, e,
					    "certificates from certfile"))) {
			goto export_end;
		}
		while(sk_X509_num(morecerts) > 0) {
			sk_X509_push(certs, sk_X509_shift(morecerts));
		}
		sk_X509_free(morecerts);
 	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building chain");
#endif

	/* If chaining get chain from user cert */
	if (chain) {
        	int vret;
		STACK_OF(X509) *chain2;
		X509_STORE *store = X509_STORE_new();
		if (!store)
			{
			BIO_printf (bio_err, "Memory allocation error\n");
			goto export_end;
			}
		if (!X509_STORE_load_locations(store, CAfile, CApath))
			X509_STORE_set_default_paths (store);

		vret = get_cert_chain (ucert, store, &chain2);
		X509_STORE_free(store);

		if (!vret) {
		    /* Exclude verified certificate */
		    for (i = 1; i < sk_X509_num (chain2) ; i++) 
			sk_X509_push(certs, sk_X509_value (chain2, i));
		    /* Free first certificate */
		    X509_free(sk_X509_value(chain2, 0));
		    sk_X509_free(chain2);
		} else {
			BIO_printf (bio_err, "Error %s getting chain.\n",
					X509_verify_cert_error_string(vret));
			goto export_end;
		}			
    	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building bags");
#endif

	/* We now have loads of certificates: include them all */
	for(i = 0; i < sk_X509_num(certs); i++) {
		X509 *cert = NULL;
		cert = sk_X509_value(certs, i);
		bag = PKCS12_x5092certbag(cert);
		/* If it matches private key set id */
		if(cert == ucert) {
			if(name) PKCS12_add_friendlyname(bag, name, -1);
			PKCS12_add_localkeyid(bag, keyid, keyidlen);
		} else if((catmp = sk_shift(canames))) 
				PKCS12_add_friendlyname(bag, catmp, -1);
		sk_PKCS12_SAFEBAG_push(bags, bag);
	}
	sk_X509_pop_free(certs, X509_free);
	certs = NULL;

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("encrypting bags");
#endif

	if(!noprompt &&
		EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
	    goto export_end;
        }
	if (!twopass) strcpy(macpass, pass);
	/* Turn certbags into encrypted authsafe */
	authsafe = PKCS12_pack_p7encdata(cert_pbe, cpass, -1, NULL, 0,
								 iter, bags);
	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;

	if (!authsafe) {
		ERR_print_errors (bio_err);
		goto export_end;
	}

	safes = sk_PKCS7_new_null ();
	sk_PKCS7_push (safes, authsafe);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building shrouded key bag");
#endif

	/* Make a shrouded key bag */
	p8 = EVP_PKEY2PKCS8 (key);
	if(keytype) PKCS8_add_keyusage(p8, keytype);
	bag = PKCS12_MAKE_SHKEYBAG(key_pbe, cpass, -1, NULL, 0, iter, p8);
	PKCS8_PRIV_KEY_INFO_free(p8);
	p8 = NULL;
        if (name) PKCS12_add_friendlyname (bag, name, -1);
	if(csp_name) PKCS12_add_CSPName_asc(bag, csp_name, -1);
	PKCS12_add_localkeyid (bag, keyid, keyidlen);
	bags = sk_PKCS12_SAFEBAG_new_null();
	sk_PKCS12_SAFEBAG_push (bags, bag);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("encrypting shrouded key bag");
#endif

	/* Turn it into unencrypted safe bag */
	authsafe = PKCS12_pack_p7data (bags);
	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;
	sk_PKCS7_push (safes, authsafe);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building pkcs12");
#endif

	p12 = PKCS12_init(NID_pkcs7_data);

	PKCS12_pack_authsafes(p12, safes);

	sk_PKCS7_pop_free(safes, PKCS7_free);
	safes = NULL;

	PKCS12_set_mac (p12, mpass, -1, NULL, 0, maciter, NULL);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("writing pkcs12");
#endif

	i2d_PKCS12_bio (out, p12);

	ret = 0;

    export_end:
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_pop_info();
	CRYPTO_push_info("process -export_cert: freeing");
#endif

	if (key) EVP_PKEY_free(key);
	if (certs) sk_X509_pop_free(certs, X509_free);
	if (safes) sk_PKCS7_pop_free(safes, PKCS7_free);
	if (bags) sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif
	goto end;
	
    }

    if (!(p12 = d2i_PKCS12_bio (in, NULL))) {
	ERR_print_errors(bio_err);
	goto end;
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read import password");
#endif
    if(!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
	goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif

    if (!twopass) strcpy(macpass, pass);

    if (options & INFO) BIO_printf (bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get (p12->mac->iter) : 1);
    if(macver) {
#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("verify MAC");
#endif
	/* If we enter empty password try no password first */
	if(!macpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
		/* If mac and crypto pass the same set it to NULL too */
		if(!twopass) cpass = NULL;
	} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
	    BIO_printf (bio_err, "Mac verify error: invalid password?\n");
	    ERR_print_errors (bio_err);
	    goto end;
	}
	BIO_printf (bio_err, "MAC verified OK\n");
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("output keys and certificates");
#endif
    if (!dump_certs_keys_p12 (out, p12, cpass, -1, options, passout)) {
	BIO_printf(bio_err, "Error outputting keys and certificates\n");
	ERR_print_errors (bio_err);
	goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    ret = 0;
 end:
    if (p12) PKCS12_free(p12);
    if(export_cert || inrand) app_RAND_write_file(NULL, bio_err);
#ifdef CRYPTO_MDEBUG
    CRYPTO_remove_all_info();
#endif
    BIO_free(in);
    BIO_free_all(out);
    if (canames) sk_free(canames);
    if(passin) OPENSSL_free(passin);
    if(passout) OPENSSL_free(passout);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
コード例 #8
0
ファイル: ocsp.c プロジェクト: pascal-cuoq/openbsd
int
ocsp_main(int argc, char **argv)
{
	char **args;
	char *host = NULL, *port = NULL, *path = "/";
	char *reqin = NULL, *respin = NULL;
	char *reqout = NULL, *respout = NULL;
	char *signfile = NULL, *keyfile = NULL;
	char *rsignfile = NULL, *rkeyfile = NULL;
	char *outfile = NULL;
	int add_nonce = 1, noverify = 0, use_ssl = -1;
	STACK_OF(CONF_VALUE) * headers = NULL;
	OCSP_REQUEST *req = NULL;
	OCSP_RESPONSE *resp = NULL;
	OCSP_BASICRESP *bs = NULL;
	X509 *issuer = NULL, *cert = NULL;
	X509 *signer = NULL, *rsigner = NULL;
	EVP_PKEY *key = NULL, *rkey = NULL;
	BIO *acbio = NULL, *cbio = NULL;
	BIO *derbio = NULL;
	BIO *out = NULL;
	int req_timeout = -1;
	int req_text = 0, resp_text = 0;
	long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
	char *CAfile = NULL, *CApath = NULL;
	X509_STORE *store = NULL;
	STACK_OF(X509) * sign_other = NULL, *verify_other = NULL, *rother = NULL;
	char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
	unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
	int ret = 1;
	int accept_count = -1;
	int badarg = 0;
	int i;
	int ignore_err = 0;
	STACK_OF(OPENSSL_STRING) * reqnames = NULL;
	STACK_OF(OCSP_CERTID) * ids = NULL;
	X509 *rca_cert = NULL;
	char *ridx_filename = NULL;
	char *rca_filename = NULL;
	CA_DB *rdb = NULL;
	int nmin = 0, ndays = -1;
	const EVP_MD *cert_id_md = NULL;
	const char *errstr = NULL;

	args = argv + 1;
	reqnames = sk_OPENSSL_STRING_new_null();
	ids = sk_OCSP_CERTID_new_null();
	while (!badarg && *args && *args[0] == '-') {
		if (!strcmp(*args, "-out")) {
			if (args[1]) {
				args++;
				outfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-timeout")) {
			if (args[1]) {
				args++;
				req_timeout = strtonum(*args, 0,
				    INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal timeout value %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-url")) {
			if (args[1]) {
				args++;
				if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) {
					BIO_printf(bio_err, "Error parsing URL\n");
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-host")) {
			if (args[1]) {
				args++;
				host = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-port")) {
			if (args[1]) {
				args++;
				port = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-header")) {
			if (args[1] && args[2]) {
				if (!X509V3_add_value(args[1], args[2], &headers))
					goto end;
				args += 2;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ignore_err"))
			ignore_err = 1;
		else if (!strcmp(*args, "-noverify"))
			noverify = 1;
		else if (!strcmp(*args, "-nonce"))
			add_nonce = 2;
		else if (!strcmp(*args, "-no_nonce"))
			add_nonce = 0;
		else if (!strcmp(*args, "-resp_no_certs"))
			rflags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-resp_key_id"))
			rflags |= OCSP_RESPID_KEY;
		else if (!strcmp(*args, "-no_certs"))
			sign_flags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-no_signature_verify"))
			verify_flags |= OCSP_NOSIGS;
		else if (!strcmp(*args, "-no_cert_verify"))
			verify_flags |= OCSP_NOVERIFY;
		else if (!strcmp(*args, "-no_chain"))
			verify_flags |= OCSP_NOCHAIN;
		else if (!strcmp(*args, "-no_cert_checks"))
			verify_flags |= OCSP_NOCHECKS;
		else if (!strcmp(*args, "-no_explicit"))
			verify_flags |= OCSP_NOEXPLICIT;
		else if (!strcmp(*args, "-trust_other"))
			verify_flags |= OCSP_TRUSTOTHER;
		else if (!strcmp(*args, "-no_intern"))
			verify_flags |= OCSP_NOINTERN;
		else if (!strcmp(*args, "-text")) {
			req_text = 1;
			resp_text = 1;
		} else if (!strcmp(*args, "-req_text"))
			req_text = 1;
		else if (!strcmp(*args, "-resp_text"))
			resp_text = 1;
		else if (!strcmp(*args, "-reqin")) {
			if (args[1]) {
				args++;
				reqin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respin")) {
			if (args[1]) {
				args++;
				respin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signer")) {
			if (args[1]) {
				args++;
				signfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-VAfile")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
				verify_flags |= OCSP_TRUSTOTHER;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-sign_other")) {
			if (args[1]) {
				args++;
				sign_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-verify_other")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CAfile")) {
			if (args[1]) {
				args++;
				CAfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CApath")) {
			if (args[1]) {
				args++;
				CApath = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-validity_period")) {
			if (args[1]) {
				args++;
				nsec = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-status_age")) {
			if (args[1]) {
				args++;
				maxage = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity age %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signkey")) {
			if (args[1]) {
				args++;
				keyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-reqout")) {
			if (args[1]) {
				args++;
				reqout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respout")) {
			if (args[1]) {
				args++;
				respout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-path")) {
			if (args[1]) {
				args++;
				path = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-issuer")) {
			if (args[1]) {
				args++;
				X509_free(issuer);
				issuer = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "issuer certificate");
				if (!issuer)
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-cert")) {
			if (args[1]) {
				args++;
				X509_free(cert);
				cert = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "certificate");
				if (!cert)
					goto end;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-serial")) {
			if (args[1]) {
				args++;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-index")) {
			if (args[1]) {
				args++;
				ridx_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CA")) {
			if (args[1]) {
				args++;
				rca_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-nmin")) {
			if (args[1]) {
				args++;
				nmin = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			}
			if (ndays == -1)
				ndays = 0;
			else
				badarg = 1;
		} else if (!strcmp(*args, "-nrequest")) {
			if (args[1]) {
				args++;
				accept_count = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal accept count %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ndays")) {
			if (args[1]) {
				args++;
				ndays = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rsigner")) {
			if (args[1]) {
				args++;
				rsignfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rkey")) {
			if (args[1]) {
				args++;
				rkeyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rother")) {
			if (args[1]) {
				args++;
				rcertfile = *args;
			} else
				badarg = 1;
		} else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) {
			badarg = 1;
		}
		args++;
	}

	/* Have we anything to do? */
	if (!req && !reqin && !respin && !(port && ridx_filename))
		badarg = 1;

	if (badarg) {
		BIO_printf(bio_err, "OCSP utility\n");
		BIO_printf(bio_err, "Usage ocsp [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-out file          output filename\n");
		BIO_printf(bio_err, "-issuer file       issuer certificate\n");
		BIO_printf(bio_err, "-cert file         certificate to check\n");
		BIO_printf(bio_err, "-serial n          serial number to check\n");
		BIO_printf(bio_err, "-signer file       certificate to sign OCSP request with\n");
		BIO_printf(bio_err, "-signkey file      private key to sign OCSP request with\n");
		BIO_printf(bio_err, "-sign_other file   additional certificates to include in signed request\n");
		BIO_printf(bio_err, "-no_certs          don't include any certificates in signed request\n");
		BIO_printf(bio_err, "-req_text          print text form of request\n");
		BIO_printf(bio_err, "-resp_text         print text form of response\n");
		BIO_printf(bio_err, "-text              print text form of request and response\n");
		BIO_printf(bio_err, "-reqout file       write DER encoded OCSP request to \"file\"\n");
		BIO_printf(bio_err, "-respout file      write DER encoded OCSP reponse to \"file\"\n");
		BIO_printf(bio_err, "-reqin file        read DER encoded OCSP request from \"file\"\n");
		BIO_printf(bio_err, "-respin file       read DER encoded OCSP reponse from \"file\"\n");
		BIO_printf(bio_err, "-nonce             add OCSP nonce to request\n");
		BIO_printf(bio_err, "-no_nonce          don't add OCSP nonce to request\n");
		BIO_printf(bio_err, "-url URL           OCSP responder URL\n");
		BIO_printf(bio_err, "-host host:n       send OCSP request to host on port n\n");
		BIO_printf(bio_err, "-path              path to use in OCSP request\n");
		BIO_printf(bio_err, "-CApath dir        trusted certificates directory\n");
		BIO_printf(bio_err, "-CAfile file       trusted certificates file\n");
		BIO_printf(bio_err, "-VAfile file       validator certificates file\n");
		BIO_printf(bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
		BIO_printf(bio_err, "-status_age n      maximum status age in seconds\n");
		BIO_printf(bio_err, "-noverify          don't verify response at all\n");
		BIO_printf(bio_err, "-verify_other file additional certificates to search for signer\n");
		BIO_printf(bio_err, "-trust_other       don't verify additional certificates\n");
		BIO_printf(bio_err, "-no_intern         don't search certificates contained in response for signer\n");
		BIO_printf(bio_err, "-no_signature_verify don't check signature on response\n");
		BIO_printf(bio_err, "-no_cert_verify    don't check signing certificate\n");
		BIO_printf(bio_err, "-no_chain          don't chain verify response\n");
		BIO_printf(bio_err, "-no_cert_checks    don't do additional checks on signing certificate\n");
		BIO_printf(bio_err, "-port num		 port to run responder on\n");
		BIO_printf(bio_err, "-index file	 certificate status index file\n");
		BIO_printf(bio_err, "-CA file		 CA certificate\n");
		BIO_printf(bio_err, "-rsigner file	 responder certificate to sign responses with\n");
		BIO_printf(bio_err, "-rkey file	 responder key to sign responses with\n");
		BIO_printf(bio_err, "-rother file	 other certificates to include in response\n");
		BIO_printf(bio_err, "-resp_no_certs     don't include any certificates in response\n");
		BIO_printf(bio_err, "-nmin n	 	 number of minutes before next update\n");
		BIO_printf(bio_err, "-ndays n	 	 number of days before next update\n");
		BIO_printf(bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
		BIO_printf(bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
		BIO_printf(bio_err, "-<dgst alg>     use specified digest in the request\n");
		goto end;
	}
	if (outfile)
		out = BIO_new_file(outfile, "w");
	else
		out = BIO_new_fp(stdout, BIO_NOCLOSE);

	if (!out) {
		BIO_printf(bio_err, "Error opening output file\n");
		goto end;
	}
	if (!req && (add_nonce != 2))
		add_nonce = 0;

	if (!req && reqin) {
		derbio = BIO_new_file(reqin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP request file\n");
			goto end;
		}
		req = d2i_OCSP_REQUEST_bio(derbio, NULL);
		BIO_free(derbio);
		if (!req) {
			BIO_printf(bio_err, "Error reading OCSP request\n");
			goto end;
		}
	}
	if (!req && port) {
		acbio = init_responder(port);
		if (!acbio)
			goto end;
	}
	if (rsignfile && !rdb) {
		if (!rkeyfile)
			rkeyfile = rsignfile;
		rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
		    NULL, "responder certificate");
		if (!rsigner) {
			BIO_printf(bio_err, "Error loading responder certificate\n");
			goto end;
		}
		rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
		    NULL, "CA certificate");
		if (rcertfile) {
			rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
			    NULL, "responder other certificates");
			if (!rother)
				goto end;
		}
		rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL,
		    "responder private key");
		if (!rkey)
			goto end;
	}
	if (acbio)
		BIO_printf(bio_err, "Waiting for OCSP client connections...\n");

redo_accept:

	if (acbio) {
		if (!do_responder(&req, &cbio, acbio, port))
			goto end;
		if (!req) {
			resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
			send_ocsp_response(cbio, resp);
			goto done_resp;
		}
	}
	if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
		BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
		goto end;
	}
	if (req && add_nonce)
		OCSP_request_add1_nonce(req, NULL, -1);

	if (signfile) {
		if (!keyfile)
			keyfile = signfile;
		signer = load_cert(bio_err, signfile, FORMAT_PEM,
		    NULL, "signer certificate");
		if (!signer) {
			BIO_printf(bio_err, "Error loading signer certificate\n");
			goto end;
		}
		if (sign_certfile) {
			sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
			    NULL, "signer certificates");
			if (!sign_other)
				goto end;
		}
		key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL,
		    "signer private key");
		if (!key)
			goto end;

		if (!OCSP_request_sign(req, signer, key, NULL, sign_other, sign_flags)) {
			BIO_printf(bio_err, "Error signing OCSP request\n");
			goto end;
		}
	}
	if (req_text && req)
		OCSP_REQUEST_print(out, req, 0);

	if (reqout) {
		derbio = BIO_new_file(reqout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", reqout);
			goto end;
		}
		i2d_OCSP_REQUEST_bio(derbio, req);
		BIO_free(derbio);
	}
	if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
		BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
		goto end;
	}
	if (ridx_filename && !rdb) {
		rdb = load_index(ridx_filename, NULL);
		if (!rdb)
			goto end;
		if (!index_index(rdb))
			goto end;
	}
	if (rdb) {
		i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
		if (cbio)
			send_ocsp_response(cbio, resp);
	} else if (host) {
		resp = process_responder(bio_err, req, host, path,
		    port, use_ssl, headers, req_timeout);
		if (!resp)
			goto end;
	} else if (respin) {
		derbio = BIO_new_file(respin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP response file\n");
			goto end;
		}
		resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
		BIO_free(derbio);
		if (!resp) {
			BIO_printf(bio_err, "Error reading OCSP response\n");
			goto end;
		}
	} else {
		ret = 0;
		goto end;
	}

done_resp:

	if (respout) {
		derbio = BIO_new_file(respout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", respout);
			goto end;
		}
		i2d_OCSP_RESPONSE_bio(derbio, resp);
		BIO_free(derbio);
	}
	i = OCSP_response_status(resp);

	if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
		BIO_printf(out, "Responder Error: %s (%d)\n",
		    OCSP_response_status_str(i), i);
		if (ignore_err)
			goto redo_accept;
		ret = 0;
		goto end;
	}
	if (resp_text)
		OCSP_RESPONSE_print(out, resp, 0);

	/* If running as responder don't verify our own response */
	if (cbio) {
		if (accept_count > 0)
			accept_count--;
		/* Redo if more connections needed */
		if (accept_count) {
			BIO_free_all(cbio);
			cbio = NULL;
			OCSP_REQUEST_free(req);
			req = NULL;
			OCSP_RESPONSE_free(resp);
			resp = NULL;
			goto redo_accept;
		}
		goto end;
	}
	if (!store)
		store = setup_verify(bio_err, CAfile, CApath);
	if (!store)
		goto end;
	if (verify_certfile) {
		verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
		    NULL, "validator certificate");
		if (!verify_other)
			goto end;
	}
	bs = OCSP_response_get1_basic(resp);

	if (!bs) {
		BIO_printf(bio_err, "Error parsing response\n");
		goto end;
	}
	if (!noverify) {
		if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
			if (i == -1)
				BIO_printf(bio_err, "WARNING: no nonce in response\n");
			else {
				BIO_printf(bio_err, "Nonce Verify error\n");
				goto end;
			}
		}
		i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
		if (i < 0)
			i = OCSP_basic_verify(bs, NULL, store, 0);

		if (i <= 0) {
			BIO_printf(bio_err, "Response Verify Failure\n");
			ERR_print_errors(bio_err);
		} else
			BIO_printf(bio_err, "Response verify OK\n");

	}
	if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
		goto end;

	ret = 0;

end:
	ERR_print_errors(bio_err);
	X509_free(signer);
	X509_STORE_free(store);
	EVP_PKEY_free(key);
	EVP_PKEY_free(rkey);
	X509_free(issuer);
	X509_free(cert);
	X509_free(rsigner);
	X509_free(rca_cert);
	free_index(rdb);
	BIO_free_all(cbio);
	BIO_free_all(acbio);
	BIO_free(out);
	OCSP_REQUEST_free(req);
	OCSP_RESPONSE_free(resp);
	OCSP_BASICRESP_free(bs);
	sk_OPENSSL_STRING_free(reqnames);
	sk_OCSP_CERTID_free(ids);
	sk_X509_pop_free(sign_other, X509_free);
	sk_X509_pop_free(verify_other, X509_free);
	sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);

	if (use_ssl != -1) {
		free(host);
		free(port);
		free(path);
	}
	return (ret);
}
コード例 #9
0
ファイル: rpc_secure.cpp プロジェクト: clemahieu/raiblocks
nano::rpc_secure::rpc_secure (boost::asio::io_service & service_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a) :
rpc (service_a, config_a, rpc_handler_interface_a),
ssl_context (boost::asio::ssl::context::tlsv12_server)
{
	load_certs (ssl_context);
}
コード例 #10
0
ファイル: smime.c プロジェクト: 321543223/kbengine
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	int operation = 0;
	int ret = 0;
	char **args;
	const char *inmode = "r", *outmode = "w";
	char *infile = NULL, *outfile = NULL;
	char *signerfile = NULL, *recipfile = NULL;
	char *certfile = NULL, *keyfile = NULL, *contfile=NULL;
	const EVP_CIPHER *cipher = NULL;
	PKCS7 *p7 = NULL;
	X509_STORE *store = NULL;
	X509 *cert = NULL, *recip = NULL, *signer = NULL;
	EVP_PKEY *key = NULL;
	STACK_OF(X509) *encerts = NULL, *other = NULL;
	BIO *in = NULL, *out = NULL, *indata = NULL;
	int badarg = 0;
	int flags = PKCS7_DETACHED;
	char *to = NULL, *from = NULL, *subject = NULL;
	char *CAfile = NULL, *CApath = NULL;
	char *passargin = NULL, *passin = NULL;
	char *inrand = NULL;
	int need_rand = 0;
	int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
        int keyform = FORMAT_PEM;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif

	X509_VERIFY_PARAM *vpm = NULL;

	args = argv + 1;
	ret = 1;

	apps_startup();

	if (bio_err == NULL)
		{
		if ((bio_err = BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err, stderr, BIO_NOCLOSE|BIO_FP_TEXT);
		}

	if (!load_config(bio_err, NULL))
		goto end;

	while (!badarg && *args && *args[0] == '-')
		{
		if (!strcmp (*args, "-encrypt"))
			operation = SMIME_ENCRYPT;
		else if (!strcmp (*args, "-decrypt"))
			operation = SMIME_DECRYPT;
		else if (!strcmp (*args, "-sign"))
			operation = SMIME_SIGN;
		else if (!strcmp (*args, "-verify"))
			operation = SMIME_VERIFY;
		else if (!strcmp (*args, "-pk7out"))
			operation = SMIME_PK7OUT;
#ifndef OPENSSL_NO_DES
		else if (!strcmp (*args, "-des3")) 
				cipher = EVP_des_ede3_cbc();
		else if (!strcmp (*args, "-des")) 
				cipher = EVP_des_cbc();
#endif
#ifndef OPENSSL_NO_SEED
		else if (!strcmp (*args, "-seed")) 
				cipher = EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_RC2
		else if (!strcmp (*args, "-rc2-40")) 
				cipher = EVP_rc2_40_cbc();
		else if (!strcmp (*args, "-rc2-128")) 
				cipher = EVP_rc2_cbc();
		else if (!strcmp (*args, "-rc2-64")) 
				cipher = EVP_rc2_64_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (!strcmp(*args,"-aes128"))
				cipher = EVP_aes_128_cbc();
		else if (!strcmp(*args,"-aes192"))
				cipher = EVP_aes_192_cbc();
		else if (!strcmp(*args,"-aes256"))
				cipher = EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (!strcmp(*args,"-camellia128"))
				cipher = EVP_camellia_128_cbc();
		else if (!strcmp(*args,"-camellia192"))
				cipher = EVP_camellia_192_cbc();
		else if (!strcmp(*args,"-camellia256"))
				cipher = EVP_camellia_256_cbc();
#endif
		else if (!strcmp (*args, "-text")) 
				flags |= PKCS7_TEXT;
		else if (!strcmp (*args, "-nointern")) 
				flags |= PKCS7_NOINTERN;
		else if (!strcmp (*args, "-noverify")) 
				flags |= PKCS7_NOVERIFY;
		else if (!strcmp (*args, "-nochain")) 
				flags |= PKCS7_NOCHAIN;
		else if (!strcmp (*args, "-nocerts")) 
				flags |= PKCS7_NOCERTS;
		else if (!strcmp (*args, "-noattr")) 
				flags |= PKCS7_NOATTR;
		else if (!strcmp (*args, "-nodetach")) 
				flags &= ~PKCS7_DETACHED;
		else if (!strcmp (*args, "-nosmimecap"))
				flags |= PKCS7_NOSMIMECAP;
		else if (!strcmp (*args, "-binary"))
				flags |= PKCS7_BINARY;
		else if (!strcmp (*args, "-nosigs"))
				flags |= PKCS7_NOSIGS;
		else if (!strcmp (*args, "-nooldmime"))
				flags |= PKCS7_NOOLDMIMETYPE;
		else if (!strcmp (*args, "-crlfeol"))
				flags |= PKCS7_CRLFEOL;
		else if (!strcmp(*args,"-rand"))
			{
			if (args[1])
				{
				args++;
				inrand = *args;
				}
			else
				badarg = 1;
			need_rand = 1;
			}
#ifndef OPENSSL_NO_ENGINE
		else if (!strcmp(*args,"-engine"))
			{
			if (args[1])
				{
				args++;
				engine = *args;
				}
			else badarg = 1;
			}
#endif
		else if (!strcmp(*args,"-passin"))
			{
			if (args[1])
				{
				args++;
				passargin = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-to"))
			{
			if (args[1])
				{
				args++;
				to = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-from"))
			{
			if (args[1])
				{
				args++;
				from = *args;
				}
			else badarg = 1;
			}
		else if (!strcmp (*args, "-subject"))
			{
			if (args[1])
				{
				args++;
				subject = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-signer"))
			{
			if (args[1])
				{
				args++;
				signerfile = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-recip"))
			{
			if (args[1])
				{
				args++;
				recipfile = *args;
				}
			else badarg = 1;
			}
		else if (!strcmp (*args, "-inkey"))
			{
			if (args[1])
				{
				args++;
				keyfile = *args;
				}
			else
				badarg = 1;
		}
		else if (!strcmp (*args, "-keyform"))
			{
			if (args[1])
				{
				args++;
				keyform = str2fmt(*args);
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-certfile"))
			{
			if (args[1])
				{
				args++;
				certfile = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-CAfile"))
			{
			if (args[1])
				{
				args++;
				CAfile = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-CApath"))
			{
			if (args[1])
				{
				args++;
				CApath = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-in"))
			{
			if (args[1])
				{
				args++;
				infile = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-inform"))
			{
			if (args[1])
				{
				args++;
				informat = str2fmt(*args);
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-outform"))
			{
			if (args[1])
				{
				args++;
				outformat = str2fmt(*args);
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-out"))
			{
			if (args[1])
				{
				args++;
				outfile = *args;
				}
			else
				badarg = 1;
			}
		else if (!strcmp (*args, "-content"))
			{
			if (args[1])
				{
				args++;
				contfile = *args;
				}
			else
				badarg = 1;
			}
		else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
			continue;
		else
			badarg = 1;
		args++;
		}


	if (operation == SMIME_SIGN)
		{
		if (!signerfile)
			{
			BIO_printf(bio_err, "No signer certificate specified\n");
			badarg = 1;
			}
		need_rand = 1;
		}
	else if (operation == SMIME_DECRYPT)
		{
		if (!recipfile && !keyfile)
			{
			BIO_printf(bio_err, "No recipient certificate or key specified\n");
			badarg = 1;
			}
		}
	else if (operation == SMIME_ENCRYPT)
		{
		if (!*args)
			{
			BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
			badarg = 1;
			}
		need_rand = 1;
		}
	else if (!operation)
		badarg = 1;

	if (badarg)
		{
		BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n");
		BIO_printf (bio_err, "where options are\n");
		BIO_printf (bio_err, "-encrypt       encrypt message\n");
		BIO_printf (bio_err, "-decrypt       decrypt encrypted message\n");
		BIO_printf (bio_err, "-sign          sign message\n");
		BIO_printf (bio_err, "-verify        verify signed message\n");
		BIO_printf (bio_err, "-pk7out        output PKCS#7 structure\n");
#ifndef OPENSSL_NO_DES
		BIO_printf (bio_err, "-des3          encrypt with triple DES\n");
		BIO_printf (bio_err, "-des           encrypt with DES\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf (bio_err, "-seed          encrypt with SEED\n");
#endif
#ifndef OPENSSL_NO_RC2
		BIO_printf (bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
		BIO_printf (bio_err, "-rc2-64        encrypt with RC2-64\n");
		BIO_printf (bio_err, "-rc2-128       encrypt with RC2-128\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
		BIO_printf (bio_err, "               encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n");
		BIO_printf (bio_err, "               encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf (bio_err, "-nointern      don't search certificates in message for signer\n");
		BIO_printf (bio_err, "-nosigs        don't verify message signature\n");
		BIO_printf (bio_err, "-noverify      don't verify signers certificate\n");
		BIO_printf (bio_err, "-nocerts       don't include signers certificate when signing\n");
		BIO_printf (bio_err, "-nodetach      use opaque signing\n");
		BIO_printf (bio_err, "-noattr        don't include any signed attributes\n");
		BIO_printf (bio_err, "-binary        don't translate message to text\n");
		BIO_printf (bio_err, "-certfile file other certificates file\n");
		BIO_printf (bio_err, "-signer file   signer certificate file\n");
		BIO_printf (bio_err, "-recip  file   recipient certificate file for decryption\n");
		BIO_printf (bio_err, "-in file       input file\n");
		BIO_printf (bio_err, "-inform arg    input format SMIME (default), PEM or DER\n");
		BIO_printf (bio_err, "-inkey file    input private key (if not signer or recipient)\n");
		BIO_printf (bio_err, "-keyform arg   input private key format (PEM or ENGINE)\n");
		BIO_printf (bio_err, "-out file      output file\n");
		BIO_printf (bio_err, "-outform arg   output format SMIME (default), PEM or DER\n");
		BIO_printf (bio_err, "-content file  supply or override content for detached signature\n");
		BIO_printf (bio_err, "-to addr       to address\n");
		BIO_printf (bio_err, "-from ad       from address\n");
		BIO_printf (bio_err, "-subject s     subject\n");
		BIO_printf (bio_err, "-text          include or delete text MIME headers\n");
		BIO_printf (bio_err, "-CApath dir    trusted certificates directory\n");
		BIO_printf (bio_err, "-CAfile file   trusted certificates file\n");
		BIO_printf (bio_err, "-crl_check     check revocation status of signer's certificate using CRLs\n");
		BIO_printf (bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf (bio_err, "-engine e      use engine e, possibly a hardware device.\n");
#endif
		BIO_printf (bio_err, "-passin arg    input file pass phrase source\n");
		BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,  "               load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,  "               the random number generator\n");
		BIO_printf (bio_err, "cert.pem       recipient certificate(s) for encryption\n");
		goto end;
		}

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if (!app_passwd(bio_err, passargin, NULL, &passin, NULL))
		{
		BIO_printf(bio_err, "Error getting password\n");
		goto end;
		}

	if (need_rand)
		{
		app_RAND_load_file(NULL, bio_err, (inrand != NULL));
		if (inrand != NULL)
			BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
				app_RAND_load_files(inrand));
		}

	ret = 2;

	if (operation != SMIME_SIGN)
		flags &= ~PKCS7_DETACHED;

	if (operation & SMIME_OP)
		{
		if (flags & PKCS7_BINARY)
			inmode = "rb";
		if (outformat == FORMAT_ASN1)
			outmode = "wb";
		}
	else
		{
		if (flags & PKCS7_BINARY)
			outmode = "wb";
		if (informat == FORMAT_ASN1)
			inmode = "rb";
		}

	if (operation == SMIME_ENCRYPT)
		{
		if (!cipher)
			{
#ifndef OPENSSL_NO_RC2			
			cipher = EVP_rc2_40_cbc();
#else
			BIO_printf(bio_err, "No cipher selected\n");
			goto end;
#endif
			}
		encerts = sk_X509_new_null();
		while (*args)
			{
			if (!(cert = load_cert(bio_err,*args,FORMAT_PEM,
				NULL, e, "recipient certificate file")))
				{
#if 0				/* An appropriate message is already printed */
				BIO_printf(bio_err, "Can't read recipient certificate file %s\n", *args);
#endif
				goto end;
				}
			sk_X509_push(encerts, cert);
			cert = NULL;
			args++;
			}
		}

	if (signerfile && (operation == SMIME_SIGN))
		{
		if (!(signer = load_cert(bio_err,signerfile,FORMAT_PEM, NULL,
			e, "signer certificate")))
			{
#if 0			/* An appropri message has already been printed */
			BIO_printf(bio_err, "Can't read signer certificate file %s\n", signerfile);
#endif
			goto end;
			}
		}

	if (certfile)
		{
		if (!(other = load_certs(bio_err,certfile,FORMAT_PEM, NULL,
			e, "certificate file")))
			{
#if 0			/* An appropriate message has already been printed */
			BIO_printf(bio_err, "Can't read certificate file %s\n", certfile);
#endif
			ERR_print_errors(bio_err);
			goto end;
			}
		}

	if (recipfile && (operation == SMIME_DECRYPT))
		{
		if (!(recip = load_cert(bio_err,recipfile,FORMAT_PEM,NULL,
			e, "recipient certificate file")))
			{
#if 0			/* An appropriate message has alrady been printed */
			BIO_printf(bio_err, "Can't read recipient certificate file %s\n", recipfile);
#endif
			ERR_print_errors(bio_err);
			goto end;
			}
		}

	if (operation == SMIME_DECRYPT)
		{
		if (!keyfile)
			keyfile = recipfile;
		}
	else if (operation == SMIME_SIGN)
		{
		if (!keyfile)
			keyfile = signerfile;
		}
	else keyfile = NULL;

	if (keyfile)
		{
		key = load_key(bio_err, keyfile, keyform, 0, passin, e,
			       "signing key file");
		if (!key)
			goto end;
		}

	if (infile)
		{
		if (!(in = BIO_new_file(infile, inmode)))
			{
			BIO_printf (bio_err,
				 "Can't open input file %s\n", infile);
			goto end;
			}
		}
	else
		in = BIO_new_fp(stdin, BIO_NOCLOSE);

	if (outfile)
		{
		if (!(out = BIO_new_file(outfile, outmode)))
			{
			BIO_printf (bio_err,
				 "Can't open output file %s\n", outfile);
			goto end;
			}
		}
	else
		{
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		    out = BIO_push(tmpbio, out);
		}
#endif
		}

	if (operation == SMIME_VERIFY)
		{
		if (!(store = setup_verify(bio_err, CAfile, CApath)))
			goto end;
		X509_STORE_set_verify_cb_func(store, smime_cb);
		if (vpm)
			X509_STORE_set1_param(store, vpm);
		}


	ret = 3;

	if (operation == SMIME_ENCRYPT)
		p7 = PKCS7_encrypt(encerts, in, cipher, flags);
	else if (operation == SMIME_SIGN)
		{
		/* If detached data and SMIME output enable partial
		 * signing.
		 */
		if ((flags & PKCS7_DETACHED) && (outformat == FORMAT_SMIME))
			flags |= PKCS7_STREAM;
		p7 = PKCS7_sign(signer, key, other, in, flags);
		}
	else
		{
		if (informat == FORMAT_SMIME) 
			p7 = SMIME_read_PKCS7(in, &indata);
		else if (informat == FORMAT_PEM) 
			p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
		else if (informat == FORMAT_ASN1) 
			p7 = d2i_PKCS7_bio(in, NULL);
		else
			{
			BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
			goto end;
			}

		if (!p7)
			{
			BIO_printf(bio_err, "Error reading S/MIME message\n");
			goto end;
			}
		if (contfile)
			{
			BIO_free(indata);
			if (!(indata = BIO_new_file(contfile, "rb")))
				{
				BIO_printf(bio_err, "Can't read content file %s\n", contfile);
				goto end;
				}
			}
		}

	if (!p7)
		{
		BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
		goto end;
		}

	ret = 4;
	if (operation == SMIME_DECRYPT)
		{
		if (!PKCS7_decrypt(p7, key, recip, out, flags))
			{
			BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
			goto end;
			}
		}
	else if (operation == SMIME_VERIFY)
		{
		STACK_OF(X509) *signers;
		if (PKCS7_verify(p7, other, store, indata, out, flags))
			BIO_printf(bio_err, "Verification successful\n");
		else
			{
			BIO_printf(bio_err, "Verification failure\n");
			goto end;
			}
		signers = PKCS7_get0_signers(p7, other, flags);
		if (!save_certs(signerfile, signers))
			{
			BIO_printf(bio_err, "Error writing signers to %s\n",
								signerfile);
			ret = 5;
			goto end;
			}
		sk_X509_free(signers);
		}
	else if (operation == SMIME_PK7OUT)
		PEM_write_bio_PKCS7(out, p7);
	else
		{
		if (to)
			BIO_printf(out, "To: %s\n", to);
		if (from)
			BIO_printf(out, "From: %s\n", from);
		if (subject)
			BIO_printf(out, "Subject: %s\n", subject);
		if (outformat == FORMAT_SMIME) 
			SMIME_write_PKCS7(out, p7, in, flags);
		else if (outformat == FORMAT_PEM) 
			PEM_write_bio_PKCS7(out,p7);
		else if (outformat == FORMAT_ASN1) 
			i2d_PKCS7_bio(out,p7);
		else
			{
			BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
			goto end;
			}
		}
	ret = 0;
end:
	if (need_rand)
		app_RAND_write_file(NULL, bio_err);
	if (ret) ERR_print_errors(bio_err);
	sk_X509_pop_free(encerts, X509_free);
	sk_X509_pop_free(other, X509_free);
	if (vpm)
		X509_VERIFY_PARAM_free(vpm);
	X509_STORE_free(store);
	X509_free(cert);
	X509_free(recip);
	X509_free(signer);
	EVP_PKEY_free(key);
	PKCS7_free(p7);
	BIO_free(in);
	BIO_free(indata);
	BIO_free_all(out);
	if (passin) OPENSSL_free(passin);
	return (ret);
}
コード例 #11
0
ファイル: smime.c プロジェクト: dgervais/openssl
int smime_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL, *indata = NULL;
    EVP_PKEY *key = NULL;
    PKCS7 *p7 = NULL;
    STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
    STACK_OF(X509) *encerts = NULL, *other = NULL;
    X509 *cert = NULL, *recip = NULL, *signer = NULL;
    X509_STORE *store = NULL;
    X509_VERIFY_PARAM *vpm = NULL;
    const EVP_CIPHER *cipher = NULL;
    const EVP_MD *sign_md = NULL;
    const char *CAfile = NULL, *CApath = NULL, *prog = NULL;
    char *certfile = NULL, *keyfile = NULL, *contfile = NULL, *inrand = NULL;
    char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile =
        NULL;
    char *passinarg = NULL, *passin = NULL, *to = NULL, *from =
        NULL, *subject = NULL;
    OPTION_CHOICE o;
    int noCApath = 0, noCAfile = 0;
    int flags = PKCS7_DETACHED, operation = 0, ret = 0, need_rand = 0, indef =
        0;
    int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform =
        FORMAT_PEM;
    int vpmtouched = 0, rv = 0;
    ENGINE *e = NULL;
    const char *mime_eol = "\n";

    if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
        return 1;

    prog = opt_init(argc, argv, smime_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(smime_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
                goto opthelp;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENCRYPT:
            operation = SMIME_ENCRYPT;
            break;
        case OPT_DECRYPT:
            operation = SMIME_DECRYPT;
            break;
        case OPT_SIGN:
            operation = SMIME_SIGN;
            break;
        case OPT_RESIGN:
            operation = SMIME_RESIGN;
            break;
        case OPT_VERIFY:
            operation = SMIME_VERIFY;
            break;
        case OPT_PK7OUT:
            operation = SMIME_PK7OUT;
            break;
        case OPT_TEXT:
            flags |= PKCS7_TEXT;
            break;
        case OPT_NOINTERN:
            flags |= PKCS7_NOINTERN;
            break;
        case OPT_NOVERIFY:
            flags |= PKCS7_NOVERIFY;
            break;
        case OPT_NOCHAIN:
            flags |= PKCS7_NOCHAIN;
            break;
        case OPT_NOCERTS:
            flags |= PKCS7_NOCERTS;
            break;
        case OPT_NOATTR:
            flags |= PKCS7_NOATTR;
            break;
        case OPT_NODETACH:
            flags &= ~PKCS7_DETACHED;
            break;
        case OPT_NOSMIMECAP:
            flags |= PKCS7_NOSMIMECAP;
            break;
        case OPT_BINARY:
            flags |= PKCS7_BINARY;
            break;
        case OPT_NOSIGS:
            flags |= PKCS7_NOSIGS;
            break;
        case OPT_STREAM:
        case OPT_INDEF:
            indef = 1;
            break;
        case OPT_NOINDEF:
            indef = 0;
            break;
        case OPT_CRLFEOL:
            flags |= PKCS7_CRLFEOL;
            mime_eol = "\r\n";
            break;
        case OPT_RAND:
            inrand = opt_arg();
            need_rand = 1;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_TO:
            to = opt_arg();
            break;
        case OPT_FROM:
            from = opt_arg();
            break;
        case OPT_SUBJECT:
            subject = opt_arg();
            break;
        case OPT_SIGNER:
            /* If previous -signer argument add signer to list */
            if (signerfile) {
                if (sksigners == NULL
                    && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                if (keyfile == NULL)
                    keyfile = signerfile;
                if (skkeys == NULL
                    && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(skkeys, keyfile);
                keyfile = NULL;
            }
            signerfile = opt_arg();
            break;
        case OPT_RECIP:
            recipfile = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_arg(), &sign_md))
                goto opthelp;
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &cipher))
                goto opthelp;
            break;
        case OPT_INKEY:
            /* If previous -inkey argument add signer to list */
            if (keyfile) {
                if (signerfile == NULL) {
                    BIO_printf(bio_err,
                               "%s: Must have -signer before -inkey\n", prog);
                    goto opthelp;
                }
                if (sksigners == NULL
                    && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                signerfile = NULL;
                if (skkeys == NULL
                    && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(skkeys, keyfile);
            }
            keyfile = opt_arg();
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
                goto opthelp;
            break;
        case OPT_CERTFILE:
            certfile = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_NOCAFILE:
            noCAfile = 1;
            break;
        case OPT_NOCAPATH:
            noCApath = 1;
            break;
        case OPT_CONTENT:
            contfile = opt_arg();
            break;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto opthelp;
            vpmtouched++;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
        BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
        goto opthelp;
    }

    if (operation & SMIME_SIGNERS) {
        /* Check to see if any final signer needs to be appended */
        if (keyfile && !signerfile) {
            BIO_puts(bio_err, "Illegal -inkey without -signer\n");
            goto opthelp;
        }
        if (signerfile) {
            if (!sksigners
                && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(sksigners, signerfile);
            if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            if (!keyfile)
                keyfile = signerfile;
            sk_OPENSSL_STRING_push(skkeys, keyfile);
        }
        if (!sksigners) {
            BIO_printf(bio_err, "No signer certificate specified\n");
            goto opthelp;
        }
        signerfile = NULL;
        keyfile = NULL;
        need_rand = 1;
    } else if (operation == SMIME_DECRYPT) {
        if (!recipfile && !keyfile) {
            BIO_printf(bio_err,
                       "No recipient certificate or key specified\n");
            goto opthelp;
        }
    } else if (operation == SMIME_ENCRYPT) {
        if (argc == 0) {
            BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
            goto opthelp;
        }
        need_rand = 1;
    } else if (!operation)
        goto opthelp;

    if (!app_passwd(passinarg, NULL, &passin, NULL)) {
        BIO_printf(bio_err, "Error getting password\n");
        goto end;
    }

    if (need_rand) {
        app_RAND_load_file(NULL, (inrand != NULL));
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));
    }

    ret = 2;

    if (!(operation & SMIME_SIGNERS))
        flags &= ~PKCS7_DETACHED;

    if (!(operation & SMIME_OP)) {
        if (flags & PKCS7_BINARY)
            outformat = FORMAT_BINARY;
    }

    if (!(operation & SMIME_IP)) {
        if (flags & PKCS7_BINARY)
            informat = FORMAT_BINARY;
    }

    if (operation == SMIME_ENCRYPT) {
        if (!cipher) {
#ifndef OPENSSL_NO_DES
            cipher = EVP_des_ede3_cbc();
#else
            BIO_printf(bio_err, "No cipher selected\n");
            goto end;
#endif
        }
        encerts = sk_X509_new_null();
        if (!encerts)
            goto end;
        while (*argv) {
            cert = load_cert(*argv, FORMAT_PEM,
                             "recipient certificate file");
            if (cert == NULL)
                goto end;
            sk_X509_push(encerts, cert);
            cert = NULL;
            argv++;
        }
    }

    if (certfile) {
        if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
                        "certificate file")) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (recipfile && (operation == SMIME_DECRYPT)) {
        if ((recip = load_cert(recipfile, FORMAT_PEM,
                               "recipient certificate file")) == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (operation == SMIME_DECRYPT) {
        if (!keyfile)
            keyfile = recipfile;
    } else if (operation == SMIME_SIGN) {
        if (!keyfile)
            keyfile = signerfile;
    } else
        keyfile = NULL;

    if (keyfile) {
        key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
        if (!key)
            goto end;
    }

    in = bio_open_default(infile, 'r', informat);
    if (in == NULL)
        goto end;

    if (operation & SMIME_IP) {
        if (informat == FORMAT_SMIME)
            p7 = SMIME_read_PKCS7(in, &indata);
        else if (informat == FORMAT_PEM)
            p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
        else if (informat == FORMAT_ASN1)
            p7 = d2i_PKCS7_bio(in, NULL);
        else {
            BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
            goto end;
        }

        if (!p7) {
            BIO_printf(bio_err, "Error reading S/MIME message\n");
            goto end;
        }
        if (contfile) {
            BIO_free(indata);
            if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
                BIO_printf(bio_err, "Can't read content file %s\n", contfile);
                goto end;
            }
        }
    }

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    if (operation == SMIME_VERIFY) {
        if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL)
            goto end;
        X509_STORE_set_verify_cb(store, smime_cb);
        if (vpmtouched)
            X509_STORE_set1_param(store, vpm);
    }

    ret = 3;

    if (operation == SMIME_ENCRYPT) {
        if (indef)
            flags |= PKCS7_STREAM;
        p7 = PKCS7_encrypt(encerts, in, cipher, flags);
    } else if (operation & SMIME_SIGNERS) {
        int i;
        /*
         * If detached data content we only enable streaming if S/MIME output
         * format.
         */
        if (operation == SMIME_SIGN) {
            if (flags & PKCS7_DETACHED) {
                if (outformat == FORMAT_SMIME)
                    flags |= PKCS7_STREAM;
            } else if (indef)
                flags |= PKCS7_STREAM;
            flags |= PKCS7_PARTIAL;
            p7 = PKCS7_sign(NULL, NULL, other, in, flags);
            if (!p7)
                goto end;
            if (flags & PKCS7_NOCERTS) {
                for (i = 0; i < sk_X509_num(other); i++) {
                    X509 *x = sk_X509_value(other, i);
                    PKCS7_add_certificate(p7, x);
                }
            }
        } else
            flags |= PKCS7_REUSE_DIGEST;
        for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
            signerfile = sk_OPENSSL_STRING_value(sksigners, i);
            keyfile = sk_OPENSSL_STRING_value(skkeys, i);
            signer = load_cert(signerfile, FORMAT_PEM,
                               "signer certificate");
            if (!signer)
                goto end;
            key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
            if (!key)
                goto end;
            if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags))
                goto end;
            X509_free(signer);
            signer = NULL;
            EVP_PKEY_free(key);
            key = NULL;
        }
        /* If not streaming or resigning finalize structure */
        if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
            if (!PKCS7_final(p7, in, flags))
                goto end;
        }
    }

    if (!p7) {
        BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
        goto end;
    }

    ret = 4;
    if (operation == SMIME_DECRYPT) {
        if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
            BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
            goto end;
        }
    } else if (operation == SMIME_VERIFY) {
        STACK_OF(X509) *signers;
        if (PKCS7_verify(p7, other, store, indata, out, flags))
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            goto end;
        }
        signers = PKCS7_get0_signers(p7, other, flags);
        if (!save_certs(signerfile, signers)) {
            BIO_printf(bio_err, "Error writing signers to %s\n", signerfile);
            ret = 5;
            goto end;
        }
        sk_X509_free(signers);
    } else if (operation == SMIME_PK7OUT)
        PEM_write_bio_PKCS7(out, p7);
    else {
        if (to)
            BIO_printf(out, "To: %s%s", to, mime_eol);
        if (from)
            BIO_printf(out, "From: %s%s", from, mime_eol);
        if (subject)
            BIO_printf(out, "Subject: %s%s", subject, mime_eol);
        if (outformat == FORMAT_SMIME) {
            if (operation == SMIME_RESIGN)
                rv = SMIME_write_PKCS7(out, p7, indata, flags);
            else
                rv = SMIME_write_PKCS7(out, p7, in, flags);
        } else if (outformat == FORMAT_PEM)
            rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags);
        else if (outformat == FORMAT_ASN1)
            rv = i2d_PKCS7_bio_stream(out, p7, in, flags);
        else {
            BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
            goto end;
        }
        if (rv == 0) {
            BIO_printf(bio_err, "Error writing output\n");
            ret = 3;
            goto end;
        }
    }
    ret = 0;
 end:
    if (need_rand)
        app_RAND_write_file(NULL);
    if (ret)
        ERR_print_errors(bio_err);
    sk_X509_pop_free(encerts, X509_free);
    sk_X509_pop_free(other, X509_free);
    X509_VERIFY_PARAM_free(vpm);
    sk_OPENSSL_STRING_free(sksigners);
    sk_OPENSSL_STRING_free(skkeys);
    X509_STORE_free(store);
    X509_free(cert);
    X509_free(recip);
    X509_free(signer);
    EVP_PKEY_free(key);
    PKCS7_free(p7);
    release_engine(e);
    BIO_free(in);
    BIO_free(indata);
    BIO_free_all(out);
    OPENSSL_free(passin);
    return (ret);
}
コード例 #12
0
ファイル: verify.c プロジェクト: DoctorLawrence/openssl
int verify_main(int argc, char **argv)
{
    ENGINE *e = NULL;
    STACK_OF(X509) *untrusted = NULL, *trusted = NULL;
    STACK_OF(X509_CRL) *crls = NULL;
    X509_STORE *store = NULL;
    X509_VERIFY_PARAM *vpm = NULL;
    char *prog, *CApath = NULL, *CAfile = NULL;
    char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;
    int vpmtouched = 0, crl_download = 0, show_chain = 0, i = 0, ret = 1;
    OPTION_CHOICE o;

    if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
        goto end;

    prog = opt_init(argc, argv, verify_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(verify_options);
            BIO_printf(bio_err, "Recognized usages:\n");
            for (i = 0; i < X509_PURPOSE_get_count(); i++) {
                X509_PURPOSE *ptmp;
                ptmp = X509_PURPOSE_get0(i);
                BIO_printf(bio_err, "\t%-10s\t%s\n",
                        X509_PURPOSE_get0_sname(ptmp),
                        X509_PURPOSE_get0_name(ptmp));
            }

            BIO_printf(bio_err, "Recognized verify names:\n");
            for (i = 0; i < X509_VERIFY_PARAM_get_count(); i++) {
                const X509_VERIFY_PARAM *vptmp;
                vptmp = X509_VERIFY_PARAM_get0(i);
                BIO_printf(bio_err, "\t%-10s\n",
                        X509_VERIFY_PARAM_get0_name(vptmp));
            }
            ret = 0;
            goto end;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto end;
            vpmtouched++;
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_UNTRUSTED:
            untfile = opt_arg();
            break;
        case OPT_TRUSTED:
            trustfile = opt_arg();
            break;
        case OPT_CRLFILE:
            crlfile = opt_arg();
            break;
        case OPT_CRL_DOWNLOAD:
            crl_download = 1;
            break;
        case OPT_SHOW_CHAIN:
            show_chain = 1;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_VERBOSE:
            v_verbose = 1;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (!(store = setup_verify(CAfile, CApath)))
        goto end;
    X509_STORE_set_verify_cb(store, cb);

    if (vpmtouched)
        X509_STORE_set1_param(store, vpm);

    ERR_clear_error();

    if (untfile) {
        untrusted = load_certs(untfile, FORMAT_PEM,
                               NULL, e, "untrusted certificates");
        if (!untrusted)
            goto end;
    }

    if (trustfile) {
        trusted = load_certs(trustfile, FORMAT_PEM,
                             NULL, e, "trusted certificates");
        if (!trusted)
            goto end;
    }

    if (crlfile) {
        crls = load_crls(crlfile, FORMAT_PEM, NULL, e, "other CRLs");
        if (!crls)
            goto end;
    }

    if (crl_download)
        store_setup_crl_download(store);

    ret = 0;
    if (argc < 1) {
        if (check(store, NULL, untrusted, trusted, crls, e, show_chain) != 1)
            ret = -1;
    } else {
        for (i = 0; i < argc; i++)
            if (check(store, argv[i], untrusted, trusted, crls, e,
                      show_chain) != 1)
                ret = -1;
    }

 end:
    X509_VERIFY_PARAM_free(vpm);
    X509_STORE_free(store);
    sk_X509_pop_free(untrusted, X509_free);
    sk_X509_pop_free(trusted, X509_free);
    sk_X509_CRL_pop_free(crls, X509_CRL_free);
    return (ret < 0 ? 2 : ret);
}
コード例 #13
0
ファイル: cms.c プロジェクト: Muffo/openssl
int cms_main(int argc, char **argv)
{
    ASN1_OBJECT *econtent_type = NULL;
    BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
    CMS_ContentInfo *cms = NULL, *rcms = NULL;
    CMS_ReceiptRequest *rr = NULL;
    ENGINE *e = NULL;
    EVP_PKEY *key = NULL;
    const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
    const EVP_MD *sign_md = NULL;
    STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
    STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
    STACK_OF(X509) *encerts = NULL, *other = NULL;
    X509 *cert = NULL, *recip = NULL, *signer = NULL;
    X509_STORE *store = NULL;
    X509_VERIFY_PARAM *vpm = NULL;
    char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
    const char *CAfile = NULL, *CApath = NULL;
    char *certsoutfile = NULL;
    int noCAfile = 0, noCApath = 0;
    char *infile = NULL, *outfile = NULL, *rctfile = NULL, *inrand = NULL;
    char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile =
        NULL;
    char *to = NULL, *from = NULL, *subject = NULL, *prog;
    cms_key_param *key_first = NULL, *key_param = NULL;
    int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched =
        0;
    int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
    int need_rand = 0, operation = 0, ret = 1, rr_print = 0, rr_allorfirst =
        -1;
    int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
    size_t secret_keylen = 0, secret_keyidlen = 0;
    unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
    unsigned char *secret_key = NULL, *secret_keyid = NULL;
    long ltmp;
    const char *mime_eol = "\n";
    OPTION_CHOICE o;

    if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
        return 1;

    prog = opt_init(argc, argv, cms_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(cms_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat))
                goto opthelp;
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDS, &outformat))
                goto opthelp;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_ENCRYPT:
            operation = SMIME_ENCRYPT;
            break;
        case OPT_DECRYPT:
            operation = SMIME_DECRYPT;
            break;
        case OPT_SIGN:
            operation = SMIME_SIGN;
            break;
        case OPT_SIGN_RECEIPT:
            operation = SMIME_SIGN_RECEIPT;
            break;
        case OPT_RESIGN:
            operation = SMIME_RESIGN;
            break;
        case OPT_VERIFY:
            operation = SMIME_VERIFY;
            break;
        case OPT_VERIFY_RETCODE:
            verify_retcode = 1;
            break;
        case OPT_VERIFY_RECEIPT:
            operation = SMIME_VERIFY_RECEIPT;
            rctfile = opt_arg();
            break;
        case OPT_CMSOUT:
            operation = SMIME_CMSOUT;
            break;
        case OPT_DATA_OUT:
            operation = SMIME_DATAOUT;
            break;
        case OPT_DATA_CREATE:
            operation = SMIME_DATA_CREATE;
            break;
        case OPT_DIGEST_VERIFY:
            operation = SMIME_DIGEST_VERIFY;
            break;
        case OPT_DIGEST_CREATE:
            operation = SMIME_DIGEST_CREATE;
            break;
        case OPT_COMPRESS:
            operation = SMIME_COMPRESS;
            break;
        case OPT_UNCOMPRESS:
            operation = SMIME_UNCOMPRESS;
            break;
        case OPT_ED_DECRYPT:
            operation = SMIME_ENCRYPTED_DECRYPT;
            break;
        case OPT_ED_ENCRYPT:
            operation = SMIME_ENCRYPTED_ENCRYPT;
            break;
        case OPT_DEBUG_DECRYPT:
            flags |= CMS_DEBUG_DECRYPT;
            break;
        case OPT_TEXT:
            flags |= CMS_TEXT;
            break;
        case OPT_ASCIICRLF:
            flags |= CMS_ASCIICRLF;
            break;
        case OPT_NOINTERN:
            flags |= CMS_NOINTERN;
            break;
        case OPT_NOVERIFY:
            flags |= CMS_NO_SIGNER_CERT_VERIFY;
            break;
        case OPT_NOCERTS:
            flags |= CMS_NOCERTS;
            break;
        case OPT_NOATTR:
            flags |= CMS_NOATTR;
            break;
        case OPT_NODETACH:
            flags &= ~CMS_DETACHED;
            break;
        case OPT_NOSMIMECAP:
            flags |= CMS_NOSMIMECAP;
            break;
        case OPT_BINARY:
            flags |= CMS_BINARY;
            break;
        case OPT_KEYID:
            flags |= CMS_USE_KEYID;
            break;
        case OPT_NOSIGS:
            flags |= CMS_NOSIGS;
            break;
        case OPT_NO_CONTENT_VERIFY:
            flags |= CMS_NO_CONTENT_VERIFY;
            break;
        case OPT_NO_ATTR_VERIFY:
            flags |= CMS_NO_ATTR_VERIFY;
            break;
        case OPT_INDEF:
            flags |= CMS_STREAM;
            break;
        case OPT_NOINDEF:
            flags &= ~CMS_STREAM;
            break;
        case OPT_NOOLDMIME:
            flags |= CMS_NOOLDMIMETYPE;
            break;
        case OPT_CRLFEOL:
            mime_eol = "\r\n";
            flags |= CMS_CRLFEOL;
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_RR_PRINT:
            rr_print = 1;
            break;
        case OPT_RR_ALL:
            rr_allorfirst = 0;
            break;
        case OPT_RR_FIRST:
            rr_allorfirst = 1;
            break;
        case OPT_RCTFORM:
            if (rctformat == FORMAT_SMIME)
                rcms = SMIME_read_CMS(rctin, NULL);
            else if (rctformat == FORMAT_PEM)
                rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
            else if (rctformat == FORMAT_ASN1)
                if (!opt_format(opt_arg(),
                                OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat))
                    goto opthelp;
            break;
        case OPT_CERTFILE:
            certfile = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_NOCAFILE:
            noCAfile = 1;
            break;
        case OPT_NOCAPATH:
            noCApath = 1;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_CONTENT:
            contfile = opt_arg();
            break;
        case OPT_RR_FROM:
            if (rr_from == NULL
                && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(rr_from, opt_arg());
            break;
        case OPT_RR_TO:
            if (rr_to == NULL
                && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(rr_to, opt_arg());
            break;
        case OPT_PRINT:
            noout = print = 1;
            break;
        case OPT_SECRETKEY:
            secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
            if (secret_key == NULL) {
                BIO_printf(bio_err, "Invalid key %s\n", opt_arg());
                goto end;
            }
            secret_keylen = (size_t)ltmp;
            break;
        case OPT_SECRETKEYID:
            secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp);
            if (secret_keyid == NULL) {
                BIO_printf(bio_err, "Invalid id %s\n", opt_arg());
                goto opthelp;
            }
            secret_keyidlen = (size_t)ltmp;
            break;
        case OPT_PWRI_PASSWORD:
            pwri_pass = (unsigned char *)opt_arg();
            break;
        case OPT_ECONTENT_TYPE:
            econtent_type = OBJ_txt2obj(opt_arg(), 0);
            if (econtent_type == NULL) {
                BIO_printf(bio_err, "Invalid OID %s\n", opt_arg());
                goto opthelp;
            }
            break;
        case OPT_RAND:
            inrand = opt_arg();
            need_rand = 1;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_TO:
            to = opt_arg();
            break;
        case OPT_FROM:
            from = opt_arg();
            break;
        case OPT_SUBJECT:
            subject = opt_arg();
            break;
        case OPT_CERTSOUT:
            certsoutfile = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_arg(), &sign_md))
                goto end;
            break;
        case OPT_SIGNER:
            /* If previous -signer argument add signer to list */
            if (signerfile) {
                if (sksigners == NULL
                    && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                if (keyfile == NULL)
                    keyfile = signerfile;
                if (skkeys == NULL
                    && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(skkeys, keyfile);
                keyfile = NULL;
            }
            signerfile = opt_arg();
            break;
        case OPT_INKEY:
            /* If previous -inkey argument add signer to list */
            if (keyfile) {
                if (signerfile == NULL) {
                    BIO_puts(bio_err, "Illegal -inkey without -signer\n");
                    goto end;
                }
                if (sksigners == NULL
                    && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                signerfile = NULL;
                if (skkeys == NULL
                    && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                sk_OPENSSL_STRING_push(skkeys, keyfile);
            }
            keyfile = opt_arg();
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
                goto opthelp;
            break;
        case OPT_RECIP:
            if (operation == SMIME_ENCRYPT) {
                if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL)
                    goto end;
                cert = load_cert(opt_arg(), FORMAT_PEM,
                                 "recipient certificate file");
                if (cert == NULL)
                    goto end;
                sk_X509_push(encerts, cert);
                cert = NULL;
            } else
                recipfile = opt_arg();
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &cipher))
                goto end;
            break;
        case OPT_KEYOPT:
            keyidx = -1;
            if (operation == SMIME_ENCRYPT) {
                if (encerts)
                    keyidx += sk_X509_num(encerts);
            } else {
                if (keyfile || signerfile)
                    keyidx++;
                if (skkeys)
                    keyidx += sk_OPENSSL_STRING_num(skkeys);
            }
            if (keyidx < 0) {
                BIO_printf(bio_err, "No key specified\n");
                goto opthelp;
            }
            if (key_param == NULL || key_param->idx != keyidx) {
                cms_key_param *nparam;
                nparam = app_malloc(sizeof(*nparam), "key param buffer");
                nparam->idx = keyidx;
                if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL)
                    goto end;
                nparam->next = NULL;
                if (key_first == NULL)
                    key_first = nparam;
                else
                    key_param->next = nparam;
                key_param = nparam;
            }
            sk_OPENSSL_STRING_push(key_param->param, opt_arg());
            break;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto end;
            vpmtouched++;
            break;
        case OPT_3DES_WRAP:
# ifndef OPENSSL_NO_DES
            wrap_cipher = EVP_des_ede3_wrap();
# endif
            break;
        case OPT_AES128_WRAP:
            wrap_cipher = EVP_aes_128_wrap();
            break;
        case OPT_AES192_WRAP:
            wrap_cipher = EVP_aes_192_wrap();
            break;
        case OPT_AES256_WRAP:
            wrap_cipher = EVP_aes_256_wrap();
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (((rr_allorfirst != -1) || rr_from) && !rr_to) {
        BIO_puts(bio_err, "No Signed Receipts Recipients\n");
        goto opthelp;
    }

    if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) {
        BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
        goto opthelp;
    }
    if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
        BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
        goto opthelp;
    }

    if (operation & SMIME_SIGNERS) {
        if (keyfile && !signerfile) {
            BIO_puts(bio_err, "Illegal -inkey without -signer\n");
            goto opthelp;
        }
        /* Check to see if any final signer needs to be appended */
        if (signerfile) {
            if (!sksigners
                && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(sksigners, signerfile);
            if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            if (!keyfile)
                keyfile = signerfile;
            sk_OPENSSL_STRING_push(skkeys, keyfile);
        }
        if (!sksigners) {
            BIO_printf(bio_err, "No signer certificate specified\n");
            goto opthelp;
        }
        signerfile = NULL;
        keyfile = NULL;
        need_rand = 1;
    }

    else if (operation == SMIME_DECRYPT) {
        if (!recipfile && !keyfile && !secret_key && !pwri_pass) {
            BIO_printf(bio_err,
                       "No recipient certificate or key specified\n");
            goto opthelp;
        }
    } else if (operation == SMIME_ENCRYPT) {
        if (*argv == NULL && !secret_key && !pwri_pass && !encerts) {
            BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
            goto opthelp;
        }
        need_rand = 1;
    } else if (!operation)
        goto opthelp;

    if (!app_passwd(passinarg, NULL, &passin, NULL)) {
        BIO_printf(bio_err, "Error getting password\n");
        goto end;
    }

    if (need_rand) {
        app_RAND_load_file(NULL, (inrand != NULL));
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));
    }

    ret = 2;

    if (!(operation & SMIME_SIGNERS))
        flags &= ~CMS_DETACHED;

    if (!(operation & SMIME_OP)) {
        if (flags & CMS_BINARY)
            outformat = FORMAT_BINARY;
    }

    if (!(operation & SMIME_IP)) {
        if (flags & CMS_BINARY)
            informat = FORMAT_BINARY;
    }

    if (operation == SMIME_ENCRYPT) {
        if (!cipher) {
# ifndef OPENSSL_NO_DES
            cipher = EVP_des_ede3_cbc();
# else
            BIO_printf(bio_err, "No cipher selected\n");
            goto end;
# endif
        }

        if (secret_key && !secret_keyid) {
            BIO_printf(bio_err, "No secret key id\n");
            goto end;
        }

        if (*argv && !encerts)
            if ((encerts = sk_X509_new_null()) == NULL)
                goto end;
        while (*argv) {
            if ((cert = load_cert(*argv, FORMAT_PEM,
                                  "recipient certificate file")) == NULL)
                goto end;
            sk_X509_push(encerts, cert);
            cert = NULL;
            argv++;
        }
    }

    if (certfile) {
        if (!load_certs(certfile, &other, FORMAT_PEM, NULL,
                        "certificate file")) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (recipfile && (operation == SMIME_DECRYPT)) {
        if ((recip = load_cert(recipfile, FORMAT_PEM,
                               "recipient certificate file")) == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (operation == SMIME_SIGN_RECEIPT) {
        if ((signer = load_cert(signerfile, FORMAT_PEM,
                                "receipt signer certificate file")) == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (operation == SMIME_DECRYPT) {
        if (!keyfile)
            keyfile = recipfile;
    } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
        if (!keyfile)
            keyfile = signerfile;
    } else
        keyfile = NULL;

    if (keyfile) {
        key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
        if (!key)
            goto end;
    }

    in = bio_open_default(infile, 'r', informat);
    if (in == NULL)
        goto end;

    if (operation & SMIME_IP) {
        if (informat == FORMAT_SMIME)
            cms = SMIME_read_CMS(in, &indata);
        else if (informat == FORMAT_PEM)
            cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
        else if (informat == FORMAT_ASN1)
            cms = d2i_CMS_bio(in, NULL);
        else {
            BIO_printf(bio_err, "Bad input format for CMS file\n");
            goto end;
        }

        if (!cms) {
            BIO_printf(bio_err, "Error reading S/MIME message\n");
            goto end;
        }
        if (contfile) {
            BIO_free(indata);
            if ((indata = BIO_new_file(contfile, "rb")) == NULL) {
                BIO_printf(bio_err, "Can't read content file %s\n", contfile);
                goto end;
            }
        }
        if (certsoutfile) {
            STACK_OF(X509) *allcerts;
            allcerts = CMS_get1_certs(cms);
            if (!save_certs(certsoutfile, allcerts)) {
                BIO_printf(bio_err,
                           "Error writing certs to %s\n", certsoutfile);
                ret = 5;
                goto end;
            }
            sk_X509_pop_free(allcerts, X509_free);
        }
    }

    if (rctfile) {
        char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
        if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) {
            BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
            goto end;
        }

        if (rctformat == FORMAT_SMIME)
            rcms = SMIME_read_CMS(rctin, NULL);
        else if (rctformat == FORMAT_PEM)
            rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
        else if (rctformat == FORMAT_ASN1)
            rcms = d2i_CMS_bio(rctin, NULL);
        else {
            BIO_printf(bio_err, "Bad input format for receipt\n");
            goto end;
        }

        if (!rcms) {
            BIO_printf(bio_err, "Error reading receipt\n");
            goto end;
        }
    }

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
        if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL)
            goto end;
        X509_STORE_set_verify_cb(store, cms_cb);
        if (vpmtouched)
            X509_STORE_set1_param(store, vpm);
    }

    ret = 3;

    if (operation == SMIME_DATA_CREATE) {
        cms = CMS_data_create(in, flags);
    } else if (operation == SMIME_DIGEST_CREATE) {
        cms = CMS_digest_create(in, sign_md, flags);
    } else if (operation == SMIME_COMPRESS) {
        cms = CMS_compress(in, -1, flags);
    } else if (operation == SMIME_ENCRYPT) {
        int i;
        flags |= CMS_PARTIAL;
        cms = CMS_encrypt(NULL, in, cipher, flags);
        if (!cms)
            goto end;
        for (i = 0; i < sk_X509_num(encerts); i++) {
            CMS_RecipientInfo *ri;
            cms_key_param *kparam;
            int tflags = flags;
            X509 *x = sk_X509_value(encerts, i);
            for (kparam = key_first; kparam; kparam = kparam->next) {
                if (kparam->idx == i) {
                    tflags |= CMS_KEY_PARAM;
                    break;
                }
            }
            ri = CMS_add1_recipient_cert(cms, x, tflags);
            if (!ri)
                goto end;
            if (kparam) {
                EVP_PKEY_CTX *pctx;
                pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
                if (!cms_set_pkey_param(pctx, kparam->param))
                    goto end;
            }
            if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
                && wrap_cipher) {
                EVP_CIPHER_CTX *wctx;
                wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
                EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
            }
        }

        if (secret_key) {
            if (!CMS_add0_recipient_key(cms, NID_undef,
                                        secret_key, secret_keylen,
                                        secret_keyid, secret_keyidlen,
                                        NULL, NULL, NULL))
                goto end;
            /* NULL these because call absorbs them */
            secret_key = NULL;
            secret_keyid = NULL;
        }
        if (pwri_pass) {
            pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass);
            if (!pwri_tmp)
                goto end;
            if (!CMS_add0_recipient_password(cms,
                                             -1, NID_undef, NID_undef,
                                             pwri_tmp, -1, NULL))
                goto end;
            pwri_tmp = NULL;
        }
        if (!(flags & CMS_STREAM)) {
            if (!CMS_final(cms, in, NULL, flags))
                goto end;
        }
    } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
        cms = CMS_EncryptedData_encrypt(in, cipher,
                                        secret_key, secret_keylen, flags);

    } else if (operation == SMIME_SIGN_RECEIPT) {
        CMS_ContentInfo *srcms = NULL;
        STACK_OF(CMS_SignerInfo) *sis;
        CMS_SignerInfo *si;
        sis = CMS_get0_SignerInfos(cms);
        if (!sis)
            goto end;
        si = sk_CMS_SignerInfo_value(sis, 0);
        srcms = CMS_sign_receipt(si, signer, key, other, flags);
        if (!srcms)
            goto end;
        CMS_ContentInfo_free(cms);
        cms = srcms;
    } else if (operation & SMIME_SIGNERS) {
        int i;
        /*
         * If detached data content we enable streaming if S/MIME output
         * format.
         */
        if (operation == SMIME_SIGN) {

            if (flags & CMS_DETACHED) {
                if (outformat == FORMAT_SMIME)
                    flags |= CMS_STREAM;
            }
            flags |= CMS_PARTIAL;
            cms = CMS_sign(NULL, NULL, other, in, flags);
            if (!cms)
                goto end;
            if (econtent_type)
                CMS_set1_eContentType(cms, econtent_type);

            if (rr_to) {
                rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
                if (!rr) {
                    BIO_puts(bio_err,
                             "Signed Receipt Request Creation Error\n");
                    goto end;
                }
            }
        } else
            flags |= CMS_REUSE_DIGEST;
        for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
            CMS_SignerInfo *si;
            cms_key_param *kparam;
            int tflags = flags;
            signerfile = sk_OPENSSL_STRING_value(sksigners, i);
            keyfile = sk_OPENSSL_STRING_value(skkeys, i);

            signer = load_cert(signerfile, FORMAT_PEM, "signer certificate");
            if (!signer)
                goto end;
            key = load_key(keyfile, keyform, 0, passin, e, "signing key file");
            if (!key)
                goto end;
            for (kparam = key_first; kparam; kparam = kparam->next) {
                if (kparam->idx == i) {
                    tflags |= CMS_KEY_PARAM;
                    break;
                }
            }
            si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
            if (!si)
                goto end;
            if (kparam) {
                EVP_PKEY_CTX *pctx;
                pctx = CMS_SignerInfo_get0_pkey_ctx(si);
                if (!cms_set_pkey_param(pctx, kparam->param))
                    goto end;
            }
            if (rr && !CMS_add1_ReceiptRequest(si, rr))
                goto end;
            X509_free(signer);
            signer = NULL;
            EVP_PKEY_free(key);
            key = NULL;
        }
        /* If not streaming or resigning finalize structure */
        if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
            if (!CMS_final(cms, in, NULL, flags))
                goto end;
        }
    }

    if (!cms) {
        BIO_printf(bio_err, "Error creating CMS structure\n");
        goto end;
    }

    ret = 4;
    if (operation == SMIME_DECRYPT) {
        if (flags & CMS_DEBUG_DECRYPT)
            CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);

        if (secret_key) {
            if (!CMS_decrypt_set1_key(cms,
                                      secret_key, secret_keylen,
                                      secret_keyid, secret_keyidlen)) {
                BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
                goto end;
            }
        }

        if (key) {
            if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
                BIO_puts(bio_err, "Error decrypting CMS using private key\n");
                goto end;
            }
        }

        if (pwri_pass) {
            if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
                BIO_puts(bio_err, "Error decrypting CMS using password\n");
                goto end;
            }
        }

        if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
            BIO_printf(bio_err, "Error decrypting CMS structure\n");
            goto end;
        }
    } else if (operation == SMIME_DATAOUT) {
        if (!CMS_data(cms, out, flags))
            goto end;
    } else if (operation == SMIME_UNCOMPRESS) {
        if (!CMS_uncompress(cms, indata, out, flags))
            goto end;
    } else if (operation == SMIME_DIGEST_VERIFY) {
        if (CMS_digest_verify(cms, indata, out, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            goto end;
        }
    } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
        if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
                                       indata, out, flags))
            goto end;
    } else if (operation == SMIME_VERIFY) {
        if (CMS_verify(cms, other, store, indata, out, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            if (verify_retcode)
                ret = verify_err + 32;
            goto end;
        }
        if (signerfile) {
            STACK_OF(X509) *signers;
            signers = CMS_get0_signers(cms);
            if (!save_certs(signerfile, signers)) {
                BIO_printf(bio_err,
                           "Error writing signers to %s\n", signerfile);
                ret = 5;
                goto end;
            }
            sk_X509_free(signers);
        }
        if (rr_print)
            receipt_request_print(cms);

    } else if (operation == SMIME_VERIFY_RECEIPT) {
        if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            goto end;
        }
    } else {
        if (noout) {
            if (print)
                CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
        } else if (outformat == FORMAT_SMIME) {
            if (to)
                BIO_printf(out, "To: %s%s", to, mime_eol);
            if (from)
                BIO_printf(out, "From: %s%s", from, mime_eol);
            if (subject)
                BIO_printf(out, "Subject: %s%s", subject, mime_eol);
            if (operation == SMIME_RESIGN)
                ret = SMIME_write_CMS(out, cms, indata, flags);
            else
                ret = SMIME_write_CMS(out, cms, in, flags);
        } else if (outformat == FORMAT_PEM)
            ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
        else if (outformat == FORMAT_ASN1)
            ret = i2d_CMS_bio_stream(out, cms, in, flags);
        else {
            BIO_printf(bio_err, "Bad output format for CMS file\n");
            goto end;
        }
        if (ret <= 0) {
            ret = 6;
            goto end;
        }
    }
    ret = 0;
 end:
    if (ret)
        ERR_print_errors(bio_err);
    if (need_rand)
        app_RAND_write_file(NULL);
    sk_X509_pop_free(encerts, X509_free);
    sk_X509_pop_free(other, X509_free);
    X509_VERIFY_PARAM_free(vpm);
    sk_OPENSSL_STRING_free(sksigners);
    sk_OPENSSL_STRING_free(skkeys);
    OPENSSL_free(secret_key);
    OPENSSL_free(secret_keyid);
    OPENSSL_free(pwri_tmp);
    ASN1_OBJECT_free(econtent_type);
    CMS_ReceiptRequest_free(rr);
    sk_OPENSSL_STRING_free(rr_to);
    sk_OPENSSL_STRING_free(rr_from);
    for (key_param = key_first; key_param;) {
        cms_key_param *tparam;
        sk_OPENSSL_STRING_free(key_param->param);
        tparam = key_param->next;
        OPENSSL_free(key_param);
        key_param = tparam;
    }
    X509_STORE_free(store);
    X509_free(cert);
    X509_free(recip);
    X509_free(signer);
    EVP_PKEY_free(key);
    CMS_ContentInfo_free(cms);
    CMS_ContentInfo_free(rcms);
    BIO_free(rctin);
    BIO_free(in);
    BIO_free(indata);
    BIO_free_all(out);
    OPENSSL_free(passin);
    return (ret);
}
コード例 #14
0
ファイル: pkcs12.c プロジェクト: VaryJames/Sample
int pkcs12_main(int argc, char **argv)
{
    char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
    char *name = NULL, *csp_name = NULL;
    char pass[50], macpass[50];
    int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
    int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
# ifndef OPENSSL_NO_RC2
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
# else
    int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
# endif
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int ret = 1, macver = 1, noprompt = 0, add_lmk = 0;
    char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
    char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
    char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
    char *prog;
    ENGINE *e = NULL;
    BIO *in = NULL, *out = NULL;
    PKCS12 *p12 = NULL;
    STACK_OF(OPENSSL_STRING) *canames = NULL;
    const EVP_CIPHER *enc = EVP_des_ede3_cbc();
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, pkcs12_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkcs12_options);
            ret = 0;
            goto end;
        case OPT_NOKEYS:
            options |= NOKEYS;
            break;
        case OPT_KEYEX:
            keytype = KEY_EX;
            break;
        case OPT_KEYSIG:
            keytype = KEY_SIG;
            break;
        case OPT_NOCERTS:
            options |= NOCERTS;
            break;
        case OPT_CLCERTS:
            options |= CLCERTS;
            break;
        case OPT_CACERTS:
            options |= CACERTS;
            break;
        case OPT_NOOUT:
            options |= (NOKEYS | NOCERTS);
            break;
        case OPT_INFO:
            options |= INFO;
            break;
        case OPT_CHAIN:
            chain = 1;
            break;
        case OPT_TWOPASS:
            twopass = 1;
            break;
        case OPT_NOMACVER:
            macver = 0;
            break;
        case OPT_DESCERT:
            cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
            break;
        case OPT_EXPORT:
            export_cert = 1;
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &enc))
                goto opthelp;
            break;
        case OPT_NOITER:
            iter = 1;
            break;
        case OPT_MACITER:
            maciter = PKCS12_DEFAULT_ITER;
            break;
        case OPT_NOMACITER:
            maciter = 1;
            break;
        case OPT_NOMAC:
            maciter = -1;
            break;
        case OPT_MACALG:
            macalg = opt_arg();
            break;
        case OPT_NODES:
            enc = NULL;
            break;
        case OPT_CERTPBE:
            if (!set_pbe(&cert_pbe, opt_arg()))
                goto opthelp;
            break;
        case OPT_KEYPBE:
            if (!set_pbe(&key_pbe, opt_arg()))
                goto opthelp;
            break;
        case OPT_RAND:
            inrand = opt_arg();
            break;
        case OPT_INKEY:
            keyname = opt_arg();
            break;
        case OPT_CERTFILE:
            certfile = opt_arg();
            break;
        case OPT_NAME:
            name = opt_arg();
            break;
        case OPT_LMK:
            add_lmk = 1;
            break;
        case OPT_CSP:
            csp_name = opt_arg();
            break;
        case OPT_CANAME:
            if (canames == NULL
                && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(canames, opt_arg());
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_PASSWORD:
            passarg = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (passarg) {
        if (export_cert)
            passoutarg = passarg;
        else
            passinarg = passarg;
    }

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if (!cpass) {
        if (export_cert)
            cpass = passout;
        else
            cpass = passin;
    }

    if (cpass) {
        mpass = cpass;
        noprompt = 1;
    } else {
        cpass = pass;
        mpass = macpass;
    }

    if (export_cert || inrand) {
        app_RAND_load_file(NULL, (inrand != NULL));
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));
    }

    in = bio_open_default(infile, "rb");
    if (in == NULL)
        goto end;

    out = bio_open_default(outfile, "wb");
    if (out == NULL)
        goto end;

    if (twopass) {
        if (EVP_read_pw_string
            (macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
            goto end;
        }
    }

    if (export_cert) {
        EVP_PKEY *key = NULL;
        X509 *ucert = NULL, *x = NULL;
        STACK_OF(X509) *certs = NULL;
        const EVP_MD *macmd = NULL;
        unsigned char *catmp = NULL;
        int i;

        if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
            BIO_printf(bio_err, "Nothing to do!\n");
            goto export_end;
        }

        if (options & NOCERTS)
            chain = 0;

        if (!(options & NOKEYS)) {
            key = load_key(keyname ? keyname : infile,
                           FORMAT_PEM, 1, passin, e, "private key");
            if (!key)
                goto export_end;
        }

        /* Load in all certs in input file */
        if (!(options & NOCERTS)) {
            certs = load_certs(infile, FORMAT_PEM, NULL, e,
                               "certificates");
            if (!certs)
                goto export_end;

            if (key) {
                /* Look for matching private key */
                for (i = 0; i < sk_X509_num(certs); i++) {
                    x = sk_X509_value(certs, i);
                    if (X509_check_private_key(x, key)) {
                        ucert = x;
                        /* Zero keyid and alias */
                        X509_keyid_set1(ucert, NULL, 0);
                        X509_alias_set1(ucert, NULL, 0);
                        /* Remove from list */
                        (void)sk_X509_delete(certs, i);
                        break;
                    }
                }
                if (!ucert) {
                    BIO_printf(bio_err,
                               "No certificate matches private key\n");
                    goto export_end;
                }
            }

        }

        /* Add any more certificates asked for */
        if (certfile) {
            STACK_OF(X509) *morecerts = NULL;
            if (!(morecerts = load_certs(certfile, FORMAT_PEM, NULL, e,
                                         "certificates from certfile")))
                goto export_end;
            while (sk_X509_num(morecerts) > 0)
                sk_X509_push(certs, sk_X509_shift(morecerts));
            sk_X509_free(morecerts);
        }

        /* If chaining get chain from user cert */
        if (chain) {
            int vret;
            STACK_OF(X509) *chain2;
            X509_STORE *store;
            if (!(store = setup_verify(CAfile, CApath)))
                goto export_end;

            vret = get_cert_chain(ucert, store, &chain2);
            X509_STORE_free(store);

            if (!vret) {
                /* Exclude verified certificate */
                for (i = 1; i < sk_X509_num(chain2); i++)
                    sk_X509_push(certs, sk_X509_value(chain2, i));
                /* Free first certificate */
                X509_free(sk_X509_value(chain2, 0));
                sk_X509_free(chain2);
            } else {
                if (vret >= 0)
                    BIO_printf(bio_err, "Error %s getting chain.\n",
                               X509_verify_cert_error_string(vret));
                else
                    ERR_print_errors(bio_err);
                goto export_end;
            }
        }

        /* Add any CA names */

        for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
            catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
            X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
        }

        if (csp_name && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
                                      MBSTRING_ASC, (unsigned char *)csp_name,
                                      -1);

        if (add_lmk && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);

        if (!noprompt &&
            EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
            goto export_end;
        }
        if (!twopass)
            BUF_strlcpy(macpass, pass, sizeof macpass);

        p12 = PKCS12_create(cpass, name, key, ucert, certs,
                            key_pbe, cert_pbe, iter, -1, keytype);

        if (!p12) {
            ERR_print_errors(bio_err);
            goto export_end;
        }

        if (macalg) {
            if (!opt_md(macalg, &macmd))
                goto opthelp;
        }

        if (maciter != -1)
            PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);

        i2d_PKCS12_bio(out, p12);

        ret = 0;

 export_end:

        EVP_PKEY_free(key);
        if (certs)
            sk_X509_pop_free(certs, X509_free);
        if (ucert)
            X509_free(ucert);

        goto end;

    }

    if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (!noprompt
        && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
        goto end;
    }

    if (!twopass)
        BUF_strlcpy(macpass, pass, sizeof macpass);

    if ((options & INFO) && p12->mac)
        BIO_printf(bio_err, "MAC Iteration %ld\n",
                   p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
    if (macver) {
        /* If we enter empty password try no password first */
        if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
            /* If mac and crypto pass the same set it to NULL too */
            if (!twopass)
                cpass = NULL;
        } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
            BIO_printf(bio_err, "Mac verify error: invalid password?\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
        BIO_printf(bio_err, "Error outputting keys and certificates\n");
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;
 end:
    PKCS12_free(p12);
    if (export_cert || inrand)
        app_RAND_write_file(NULL);
    BIO_free(in);
    BIO_free_all(out);
    if (canames)
        sk_OPENSSL_STRING_free(canames);
    if (passin)
        OPENSSL_free(passin);
    if (passout)
        OPENSSL_free(passout);
    return (ret);
}
コード例 #15
0
ファイル: smime.c プロジェクト: Heratom/Firefly-project
int
smime_main(int argc, char **argv)
{
	ENGINE *e = NULL;
	int operation = 0;
	int ret = 0;
	char **args;
	const char *inmode = "r", *outmode = "w";
	char *infile = NULL, *outfile = NULL;
	char *signerfile = NULL, *recipfile = NULL;
	STACK_OF(OPENSSL_STRING) * sksigners = NULL, *skkeys = NULL;
	char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
	const EVP_CIPHER *cipher = NULL;
	PKCS7 *p7 = NULL;
	X509_STORE *store = NULL;
	X509 *cert = NULL, *recip = NULL, *signer = NULL;
	EVP_PKEY *key = NULL;
	STACK_OF(X509) * encerts = NULL, *other = NULL;
	BIO *in = NULL, *out = NULL, *indata = NULL;
	int badarg = 0;
	int flags = PKCS7_DETACHED;
	char *to = NULL, *from = NULL, *subject = NULL;
	char *CAfile = NULL, *CApath = NULL;
	char *passargin = NULL, *passin = NULL;
	int indef = 0;
	const EVP_MD *sign_md = NULL;
	int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
	int keyform = FORMAT_PEM;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif

	X509_VERIFY_PARAM *vpm = NULL;

	args = argv + 1;
	ret = 1;

	while (!badarg && *args && *args[0] == '-') {
		if (!strcmp(*args, "-encrypt"))
			operation = SMIME_ENCRYPT;
		else if (!strcmp(*args, "-decrypt"))
			operation = SMIME_DECRYPT;
		else if (!strcmp(*args, "-sign"))
			operation = SMIME_SIGN;
		else if (!strcmp(*args, "-resign"))
			operation = SMIME_RESIGN;
		else if (!strcmp(*args, "-verify"))
			operation = SMIME_VERIFY;
		else if (!strcmp(*args, "-pk7out"))
			operation = SMIME_PK7OUT;
#ifndef OPENSSL_NO_DES
		else if (!strcmp(*args, "-des3"))
			cipher = EVP_des_ede3_cbc();
		else if (!strcmp(*args, "-des"))
			cipher = EVP_des_cbc();
#endif
#ifndef OPENSSL_NO_RC2
		else if (!strcmp(*args, "-rc2-40"))
			cipher = EVP_rc2_40_cbc();
		else if (!strcmp(*args, "-rc2-128"))
			cipher = EVP_rc2_cbc();
		else if (!strcmp(*args, "-rc2-64"))
			cipher = EVP_rc2_64_cbc();
#endif
#ifndef OPENSSL_NO_AES
		else if (!strcmp(*args, "-aes128"))
			cipher = EVP_aes_128_cbc();
		else if (!strcmp(*args, "-aes192"))
			cipher = EVP_aes_192_cbc();
		else if (!strcmp(*args, "-aes256"))
			cipher = EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
		else if (!strcmp(*args, "-camellia128"))
			cipher = EVP_camellia_128_cbc();
		else if (!strcmp(*args, "-camellia192"))
			cipher = EVP_camellia_192_cbc();
		else if (!strcmp(*args, "-camellia256"))
			cipher = EVP_camellia_256_cbc();
#endif
		else if (!strcmp(*args, "-text"))
			flags |= PKCS7_TEXT;
		else if (!strcmp(*args, "-nointern"))
			flags |= PKCS7_NOINTERN;
		else if (!strcmp(*args, "-noverify"))
			flags |= PKCS7_NOVERIFY;
		else if (!strcmp(*args, "-nochain"))
			flags |= PKCS7_NOCHAIN;
		else if (!strcmp(*args, "-nocerts"))
			flags |= PKCS7_NOCERTS;
		else if (!strcmp(*args, "-noattr"))
			flags |= PKCS7_NOATTR;
		else if (!strcmp(*args, "-nodetach"))
			flags &= ~PKCS7_DETACHED;
		else if (!strcmp(*args, "-nosmimecap"))
			flags |= PKCS7_NOSMIMECAP;
		else if (!strcmp(*args, "-binary"))
			flags |= PKCS7_BINARY;
		else if (!strcmp(*args, "-nosigs"))
			flags |= PKCS7_NOSIGS;
		else if (!strcmp(*args, "-stream"))
			indef = 1;
		else if (!strcmp(*args, "-indef"))
			indef = 1;
		else if (!strcmp(*args, "-noindef"))
			indef = 0;
		else if (!strcmp(*args, "-nooldmime"))
			flags |= PKCS7_NOOLDMIMETYPE;
		else if (!strcmp(*args, "-crlfeol"))
			flags |= PKCS7_CRLFEOL;
#ifndef OPENSSL_NO_ENGINE
		else if (!strcmp(*args, "-engine")) {
			if (!args[1])
				goto argerr;
			engine = *++args;
		}
#endif
		else if (!strcmp(*args, "-passin")) {
			if (!args[1])
				goto argerr;
			passargin = *++args;
		} else if (!strcmp(*args, "-to")) {
			if (!args[1])
				goto argerr;
			to = *++args;
		} else if (!strcmp(*args, "-from")) {
			if (!args[1])
				goto argerr;
			from = *++args;
		} else if (!strcmp(*args, "-subject")) {
			if (!args[1])
				goto argerr;
			subject = *++args;
		} else if (!strcmp(*args, "-signer")) {
			if (!args[1])
				goto argerr;
			/* If previous -signer argument add signer to list */

			if (signerfile) {
				if (!sksigners)
					sksigners = sk_OPENSSL_STRING_new_null();
				sk_OPENSSL_STRING_push(sksigners, signerfile);
				if (!keyfile)
					keyfile = signerfile;
				if (!skkeys)
					skkeys = sk_OPENSSL_STRING_new_null();
				sk_OPENSSL_STRING_push(skkeys, keyfile);
				keyfile = NULL;
			}
			signerfile = *++args;
		} else if (!strcmp(*args, "-recip")) {
			if (!args[1])
				goto argerr;
			recipfile = *++args;
		} else if (!strcmp(*args, "-md")) {
			if (!args[1])
				goto argerr;
			sign_md = EVP_get_digestbyname(*++args);
			if (sign_md == NULL) {
				BIO_printf(bio_err, "Unknown digest %s\n",
				    *args);
				goto argerr;
			}
		} else if (!strcmp(*args, "-inkey")) {
			if (!args[1])
				goto argerr;
			/* If previous -inkey arument add signer to list */
			if (keyfile) {
				if (!signerfile) {
					BIO_puts(bio_err, "Illegal -inkey without -signer\n");
					goto argerr;
				}
				if (!sksigners)
					sksigners = sk_OPENSSL_STRING_new_null();
				sk_OPENSSL_STRING_push(sksigners, signerfile);
				signerfile = NULL;
				if (!skkeys)
					skkeys = sk_OPENSSL_STRING_new_null();
				sk_OPENSSL_STRING_push(skkeys, keyfile);
			}
			keyfile = *++args;
		} else if (!strcmp(*args, "-keyform")) {
			if (!args[1])
				goto argerr;
			keyform = str2fmt(*++args);
		} else if (!strcmp(*args, "-certfile")) {
			if (!args[1])
				goto argerr;
			certfile = *++args;
		} else if (!strcmp(*args, "-CAfile")) {
			if (!args[1])
				goto argerr;
			CAfile = *++args;
		} else if (!strcmp(*args, "-CApath")) {
			if (!args[1])
				goto argerr;
			CApath = *++args;
		} else if (!strcmp(*args, "-in")) {
			if (!args[1])
				goto argerr;
			infile = *++args;
		} else if (!strcmp(*args, "-inform")) {
			if (!args[1])
				goto argerr;
			informat = str2fmt(*++args);
		} else if (!strcmp(*args, "-outform")) {
			if (!args[1])
				goto argerr;
			outformat = str2fmt(*++args);
		} else if (!strcmp(*args, "-out")) {
			if (!args[1])
				goto argerr;
			outfile = *++args;
		} else if (!strcmp(*args, "-content")) {
			if (!args[1])
				goto argerr;
			contfile = *++args;
		} else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
			continue;
		else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
			badarg = 1;
		args++;
	}

	if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
		BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
		goto argerr;
	}
	if (operation & SMIME_SIGNERS) {
		/* Check to see if any final signer needs to be appended */
		if (keyfile && !signerfile) {
			BIO_puts(bio_err, "Illegal -inkey without -signer\n");
			goto argerr;
		}
		if (signerfile) {
			if (!sksigners)
				sksigners = sk_OPENSSL_STRING_new_null();
			sk_OPENSSL_STRING_push(sksigners, signerfile);
			if (!skkeys)
				skkeys = sk_OPENSSL_STRING_new_null();
			if (!keyfile)
				keyfile = signerfile;
			sk_OPENSSL_STRING_push(skkeys, keyfile);
		}
		if (!sksigners) {
			BIO_printf(bio_err, "No signer certificate specified\n");
			badarg = 1;
		}
		signerfile = NULL;
		keyfile = NULL;
	} else if (operation == SMIME_DECRYPT) {
		if (!recipfile && !keyfile) {
			BIO_printf(bio_err, "No recipient certificate or key specified\n");
			badarg = 1;
		}
	} else if (operation == SMIME_ENCRYPT) {
		if (!*args) {
			BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
			badarg = 1;
		}
	} else if (!operation)
		badarg = 1;

	if (badarg) {
argerr:
		BIO_printf(bio_err, "Usage smime [options] cert.pem ...\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-encrypt       encrypt message\n");
		BIO_printf(bio_err, "-decrypt       decrypt encrypted message\n");
		BIO_printf(bio_err, "-sign          sign message\n");
		BIO_printf(bio_err, "-verify        verify signed message\n");
		BIO_printf(bio_err, "-pk7out        output PKCS#7 structure\n");
#ifndef OPENSSL_NO_DES
		BIO_printf(bio_err, "-des3          encrypt with triple DES\n");
		BIO_printf(bio_err, "-des           encrypt with DES\n");
#endif
#ifndef OPENSSL_NO_RC2
		BIO_printf(bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
		BIO_printf(bio_err, "-rc2-64        encrypt with RC2-64\n");
		BIO_printf(bio_err, "-rc2-128       encrypt with RC2-128\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
		BIO_printf(bio_err, "               encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err, "               encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err, "-nointern      don't search certificates in message for signer\n");
		BIO_printf(bio_err, "-nosigs        don't verify message signature\n");
		BIO_printf(bio_err, "-noverify      don't verify signers certificate\n");
		BIO_printf(bio_err, "-nocerts       don't include signers certificate when signing\n");
		BIO_printf(bio_err, "-nodetach      use opaque signing\n");
		BIO_printf(bio_err, "-noattr        don't include any signed attributes\n");
		BIO_printf(bio_err, "-binary        don't translate message to text\n");
		BIO_printf(bio_err, "-certfile file other certificates file\n");
		BIO_printf(bio_err, "-signer file   signer certificate file\n");
		BIO_printf(bio_err, "-recip  file   recipient certificate file for decryption\n");
		BIO_printf(bio_err, "-in file       input file\n");
		BIO_printf(bio_err, "-inform arg    input format SMIME (default), PEM or DER\n");
		BIO_printf(bio_err, "-inkey file    input private key (if not signer or recipient)\n");
		BIO_printf(bio_err, "-keyform arg   input private key format (PEM or ENGINE)\n");
		BIO_printf(bio_err, "-out file      output file\n");
		BIO_printf(bio_err, "-outform arg   output format SMIME (default), PEM or DER\n");
		BIO_printf(bio_err, "-content file  supply or override content for detached signature\n");
		BIO_printf(bio_err, "-to addr       to address\n");
		BIO_printf(bio_err, "-from ad       from address\n");
		BIO_printf(bio_err, "-subject s     subject\n");
		BIO_printf(bio_err, "-text          include or delete text MIME headers\n");
		BIO_printf(bio_err, "-CApath dir    trusted certificates directory\n");
		BIO_printf(bio_err, "-CAfile file   trusted certificates file\n");
		BIO_printf(bio_err, "-crl_check     check revocation status of signer's certificate using CRLs\n");
		BIO_printf(bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err, "-engine e      use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err, "-passin arg    input file pass phrase source\n");
		BIO_printf(bio_err, "cert.pem       recipient certificate(s) for encryption\n");
		goto end;
	}
#ifndef OPENSSL_NO_ENGINE
	e = setup_engine(bio_err, engine, 0);
#endif

	if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
		BIO_printf(bio_err, "Error getting password\n");
		goto end;
	}
	ret = 2;

	if (!(operation & SMIME_SIGNERS))
		flags &= ~PKCS7_DETACHED;

	if (operation & SMIME_OP) {
		if (outformat == FORMAT_ASN1)
			outmode = "wb";
	} else {
		if (flags & PKCS7_BINARY)
			outmode = "wb";
	}

	if (operation & SMIME_IP) {
		if (informat == FORMAT_ASN1)
			inmode = "rb";
	} else {
		if (flags & PKCS7_BINARY)
			inmode = "rb";
	}

	if (operation == SMIME_ENCRYPT) {
		if (!cipher) {
#ifndef OPENSSL_NO_RC2
			cipher = EVP_rc2_40_cbc();
#else
			BIO_printf(bio_err, "No cipher selected\n");
			goto end;
#endif
		}
		encerts = sk_X509_new_null();
		while (*args) {
			if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
			    NULL, e, "recipient certificate file"))) {
				goto end;
			}
			sk_X509_push(encerts, cert);
			cert = NULL;
			args++;
		}
	}
	if (certfile) {
		if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
			    e, "certificate file"))) {
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (recipfile && (operation == SMIME_DECRYPT)) {
		if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
			    e, "recipient certificate file"))) {
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (operation == SMIME_DECRYPT) {
		if (!keyfile)
			keyfile = recipfile;
	} else if (operation == SMIME_SIGN) {
		if (!keyfile)
			keyfile = signerfile;
	} else
		keyfile = NULL;

	if (keyfile) {
		key = load_key(bio_err, keyfile, keyform, 0, passin, e,
		    "signing key file");
		if (!key)
			goto end;
	}
	if (infile) {
		if (!(in = BIO_new_file(infile, inmode))) {
			BIO_printf(bio_err,
			    "Can't open input file %s\n", infile);
			goto end;
		}
	} else
		in = BIO_new_fp(stdin, BIO_NOCLOSE);

	if (operation & SMIME_IP) {
		if (informat == FORMAT_SMIME)
			p7 = SMIME_read_PKCS7(in, &indata);
		else if (informat == FORMAT_PEM)
			p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL);
		else if (informat == FORMAT_ASN1)
			p7 = d2i_PKCS7_bio(in, NULL);
		else {
			BIO_printf(bio_err, "Bad input format for PKCS#7 file\n");
			goto end;
		}

		if (!p7) {
			BIO_printf(bio_err, "Error reading S/MIME message\n");
			goto end;
		}
		if (contfile) {
			BIO_free(indata);
			if (!(indata = BIO_new_file(contfile, "rb"))) {
				BIO_printf(bio_err, "Can't read content file %s\n", contfile);
				goto end;
			}
		}
	}
	if (outfile) {
		if (!(out = BIO_new_file(outfile, outmode))) {
			BIO_printf(bio_err,
			    "Can't open output file %s\n", outfile);
			goto end;
		}
	} else {
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
	}

	if (operation == SMIME_VERIFY) {
		if (!(store = setup_verify(bio_err, CAfile, CApath)))
			goto end;
		X509_STORE_set_verify_cb(store, smime_cb);
		if (vpm)
			X509_STORE_set1_param(store, vpm);
	}
	ret = 3;

	if (operation == SMIME_ENCRYPT) {
		if (indef)
			flags |= PKCS7_STREAM;
		p7 = PKCS7_encrypt(encerts, in, cipher, flags);
	} else if (operation & SMIME_SIGNERS) {
		int i;
		/*
		 * If detached data content we only enable streaming if
		 * S/MIME output format.
		 */
		if (operation == SMIME_SIGN) {
			if (flags & PKCS7_DETACHED) {
				if (outformat == FORMAT_SMIME)
					flags |= PKCS7_STREAM;
			} else if (indef)
				flags |= PKCS7_STREAM;
			flags |= PKCS7_PARTIAL;
			p7 = PKCS7_sign(NULL, NULL, other, in, flags);
			if (!p7)
				goto end;
		} else
			flags |= PKCS7_REUSE_DIGEST;
		for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
			signerfile = sk_OPENSSL_STRING_value(sksigners, i);
			keyfile = sk_OPENSSL_STRING_value(skkeys, i);
			signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
			    e, "signer certificate");
			if (!signer)
				goto end;
			key = load_key(bio_err, keyfile, keyform, 0, passin, e,
			    "signing key file");
			if (!key)
				goto end;
			if (!PKCS7_sign_add_signer(p7, signer, key,
				sign_md, flags))
				goto end;
			X509_free(signer);
			signer = NULL;
			EVP_PKEY_free(key);
			key = NULL;
		}
		/* If not streaming or resigning finalize structure */
		if ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) {
			if (!PKCS7_final(p7, in, flags))
				goto end;
		}
	}
	if (!p7) {
		BIO_printf(bio_err, "Error creating PKCS#7 structure\n");
		goto end;
	}
	ret = 4;
	if (operation == SMIME_DECRYPT) {
		if (!PKCS7_decrypt(p7, key, recip, out, flags)) {
			BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n");
			goto end;
		}
	} else if (operation == SMIME_VERIFY) {
		STACK_OF(X509) * signers;
		if (PKCS7_verify(p7, other, store, indata, out, flags))
			BIO_printf(bio_err, "Verification successful\n");
		else {
			BIO_printf(bio_err, "Verification failure\n");
			goto end;
		}
		signers = PKCS7_get0_signers(p7, other, flags);
		if (!save_certs(signerfile, signers)) {
			BIO_printf(bio_err, "Error writing signers to %s\n",
			    signerfile);
			ret = 5;
			goto end;
		}
		sk_X509_free(signers);
	} else if (operation == SMIME_PK7OUT)
		PEM_write_bio_PKCS7(out, p7);
	else {
		if (to)
			BIO_printf(out, "To: %s\n", to);
		if (from)
			BIO_printf(out, "From: %s\n", from);
		if (subject)
			BIO_printf(out, "Subject: %s\n", subject);
		if (outformat == FORMAT_SMIME) {
			if (operation == SMIME_RESIGN)
				SMIME_write_PKCS7(out, p7, indata, flags);
			else
				SMIME_write_PKCS7(out, p7, in, flags);
		} else if (outformat == FORMAT_PEM)
			PEM_write_bio_PKCS7_stream(out, p7, in, flags);
		else if (outformat == FORMAT_ASN1)
			i2d_PKCS7_bio_stream(out, p7, in, flags);
		else {
			BIO_printf(bio_err, "Bad output format for PKCS#7 file\n");
			goto end;
		}
	}
	ret = 0;
end:
	if (ret)
		ERR_print_errors(bio_err);
	sk_X509_pop_free(encerts, X509_free);
	sk_X509_pop_free(other, X509_free);
	if (vpm)
		X509_VERIFY_PARAM_free(vpm);
	if (sksigners)
		sk_OPENSSL_STRING_free(sksigners);
	if (skkeys)
		sk_OPENSSL_STRING_free(skkeys);
	X509_STORE_free(store);
	X509_free(cert);
	X509_free(recip);
	X509_free(signer);
	EVP_PKEY_free(key);
	PKCS7_free(p7);
	BIO_free(in);
	BIO_free(indata);
	BIO_free_all(out);
	free(passin);

	return (ret);
}
コード例 #16
0
ファイル: verify.c プロジェクト: 2trill2spill/nextgen
int
verify_main(int argc, char **argv)
{
	int i, ret = 1, badarg = 0;
	char *CApath = NULL, *CAfile = NULL;
	char *untfile = NULL, *trustfile = NULL, *crlfile = NULL;
	STACK_OF(X509) * untrusted = NULL, *trusted = NULL;
	STACK_OF(X509_CRL) * crls = NULL;
	X509_STORE *cert_ctx = NULL;
	X509_LOOKUP *lookup = NULL;
	X509_VERIFY_PARAM *vpm = NULL;

	if (single_execution) {
		if (pledge("stdio rpath", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	cert_ctx = X509_STORE_new();
	if (cert_ctx == NULL)
		goto end;
	X509_STORE_set_verify_cb(cert_ctx, cb);

	argc--;
	argv++;
	for (;;) {
		if (argc >= 1) {
			if (strcmp(*argv, "-CApath") == 0) {
				if (argc-- < 1)
					goto end;
				CApath = *(++argv);
			} else if (strcmp(*argv, "-CAfile") == 0) {
				if (argc-- < 1)
					goto end;
				CAfile = *(++argv);
			} else if (args_verify(&argv, &argc, &badarg, bio_err,
			    &vpm)) {
				if (badarg)
					goto end;
				continue;
			} else if (strcmp(*argv, "-untrusted") == 0) {
				if (argc-- < 1)
					goto end;
				untfile = *(++argv);
			} else if (strcmp(*argv, "-trusted") == 0) {
				if (argc-- < 1)
					goto end;
				trustfile = *(++argv);
			} else if (strcmp(*argv, "-CRLfile") == 0) {
				if (argc-- < 1)
					goto end;
				crlfile = *(++argv);
			}
			else if (strcmp(*argv, "-help") == 0)
				goto end;
			else if (strcmp(*argv, "-verbose") == 0)
				v_verbose = 1;
			else if (argv[0][0] == '-')
				goto end;
			else
				break;
			argc--;
			argv++;
		} else
			break;
	}

	if (vpm)
		X509_STORE_set1_param(cert_ctx, vpm);

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file());
	if (lookup == NULL)
		abort();
	if (CAfile) {
		i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM);
		if (!i) {
			BIO_printf(bio_err, "Error loading file %s\n", CAfile);
			ERR_print_errors(bio_err);
			goto end;
		}
	} else
		X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);

	lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir());
	if (lookup == NULL)
		abort();
	if (CApath) {
		i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM);
		if (!i) {
			BIO_printf(bio_err, "Error loading directory %s\n", CApath);
			ERR_print_errors(bio_err);
			goto end;
		}
	} else
		X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);

	ERR_clear_error();

	if (untfile) {
		untrusted = load_certs(bio_err, untfile, FORMAT_PEM,
		    NULL, "untrusted certificates");
		if (!untrusted)
			goto end;
	}
	if (trustfile) {
		trusted = load_certs(bio_err, trustfile, FORMAT_PEM,
		    NULL, "trusted certificates");
		if (!trusted)
			goto end;
	}
	if (crlfile) {
		crls = load_crls(bio_err, crlfile, FORMAT_PEM,
		    NULL, "other CRLs");
		if (!crls)
			goto end;
	}
	ret = 0;
	if (argc < 1) {
		if (1 != check(cert_ctx, NULL, untrusted, trusted, crls))
			ret = -1;
	} else {
		for (i = 0; i < argc; i++)
			if (1 != check(cert_ctx, argv[i], untrusted, trusted,
			    crls))
				ret = -1;
	}

end:
	if (ret == 1) {
		BIO_printf(bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]");
		BIO_printf(bio_err, " [-attime timestamp]");
		BIO_printf(bio_err, " cert1 cert2 ...\n");

		BIO_printf(bio_err, "recognized usages:\n");
		for (i = 0; i < X509_PURPOSE_get_count(); i++) {
			X509_PURPOSE *ptmp;
			ptmp = X509_PURPOSE_get0(i);
			BIO_printf(bio_err, "\t%-10s\t%s\n",
			    X509_PURPOSE_get0_sname(ptmp),
			    X509_PURPOSE_get0_name(ptmp));
		}
	}
	if (vpm)
		X509_VERIFY_PARAM_free(vpm);
	if (cert_ctx != NULL)
		X509_STORE_free(cert_ctx);
	sk_X509_pop_free(untrusted, X509_free);
	sk_X509_pop_free(trusted, X509_free);
	sk_X509_CRL_pop_free(crls, X509_CRL_free);

	return (ret < 0 ? 2 : ret);
}
コード例 #17
0
int main(int argc, char** argv)
{
    int ret, devId;
    int encryptedSz, decryptedSz;
    word32 certSz, keySz;
    myCryptoDevCtx myCtx;

    byte cert[2048];
    byte key[2048];
    byte encrypted[2048];
    byte decrypted[2048];
    
#ifdef DEBUG_WOLFSSL
    wolfSSL_Debugging_ON();
#endif

    ret = wolfCrypt_Init();
    if (ret != 0) {
        printf("wolfCrypt initialization failed\n");
        return -1;
    }

    /* example data for callback */
    myCtx.exampleVar = 1;

    /* setting devId to something other than INVALID_DEVID, enables
       cryptodev callback to be used internally by wolfCrypt */
    devId = 1;
    ret = wc_CryptoDev_RegisterDevice(devId, myCryptoDevCb, &myCtx);
    if (ret != 0) {
        printf("Failed to register crypto dev device, ret = %d\n", ret);
        return -1;
    }

    certSz = sizeof(cert);
    keySz = sizeof(key);
    ret = load_certs(cert, &certSz, key, &keySz);
    if (ret != 0)
        return -1;

    /* no attributes */
    encryptedSz = signedData_sign_noattrs(cert, certSz, key, keySz,
                                          encrypted, sizeof(encrypted), devId);
    if (encryptedSz < 0)
        return -1;

    decryptedSz = signedData_verify(encrypted, encryptedSz,
                                    cert, certSz, key, keySz,
                                    decrypted, sizeof(decrypted), devId);
    if (decryptedSz < 0)
        return -1;

    /* default attributes + messageType attribute */
    encryptedSz = signedData_sign_attrs(cert, certSz, key, keySz,
                                        encrypted, sizeof(encrypted), devId);
    if (encryptedSz < 0)
        return -1;

    decryptedSz = signedData_verify(encrypted, encryptedSz,
                                    cert, certSz, key, keySz,
                                    decrypted, sizeof(decrypted), devId);
    if (decryptedSz < 0)
        return -1;

    (void)argc;
    (void)argv;

    return 0;
}
コード例 #18
0
ファイル: cms.c プロジェクト: davidlt/openssl-fedora
int MAIN(int argc, char **argv)
{
    ENGINE *e = NULL;
    int operation = 0;
    int ret = 0;
    char **args;
    const char *inmode = "r", *outmode = "w";
    char *infile = NULL, *outfile = NULL, *rctfile = NULL;
    char *signerfile = NULL, *recipfile = NULL;
    STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL;
    char *certfile = NULL, *keyfile = NULL, *contfile = NULL;
    char *certsoutfile = NULL;
    const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL;
    CMS_ContentInfo *cms = NULL, *rcms = NULL;
    X509_STORE *store = NULL;
    X509 *cert = NULL, *recip = NULL, *signer = NULL;
    EVP_PKEY *key = NULL;
    STACK_OF(X509) *encerts = NULL, *other = NULL;
    BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL;
    int badarg = 0;
    int flags = CMS_DETACHED, noout = 0, print = 0;
    int verify_retcode = 0;
    int rr_print = 0, rr_allorfirst = -1;
    STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL;
    CMS_ReceiptRequest *rr = NULL;
    char *to = NULL, *from = NULL, *subject = NULL;
    char *CAfile = NULL, *CApath = NULL;
    char *passargin = NULL, *passin = NULL;
    char *inrand = NULL;
    int need_rand = 0;
    const EVP_MD *sign_md = NULL;
    int informat = FORMAT_SMIME, outformat = FORMAT_SMIME;
    int rctformat = FORMAT_SMIME, keyform = FORMAT_PEM;
# ifndef OPENSSL_NO_ENGINE
    char *engine = NULL;
# endif
    unsigned char *secret_key = NULL, *secret_keyid = NULL;
    unsigned char *pwri_pass = NULL, *pwri_tmp = NULL;
    size_t secret_keylen = 0, secret_keyidlen = 0;

    cms_key_param *key_first = NULL, *key_param = NULL;

    ASN1_OBJECT *econtent_type = NULL;

    X509_VERIFY_PARAM *vpm = NULL;

    args = argv + 1;
    ret = 1;

    apps_startup();

    if (bio_err == NULL) {
        if ((bio_err = BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
    }

    if (!load_config(bio_err, NULL))
        goto end;

    while (!badarg && *args && *args[0] == '-') {
        if (!strcmp(*args, "-encrypt"))
            operation = SMIME_ENCRYPT;
        else if (!strcmp(*args, "-decrypt"))
            operation = SMIME_DECRYPT;
        else if (!strcmp(*args, "-sign"))
            operation = SMIME_SIGN;
        else if (!strcmp(*args, "-sign_receipt"))
            operation = SMIME_SIGN_RECEIPT;
        else if (!strcmp(*args, "-resign"))
            operation = SMIME_RESIGN;
        else if (!strcmp(*args, "-verify"))
            operation = SMIME_VERIFY;
        else if (!strcmp(*args, "-verify_retcode"))
            verify_retcode = 1;
        else if (!strcmp(*args, "-verify_receipt")) {
            operation = SMIME_VERIFY_RECEIPT;
            if (!args[1])
                goto argerr;
            args++;
            rctfile = *args;
        } else if (!strcmp(*args, "-cmsout"))
            operation = SMIME_CMSOUT;
        else if (!strcmp(*args, "-data_out"))
            operation = SMIME_DATAOUT;
        else if (!strcmp(*args, "-data_create"))
            operation = SMIME_DATA_CREATE;
        else if (!strcmp(*args, "-digest_verify"))
            operation = SMIME_DIGEST_VERIFY;
        else if (!strcmp(*args, "-digest_create"))
            operation = SMIME_DIGEST_CREATE;
        else if (!strcmp(*args, "-compress"))
            operation = SMIME_COMPRESS;
        else if (!strcmp(*args, "-uncompress"))
            operation = SMIME_UNCOMPRESS;
        else if (!strcmp(*args, "-EncryptedData_decrypt"))
            operation = SMIME_ENCRYPTED_DECRYPT;
        else if (!strcmp(*args, "-EncryptedData_encrypt"))
            operation = SMIME_ENCRYPTED_ENCRYPT;
# ifndef OPENSSL_NO_DES
        else if (!strcmp(*args, "-des3"))
            cipher = EVP_des_ede3_cbc();
        else if (!strcmp(*args, "-des"))
            cipher = EVP_des_cbc();
        else if (!strcmp(*args, "-des3-wrap"))
            wrap_cipher = EVP_des_ede3_wrap();
# endif
# ifndef OPENSSL_NO_SEED
        else if (!strcmp(*args, "-seed"))
            cipher = EVP_seed_cbc();
# endif
# ifndef OPENSSL_NO_RC2
        else if (!strcmp(*args, "-rc2-40"))
            cipher = EVP_rc2_40_cbc();
        else if (!strcmp(*args, "-rc2-128"))
            cipher = EVP_rc2_cbc();
        else if (!strcmp(*args, "-rc2-64"))
            cipher = EVP_rc2_64_cbc();
# endif
# ifndef OPENSSL_NO_AES
        else if (!strcmp(*args, "-aes128"))
            cipher = EVP_aes_128_cbc();
        else if (!strcmp(*args, "-aes192"))
            cipher = EVP_aes_192_cbc();
        else if (!strcmp(*args, "-aes256"))
            cipher = EVP_aes_256_cbc();
        else if (!strcmp(*args, "-aes128-wrap"))
            wrap_cipher = EVP_aes_128_wrap();
        else if (!strcmp(*args, "-aes192-wrap"))
            wrap_cipher = EVP_aes_192_wrap();
        else if (!strcmp(*args, "-aes256-wrap"))
            wrap_cipher = EVP_aes_256_wrap();
# endif
# ifndef OPENSSL_NO_CAMELLIA
        else if (!strcmp(*args, "-camellia128"))
            cipher = EVP_camellia_128_cbc();
        else if (!strcmp(*args, "-camellia192"))
            cipher = EVP_camellia_192_cbc();
        else if (!strcmp(*args, "-camellia256"))
            cipher = EVP_camellia_256_cbc();
# endif
        else if (!strcmp(*args, "-debug_decrypt"))
            flags |= CMS_DEBUG_DECRYPT;
        else if (!strcmp(*args, "-text"))
            flags |= CMS_TEXT;
        else if (!strcmp(*args, "-nointern"))
            flags |= CMS_NOINTERN;
        else if (!strcmp(*args, "-noverify")
                 || !strcmp(*args, "-no_signer_cert_verify"))
            flags |= CMS_NO_SIGNER_CERT_VERIFY;
        else if (!strcmp(*args, "-nocerts"))
            flags |= CMS_NOCERTS;
        else if (!strcmp(*args, "-noattr"))
            flags |= CMS_NOATTR;
        else if (!strcmp(*args, "-nodetach"))
            flags &= ~CMS_DETACHED;
        else if (!strcmp(*args, "-nosmimecap"))
            flags |= CMS_NOSMIMECAP;
        else if (!strcmp(*args, "-binary"))
            flags |= CMS_BINARY;
        else if (!strcmp(*args, "-keyid"))
            flags |= CMS_USE_KEYID;
        else if (!strcmp(*args, "-nosigs"))
            flags |= CMS_NOSIGS;
        else if (!strcmp(*args, "-no_content_verify"))
            flags |= CMS_NO_CONTENT_VERIFY;
        else if (!strcmp(*args, "-no_attr_verify"))
            flags |= CMS_NO_ATTR_VERIFY;
        else if (!strcmp(*args, "-stream"))
            flags |= CMS_STREAM;
        else if (!strcmp(*args, "-indef"))
            flags |= CMS_STREAM;
        else if (!strcmp(*args, "-noindef"))
            flags &= ~CMS_STREAM;
        else if (!strcmp(*args, "-nooldmime"))
            flags |= CMS_NOOLDMIMETYPE;
        else if (!strcmp(*args, "-crlfeol"))
            flags |= CMS_CRLFEOL;
        else if (!strcmp(*args, "-noout"))
            noout = 1;
        else if (!strcmp(*args, "-receipt_request_print"))
            rr_print = 1;
        else if (!strcmp(*args, "-receipt_request_all"))
            rr_allorfirst = 0;
        else if (!strcmp(*args, "-receipt_request_first"))
            rr_allorfirst = 1;
        else if (!strcmp(*args, "-receipt_request_from")) {
            if (!args[1])
                goto argerr;
            args++;
            if (!rr_from)
                rr_from = sk_OPENSSL_STRING_new_null();
            sk_OPENSSL_STRING_push(rr_from, *args);
        } else if (!strcmp(*args, "-receipt_request_to")) {
            if (!args[1])
                goto argerr;
            args++;
            if (!rr_to)
                rr_to = sk_OPENSSL_STRING_new_null();
            sk_OPENSSL_STRING_push(rr_to, *args);
        } else if (!strcmp(*args, "-print")) {
            noout = 1;
            print = 1;
        } else if (!strcmp(*args, "-secretkey")) {
            long ltmp;
            if (!args[1])
                goto argerr;
            args++;
            secret_key = string_to_hex(*args, &ltmp);
            if (!secret_key) {
                BIO_printf(bio_err, "Invalid key %s\n", *args);
                goto argerr;
            }
            secret_keylen = (size_t)ltmp;
        } else if (!strcmp(*args, "-secretkeyid")) {
            long ltmp;
            if (!args[1])
                goto argerr;
            args++;
            secret_keyid = string_to_hex(*args, &ltmp);
            if (!secret_keyid) {
                BIO_printf(bio_err, "Invalid id %s\n", *args);
                goto argerr;
            }
            secret_keyidlen = (size_t)ltmp;
        } else if (!strcmp(*args, "-pwri_password")) {
            if (!args[1])
                goto argerr;
            args++;
            pwri_pass = (unsigned char *)*args;
        } else if (!strcmp(*args, "-econtent_type")) {
            if (!args[1])
                goto argerr;
            args++;
            econtent_type = OBJ_txt2obj(*args, 0);
            if (!econtent_type) {
                BIO_printf(bio_err, "Invalid OID %s\n", *args);
                goto argerr;
            }
        } else if (!strcmp(*args, "-rand")) {
            if (!args[1])
                goto argerr;
            args++;
            inrand = *args;
            need_rand = 1;
        }
# ifndef OPENSSL_NO_ENGINE
        else if (!strcmp(*args, "-engine")) {
            if (!args[1])
                goto argerr;
            engine = *++args;
        }
# endif
        else if (!strcmp(*args, "-passin")) {
            if (!args[1])
                goto argerr;
            passargin = *++args;
        } else if (!strcmp(*args, "-to")) {
            if (!args[1])
                goto argerr;
            to = *++args;
        } else if (!strcmp(*args, "-from")) {
            if (!args[1])
                goto argerr;
            from = *++args;
        } else if (!strcmp(*args, "-subject")) {
            if (!args[1])
                goto argerr;
            subject = *++args;
        } else if (!strcmp(*args, "-signer")) {
            if (!args[1])
                goto argerr;
            /* If previous -signer argument add signer to list */

            if (signerfile) {
                if (!sksigners)
                    sksigners = sk_OPENSSL_STRING_new_null();
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                if (!keyfile)
                    keyfile = signerfile;
                if (!skkeys)
                    skkeys = sk_OPENSSL_STRING_new_null();
                sk_OPENSSL_STRING_push(skkeys, keyfile);
                keyfile = NULL;
            }
            signerfile = *++args;
        } else if (!strcmp(*args, "-recip")) {
            if (!args[1])
                goto argerr;
            if (operation == SMIME_ENCRYPT) {
                if (!encerts)
                    encerts = sk_X509_new_null();
                cert = load_cert(bio_err, *++args, FORMAT_PEM,
                                 NULL, e, "recipient certificate file");
                if (!cert)
                    goto end;
                sk_X509_push(encerts, cert);
                cert = NULL;
            } else
                recipfile = *++args;
        } else if (!strcmp(*args, "-certsout")) {
            if (!args[1])
                goto argerr;
            certsoutfile = *++args;
        } else if (!strcmp(*args, "-md")) {
            if (!args[1])
                goto argerr;
            sign_md = EVP_get_digestbyname(*++args);
            if (sign_md == NULL) {
                BIO_printf(bio_err, "Unknown digest %s\n", *args);
                goto argerr;
            }
        } else if (!strcmp(*args, "-inkey")) {
            if (!args[1])
                goto argerr;
            /* If previous -inkey arument add signer to list */
            if (keyfile) {
                if (!signerfile) {
                    BIO_puts(bio_err, "Illegal -inkey without -signer\n");
                    goto argerr;
                }
                if (!sksigners)
                    sksigners = sk_OPENSSL_STRING_new_null();
                sk_OPENSSL_STRING_push(sksigners, signerfile);
                signerfile = NULL;
                if (!skkeys)
                    skkeys = sk_OPENSSL_STRING_new_null();
                sk_OPENSSL_STRING_push(skkeys, keyfile);
            }
            keyfile = *++args;
        } else if (!strcmp(*args, "-keyform")) {
            if (!args[1])
                goto argerr;
            keyform = str2fmt(*++args);
        } else if (!strcmp(*args, "-keyopt")) {
            int keyidx = -1;
            if (!args[1])
                goto argerr;
            if (operation == SMIME_ENCRYPT) {
                if (encerts)
                    keyidx += sk_X509_num(encerts);
            } else {
                if (keyfile || signerfile)
                    keyidx++;
                if (skkeys)
                    keyidx += sk_OPENSSL_STRING_num(skkeys);
            }
            if (keyidx < 0) {
                BIO_printf(bio_err, "No key specified\n");
                goto argerr;
            }
            if (key_param == NULL || key_param->idx != keyidx) {
                cms_key_param *nparam;
                nparam = OPENSSL_malloc(sizeof(cms_key_param));
                if (!nparam) {
                    BIO_printf(bio_err, "Out of memory\n");
                    goto argerr;
                }
                nparam->idx = keyidx;
                nparam->param = sk_OPENSSL_STRING_new_null();
                nparam->next = NULL;
                if (key_first == NULL)
                    key_first = nparam;
                else
                    key_param->next = nparam;
                key_param = nparam;
            }
            sk_OPENSSL_STRING_push(key_param->param, *++args);
        } else if (!strcmp(*args, "-rctform")) {
            if (!args[1])
                goto argerr;
            rctformat = str2fmt(*++args);
        } else if (!strcmp(*args, "-certfile")) {
            if (!args[1])
                goto argerr;
            certfile = *++args;
        } else if (!strcmp(*args, "-CAfile")) {
            if (!args[1])
                goto argerr;
            CAfile = *++args;
        } else if (!strcmp(*args, "-CApath")) {
            if (!args[1])
                goto argerr;
            CApath = *++args;
        } else if (!strcmp(*args, "-in")) {
            if (!args[1])
                goto argerr;
            infile = *++args;
        } else if (!strcmp(*args, "-inform")) {
            if (!args[1])
                goto argerr;
            informat = str2fmt(*++args);
        } else if (!strcmp(*args, "-outform")) {
            if (!args[1])
                goto argerr;
            outformat = str2fmt(*++args);
        } else if (!strcmp(*args, "-out")) {
            if (!args[1])
                goto argerr;
            outfile = *++args;
        } else if (!strcmp(*args, "-content")) {
            if (!args[1])
                goto argerr;
            contfile = *++args;
        } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm))
            continue;
        else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL)
            badarg = 1;
        args++;
    }

    if (((rr_allorfirst != -1) || rr_from) && !rr_to) {
        BIO_puts(bio_err, "No Signed Receipts Recipients\n");
        goto argerr;
    }

    if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) {
        BIO_puts(bio_err, "Signed receipts only allowed with -sign\n");
        goto argerr;
    }
    if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) {
        BIO_puts(bio_err, "Multiple signers or keys not allowed\n");
        goto argerr;
    }

    if (operation & SMIME_SIGNERS) {
        if (keyfile && !signerfile) {
            BIO_puts(bio_err, "Illegal -inkey without -signer\n");
            goto argerr;
        }
        /* Check to see if any final signer needs to be appended */
        if (signerfile) {
            if (!sksigners)
                sksigners = sk_OPENSSL_STRING_new_null();
            sk_OPENSSL_STRING_push(sksigners, signerfile);
            if (!skkeys)
                skkeys = sk_OPENSSL_STRING_new_null();
            if (!keyfile)
                keyfile = signerfile;
            sk_OPENSSL_STRING_push(skkeys, keyfile);
        }
        if (!sksigners) {
            BIO_printf(bio_err, "No signer certificate specified\n");
            badarg = 1;
        }
        signerfile = NULL;
        keyfile = NULL;
        need_rand = 1;
    }

    else if (operation == SMIME_DECRYPT) {
        if (!recipfile && !keyfile && !secret_key && !pwri_pass) {
            BIO_printf(bio_err,
                       "No recipient certificate or key specified\n");
            badarg = 1;
        }
    } else if (operation == SMIME_ENCRYPT) {
        if (!*args && !secret_key && !pwri_pass && !encerts) {
            BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n");
            badarg = 1;
        }
        need_rand = 1;
    } else if (!operation)
        badarg = 1;

    if (badarg) {
 argerr:
        BIO_printf(bio_err, "Usage cms [options] cert.pem ...\n");
        BIO_printf(bio_err, "where options are\n");
        BIO_printf(bio_err, "-encrypt       encrypt message\n");
        BIO_printf(bio_err, "-decrypt       decrypt encrypted message\n");
        BIO_printf(bio_err, "-sign          sign message\n");
        BIO_printf(bio_err, "-verify        verify signed message\n");
        BIO_printf(bio_err, "-cmsout        output CMS structure\n");
# ifndef OPENSSL_NO_DES
        BIO_printf(bio_err, "-des3          encrypt with triple DES\n");
        BIO_printf(bio_err, "-des           encrypt with DES\n");
# endif
# ifndef OPENSSL_NO_SEED
        BIO_printf(bio_err, "-seed          encrypt with SEED\n");
# endif
# ifndef OPENSSL_NO_RC2
        BIO_printf(bio_err, "-rc2-40        encrypt with RC2-40 (default)\n");
        BIO_printf(bio_err, "-rc2-64        encrypt with RC2-64\n");
        BIO_printf(bio_err, "-rc2-128       encrypt with RC2-128\n");
# endif
# ifndef OPENSSL_NO_AES
        BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
        BIO_printf(bio_err,
                   "               encrypt PEM output with cbc aes\n");
# endif
# ifndef OPENSSL_NO_CAMELLIA
        BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
        BIO_printf(bio_err,
                   "               encrypt PEM output with cbc camellia\n");
# endif
        BIO_printf(bio_err,
                   "-nointern      don't search certificates in message for signer\n");
        BIO_printf(bio_err,
                   "-nosigs        don't verify message signature\n");
        BIO_printf(bio_err,
                   "-noverify      don't verify signers certificate\n");
        BIO_printf(bio_err,
                   "-nocerts       don't include signers certificate when signing\n");
        BIO_printf(bio_err, "-nodetach      use opaque signing\n");
        BIO_printf(bio_err,
                   "-noattr        don't include any signed attributes\n");
        BIO_printf(bio_err,
                   "-binary        don't translate message to text\n");
        BIO_printf(bio_err, "-certfile file other certificates file\n");
        BIO_printf(bio_err, "-certsout file certificate output file\n");
        BIO_printf(bio_err, "-signer file   signer certificate file\n");
        BIO_printf(bio_err,
                   "-recip  file   recipient certificate file for decryption\n");
        BIO_printf(bio_err, "-keyid         use subject key identifier\n");
        BIO_printf(bio_err, "-in file       input file\n");
        BIO_printf(bio_err,
                   "-inform arg    input format SMIME (default), PEM or DER\n");
        BIO_printf(bio_err,
                   "-inkey file    input private key (if not signer or recipient)\n");
        BIO_printf(bio_err,
                   "-keyform arg   input private key format (PEM or ENGINE)\n");
        BIO_printf(bio_err, "-keyopt nm:v   set public key parameters\n");
        BIO_printf(bio_err, "-out file      output file\n");
        BIO_printf(bio_err,
                   "-outform arg   output format SMIME (default), PEM or DER\n");
        BIO_printf(bio_err,
                   "-content file  supply or override content for detached signature\n");
        BIO_printf(bio_err, "-to addr       to address\n");
        BIO_printf(bio_err, "-from ad       from address\n");
        BIO_printf(bio_err, "-subject s     subject\n");
        BIO_printf(bio_err,
                   "-text          include or delete text MIME headers\n");
        BIO_printf(bio_err,
                   "-CApath dir    trusted certificates directory\n");
        BIO_printf(bio_err, "-CAfile file   trusted certificates file\n");
        BIO_printf(bio_err,
                   "-trusted_first use trusted certificates first when building the trust chain\n");
        BIO_printf(bio_err,
                   "-no_alt_chains only ever use the first certificate chain found\n");
        BIO_printf(bio_err,
                   "-crl_check     check revocation status of signer's certificate using CRLs\n");
        BIO_printf(bio_err,
                   "-crl_check_all check revocation status of signer's certificate chain using CRLs\n");
# ifndef OPENSSL_NO_ENGINE
        BIO_printf(bio_err,
                   "-engine e      use engine e, possibly a hardware device.\n");
# endif
        BIO_printf(bio_err, "-passin arg    input file pass phrase source\n");
        BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR,
                   LIST_SEPARATOR_CHAR);
        BIO_printf(bio_err,
                   "               load the file (or the files in the directory) into\n");
        BIO_printf(bio_err, "               the random number generator\n");
        BIO_printf(bio_err,
                   "cert.pem       recipient certificate(s) for encryption\n");
        goto end;
    }
# ifndef OPENSSL_NO_ENGINE
    e = setup_engine(bio_err, engine, 0);
# endif

    if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
        BIO_printf(bio_err, "Error getting password\n");
        goto end;
    }

    if (need_rand) {
        app_RAND_load_file(NULL, bio_err, (inrand != NULL));
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));
    }

    ret = 2;

    if (!(operation & SMIME_SIGNERS))
        flags &= ~CMS_DETACHED;

    if (operation & SMIME_OP) {
        if (outformat == FORMAT_ASN1)
            outmode = "wb";
    } else {
        if (flags & CMS_BINARY)
            outmode = "wb";
    }

    if (operation & SMIME_IP) {
        if (informat == FORMAT_ASN1)
            inmode = "rb";
    } else {
        if (flags & CMS_BINARY)
            inmode = "rb";
    }

    if (operation == SMIME_ENCRYPT) {
        if (!cipher) {
# ifndef OPENSSL_NO_DES
            cipher = EVP_des_ede3_cbc();
# else
            BIO_printf(bio_err, "No cipher selected\n");
            goto end;
# endif
        }

        if (secret_key && !secret_keyid) {
            BIO_printf(bio_err, "No secret key id\n");
            goto end;
        }

        if (*args && !encerts)
            encerts = sk_X509_new_null();
        while (*args) {
            if (!(cert = load_cert(bio_err, *args, FORMAT_PEM,
                                   NULL, e, "recipient certificate file")))
                goto end;
            sk_X509_push(encerts, cert);
            cert = NULL;
            args++;
        }
    }

    if (certfile) {
        if (!(other = load_certs(bio_err, certfile, FORMAT_PEM, NULL,
                                 e, "certificate file"))) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (recipfile && (operation == SMIME_DECRYPT)) {
        if (!(recip = load_cert(bio_err, recipfile, FORMAT_PEM, NULL,
                                e, "recipient certificate file"))) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (operation == SMIME_SIGN_RECEIPT) {
        if (!(signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
                                 e, "receipt signer certificate file"))) {
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (operation == SMIME_DECRYPT) {
        if (!keyfile)
            keyfile = recipfile;
    } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) {
        if (!keyfile)
            keyfile = signerfile;
    } else
        keyfile = NULL;

    if (keyfile) {
        key = load_key(bio_err, keyfile, keyform, 0, passin, e,
                       "signing key file");
        if (!key)
            goto end;
    }

    if (infile) {
        if (!(in = BIO_new_file(infile, inmode))) {
            BIO_printf(bio_err, "Can't open input file %s\n", infile);
            goto end;
        }
    } else
        in = BIO_new_fp(stdin, BIO_NOCLOSE);

    if (operation & SMIME_IP) {
        if (informat == FORMAT_SMIME)
            cms = SMIME_read_CMS(in, &indata);
        else if (informat == FORMAT_PEM)
            cms = PEM_read_bio_CMS(in, NULL, NULL, NULL);
        else if (informat == FORMAT_ASN1)
            cms = d2i_CMS_bio(in, NULL);
        else {
            BIO_printf(bio_err, "Bad input format for CMS file\n");
            goto end;
        }

        if (!cms) {
            BIO_printf(bio_err, "Error reading S/MIME message\n");
            goto end;
        }
        if (contfile) {
            BIO_free(indata);
            if (!(indata = BIO_new_file(contfile, "rb"))) {
                BIO_printf(bio_err, "Can't read content file %s\n", contfile);
                goto end;
            }
        }
        if (certsoutfile) {
            STACK_OF(X509) *allcerts;
            allcerts = CMS_get1_certs(cms);
            if (!save_certs(certsoutfile, allcerts)) {
                BIO_printf(bio_err,
                           "Error writing certs to %s\n", certsoutfile);
                ret = 5;
                goto end;
            }
            sk_X509_pop_free(allcerts, X509_free);
        }
    }

    if (rctfile) {
        char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r";
        if (!(rctin = BIO_new_file(rctfile, rctmode))) {
            BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile);
            goto end;
        }

        if (rctformat == FORMAT_SMIME)
            rcms = SMIME_read_CMS(rctin, NULL);
        else if (rctformat == FORMAT_PEM)
            rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL);
        else if (rctformat == FORMAT_ASN1)
            rcms = d2i_CMS_bio(rctin, NULL);
        else {
            BIO_printf(bio_err, "Bad input format for receipt\n");
            goto end;
        }

        if (!rcms) {
            BIO_printf(bio_err, "Error reading receipt\n");
            goto end;
        }
    }

    if (outfile) {
        if (!(out = BIO_new_file(outfile, outmode))) {
            BIO_printf(bio_err, "Can't open output file %s\n", outfile);
            goto end;
        }
    } else {
        out = BIO_new_fp(stdout, BIO_NOCLOSE);
# ifdef OPENSSL_SYS_VMS
        {
            BIO *tmpbio = BIO_new(BIO_f_linebuffer());
            out = BIO_push(tmpbio, out);
        }
# endif
    }

    if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) {
        if (!(store = setup_verify(bio_err, CAfile, CApath)))
            goto end;
        X509_STORE_set_verify_cb(store, cms_cb);
        if (vpm)
            X509_STORE_set1_param(store, vpm);
    }

    ret = 3;

    if (operation == SMIME_DATA_CREATE) {
        cms = CMS_data_create(in, flags);
    } else if (operation == SMIME_DIGEST_CREATE) {
        cms = CMS_digest_create(in, sign_md, flags);
    } else if (operation == SMIME_COMPRESS) {
        cms = CMS_compress(in, -1, flags);
    } else if (operation == SMIME_ENCRYPT) {
        int i;
        flags |= CMS_PARTIAL;
        cms = CMS_encrypt(NULL, in, cipher, flags);
        if (!cms)
            goto end;
        for (i = 0; i < sk_X509_num(encerts); i++) {
            CMS_RecipientInfo *ri;
            cms_key_param *kparam;
            int tflags = flags;
            X509 *x = sk_X509_value(encerts, i);
            for (kparam = key_first; kparam; kparam = kparam->next) {
                if (kparam->idx == i) {
                    tflags |= CMS_KEY_PARAM;
                    break;
                }
            }
            ri = CMS_add1_recipient_cert(cms, x, tflags);
            if (!ri)
                goto end;
            if (kparam) {
                EVP_PKEY_CTX *pctx;
                pctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
                if (!cms_set_pkey_param(pctx, kparam->param))
                    goto end;
            }
            if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE
                && wrap_cipher) {
                EVP_CIPHER_CTX *wctx;
                wctx = CMS_RecipientInfo_kari_get0_ctx(ri);
                EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL);
            }
        }

        if (secret_key) {
            if (!CMS_add0_recipient_key(cms, NID_undef,
                                        secret_key, secret_keylen,
                                        secret_keyid, secret_keyidlen,
                                        NULL, NULL, NULL))
                goto end;
            /* NULL these because call absorbs them */
            secret_key = NULL;
            secret_keyid = NULL;
        }
        if (pwri_pass) {
            pwri_tmp = (unsigned char *)BUF_strdup((char *)pwri_pass);
            if (!pwri_tmp)
                goto end;
            if (!CMS_add0_recipient_password(cms,
                                             -1, NID_undef, NID_undef,
                                             pwri_tmp, -1, NULL))
                goto end;
            pwri_tmp = NULL;
        }
        if (!(flags & CMS_STREAM)) {
            if (!CMS_final(cms, in, NULL, flags))
                goto end;
        }
    } else if (operation == SMIME_ENCRYPTED_ENCRYPT) {
        cms = CMS_EncryptedData_encrypt(in, cipher,
                                        secret_key, secret_keylen, flags);

    } else if (operation == SMIME_SIGN_RECEIPT) {
        CMS_ContentInfo *srcms = NULL;
        STACK_OF(CMS_SignerInfo) *sis;
        CMS_SignerInfo *si;
        sis = CMS_get0_SignerInfos(cms);
        if (!sis)
            goto end;
        si = sk_CMS_SignerInfo_value(sis, 0);
        srcms = CMS_sign_receipt(si, signer, key, other, flags);
        if (!srcms)
            goto end;
        CMS_ContentInfo_free(cms);
        cms = srcms;
    } else if (operation & SMIME_SIGNERS) {
        int i;
        /*
         * If detached data content we enable streaming if S/MIME output
         * format.
         */
        if (operation == SMIME_SIGN) {

            if (flags & CMS_DETACHED) {
                if (outformat == FORMAT_SMIME)
                    flags |= CMS_STREAM;
            }
            flags |= CMS_PARTIAL;
            cms = CMS_sign(NULL, NULL, other, in, flags);
            if (!cms)
                goto end;
            if (econtent_type)
                CMS_set1_eContentType(cms, econtent_type);

            if (rr_to) {
                rr = make_receipt_request(rr_to, rr_allorfirst, rr_from);
                if (!rr) {
                    BIO_puts(bio_err,
                             "Signed Receipt Request Creation Error\n");
                    goto end;
                }
            }
        } else
            flags |= CMS_REUSE_DIGEST;
        for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) {
            CMS_SignerInfo *si;
            cms_key_param *kparam;
            int tflags = flags;
            signerfile = sk_OPENSSL_STRING_value(sksigners, i);
            keyfile = sk_OPENSSL_STRING_value(skkeys, i);

            signer = load_cert(bio_err, signerfile, FORMAT_PEM, NULL,
                               e, "signer certificate");
            if (!signer)
                goto end;
            key = load_key(bio_err, keyfile, keyform, 0, passin, e,
                           "signing key file");
            if (!key)
                goto end;
            for (kparam = key_first; kparam; kparam = kparam->next) {
                if (kparam->idx == i) {
                    tflags |= CMS_KEY_PARAM;
                    break;
                }
            }
            si = CMS_add1_signer(cms, signer, key, sign_md, tflags);
            if (!si)
                goto end;
            if (kparam) {
                EVP_PKEY_CTX *pctx;
                pctx = CMS_SignerInfo_get0_pkey_ctx(si);
                if (!cms_set_pkey_param(pctx, kparam->param))
                    goto end;
            }
            if (rr && !CMS_add1_ReceiptRequest(si, rr))
                goto end;
            X509_free(signer);
            signer = NULL;
            EVP_PKEY_free(key);
            key = NULL;
        }
        /* If not streaming or resigning finalize structure */
        if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) {
            if (!CMS_final(cms, in, NULL, flags))
                goto end;
        }
    }

    if (!cms) {
        BIO_printf(bio_err, "Error creating CMS structure\n");
        goto end;
    }

    ret = 4;
    if (operation == SMIME_DECRYPT) {
        if (flags & CMS_DEBUG_DECRYPT)
            CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags);

        if (secret_key) {
            if (!CMS_decrypt_set1_key(cms,
                                      secret_key, secret_keylen,
                                      secret_keyid, secret_keyidlen)) {
                BIO_puts(bio_err, "Error decrypting CMS using secret key\n");
                goto end;
            }
        }

        if (key) {
            if (!CMS_decrypt_set1_pkey(cms, key, recip)) {
                BIO_puts(bio_err, "Error decrypting CMS using private key\n");
                goto end;
            }
        }

        if (pwri_pass) {
            if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) {
                BIO_puts(bio_err, "Error decrypting CMS using password\n");
                goto end;
            }
        }

        if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) {
            BIO_printf(bio_err, "Error decrypting CMS structure\n");
            goto end;
        }
    } else if (operation == SMIME_DATAOUT) {
        if (!CMS_data(cms, out, flags))
            goto end;
    } else if (operation == SMIME_UNCOMPRESS) {
        if (!CMS_uncompress(cms, indata, out, flags))
            goto end;
    } else if (operation == SMIME_DIGEST_VERIFY) {
        if (CMS_digest_verify(cms, indata, out, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            goto end;
        }
    } else if (operation == SMIME_ENCRYPTED_DECRYPT) {
        if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen,
                                       indata, out, flags))
            goto end;
    } else if (operation == SMIME_VERIFY) {
        if (CMS_verify(cms, other, store, indata, out, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            if (verify_retcode)
                ret = verify_err + 32;
            goto end;
        }
        if (signerfile) {
            STACK_OF(X509) *signers;
            signers = CMS_get0_signers(cms);
            if (!save_certs(signerfile, signers)) {
                BIO_printf(bio_err,
                           "Error writing signers to %s\n", signerfile);
                ret = 5;
                goto end;
            }
            sk_X509_free(signers);
        }
        if (rr_print)
            receipt_request_print(bio_err, cms);

    } else if (operation == SMIME_VERIFY_RECEIPT) {
        if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0)
            BIO_printf(bio_err, "Verification successful\n");
        else {
            BIO_printf(bio_err, "Verification failure\n");
            goto end;
        }
    } else {
        if (noout) {
            if (print)
                CMS_ContentInfo_print_ctx(out, cms, 0, NULL);
        } else if (outformat == FORMAT_SMIME) {
            if (to)
                BIO_printf(out, "To: %s\n", to);
            if (from)
                BIO_printf(out, "From: %s\n", from);
            if (subject)
                BIO_printf(out, "Subject: %s\n", subject);
            if (operation == SMIME_RESIGN)
                ret = SMIME_write_CMS(out, cms, indata, flags);
            else
                ret = SMIME_write_CMS(out, cms, in, flags);
        } else if (outformat == FORMAT_PEM)
            ret = PEM_write_bio_CMS_stream(out, cms, in, flags);
        else if (outformat == FORMAT_ASN1)
            ret = i2d_CMS_bio_stream(out, cms, in, flags);
        else {
            BIO_printf(bio_err, "Bad output format for CMS file\n");
            goto end;
        }
        if (ret <= 0) {
            ret = 6;
            goto end;
        }
    }
    ret = 0;
 end:
    if (ret)
        ERR_print_errors(bio_err);
    if (need_rand)
        app_RAND_write_file(NULL, bio_err);
    sk_X509_pop_free(encerts, X509_free);
    sk_X509_pop_free(other, X509_free);
    if (vpm)
        X509_VERIFY_PARAM_free(vpm);
    if (sksigners)
        sk_OPENSSL_STRING_free(sksigners);
    if (skkeys)
        sk_OPENSSL_STRING_free(skkeys);
    if (secret_key)
        OPENSSL_free(secret_key);
    if (secret_keyid)
        OPENSSL_free(secret_keyid);
    if (pwri_tmp)
        OPENSSL_free(pwri_tmp);
    if (econtent_type)
        ASN1_OBJECT_free(econtent_type);
    if (rr)
        CMS_ReceiptRequest_free(rr);
    if (rr_to)
        sk_OPENSSL_STRING_free(rr_to);
    if (rr_from)
        sk_OPENSSL_STRING_free(rr_from);
    for (key_param = key_first; key_param;) {
        cms_key_param *tparam;
        sk_OPENSSL_STRING_free(key_param->param);
        tparam = key_param->next;
        OPENSSL_free(key_param);
        key_param = tparam;
    }
    X509_STORE_free(store);
    X509_free(cert);
    X509_free(recip);
    X509_free(signer);
    EVP_PKEY_free(key);
    CMS_ContentInfo_free(cms);
    CMS_ContentInfo_free(rcms);
    BIO_free(rctin);
    BIO_free(in);
    BIO_free(indata);
    BIO_free_all(out);
    if (passin)
        OPENSSL_free(passin);
    return (ret);
}
コード例 #19
0
ファイル: pkcs12.c プロジェクト: awakecoding/libressl
int
pkcs12_main(int argc, char **argv)
{
	ENGINE *e = NULL;
	char *infile = NULL, *outfile = NULL, *keyname = NULL;
	char *certfile = NULL;
	BIO *in = NULL, *out = NULL;
	char **args;
	char *name = NULL;
	char *csp_name = NULL;
	int add_lmk = 0;
	PKCS12 *p12 = NULL;
	char pass[50], macpass[50];
	int export_cert = 0;
	int options = 0;
	int chain = 0;
	int badarg = 0;
	int iter = PKCS12_DEFAULT_ITER;
	int maciter = PKCS12_DEFAULT_ITER;
	int twopass = 0;
	int keytype = 0;
	int cert_pbe;
	int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
	int ret = 1;
	int macver = 1;
	int noprompt = 0;
	STACK_OF(OPENSSL_STRING) * canames = NULL;
	char *cpass = NULL, *mpass = NULL;
	char *passargin = NULL, *passargout = NULL, *passarg = NULL;
	char *passin = NULL, *passout = NULL;
	char *inrand = NULL;
	char *macalg = NULL;
	char *CApath = NULL, *CAfile = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif

	signal(SIGPIPE, SIG_IGN);

	cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;

	enc = EVP_des_ede3_cbc();
	if (bio_err == NULL)
		bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;

	args = argv + 1;


	while (*args) {
		if (*args[0] == '-') {
			if (!strcmp(*args, "-nokeys"))
				options |= NOKEYS;
			else if (!strcmp(*args, "-keyex"))
				keytype = KEY_EX;
			else if (!strcmp(*args, "-keysig"))
				keytype = KEY_SIG;
			else if (!strcmp(*args, "-nocerts"))
				options |= NOCERTS;
			else if (!strcmp(*args, "-clcerts"))
				options |= CLCERTS;
			else if (!strcmp(*args, "-cacerts"))
				options |= CACERTS;
			else if (!strcmp(*args, "-noout"))
				options |= (NOKEYS | NOCERTS);
			else if (!strcmp(*args, "-info"))
				options |= INFO;
			else if (!strcmp(*args, "-chain"))
				chain = 1;
			else if (!strcmp(*args, "-twopass"))
				twopass = 1;
			else if (!strcmp(*args, "-nomacver"))
				macver = 0;
			else if (!strcmp(*args, "-descert"))
				cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
			else if (!strcmp(*args, "-export"))
				export_cert = 1;
			else if (!strcmp(*args, "-des"))
				enc = EVP_des_cbc();
			else if (!strcmp(*args, "-des3"))
				enc = EVP_des_ede3_cbc();
#ifndef OPENSSL_NO_IDEA
			else if (!strcmp(*args, "-idea"))
				enc = EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
			else if (!strcmp(*args, "-seed"))
				enc = EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
			else if (!strcmp(*args, "-aes128"))
				enc = EVP_aes_128_cbc();
			else if (!strcmp(*args, "-aes192"))
				enc = EVP_aes_192_cbc();
			else if (!strcmp(*args, "-aes256"))
				enc = EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
			else if (!strcmp(*args, "-camellia128"))
				enc = EVP_camellia_128_cbc();
			else if (!strcmp(*args, "-camellia192"))
				enc = EVP_camellia_192_cbc();
			else if (!strcmp(*args, "-camellia256"))
				enc = EVP_camellia_256_cbc();
#endif
			else if (!strcmp(*args, "-noiter"))
				iter = 1;
			else if (!strcmp(*args, "-maciter"))
				maciter = PKCS12_DEFAULT_ITER;
			else if (!strcmp(*args, "-nomaciter"))
				maciter = 1;
			else if (!strcmp(*args, "-nomac"))
				maciter = -1;
			else if (!strcmp(*args, "-macalg"))
				if (args[1]) {
					args++;
					macalg = *args;
				} else
					badarg = 1;
			else if (!strcmp(*args, "-nodes"))
				enc = NULL;
			else if (!strcmp(*args, "-certpbe")) {
				if (!set_pbe(bio_err, &cert_pbe, *++args))
					badarg = 1;
			} else if (!strcmp(*args, "-keypbe")) {
				if (!set_pbe(bio_err, &key_pbe, *++args))
					badarg = 1;
			} else if (!strcmp(*args, "-rand")) {
				if (args[1]) {
					args++;
					inrand = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-inkey")) {
				if (args[1]) {
					args++;
					keyname = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-certfile")) {
				if (args[1]) {
					args++;
					certfile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-name")) {
				if (args[1]) {
					args++;
					name = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-LMK"))
				add_lmk = 1;
			else if (!strcmp(*args, "-CSP")) {
				if (args[1]) {
					args++;
					csp_name = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-caname")) {
				if (args[1]) {
					args++;
					if (!canames)
						canames = sk_OPENSSL_STRING_new_null();
					sk_OPENSSL_STRING_push(canames, *args);
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-in")) {
				if (args[1]) {
					args++;
					infile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-out")) {
				if (args[1]) {
					args++;
					outfile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-passin")) {
				if (args[1]) {
					args++;
					passargin = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-passout")) {
				if (args[1]) {
					args++;
					passargout = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-password")) {
				if (args[1]) {
					args++;
					passarg = *args;
					noprompt = 1;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-CApath")) {
				if (args[1]) {
					args++;
					CApath = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-CAfile")) {
				if (args[1]) {
					args++;
					CAfile = *args;
				} else
					badarg = 1;
#ifndef OPENSSL_NO_ENGINE
			} else if (!strcmp(*args, "-engine")) {
				if (args[1]) {
					args++;
					engine = *args;
				} else
					badarg = 1;
#endif
			} else
				badarg = 1;

		} else
			badarg = 1;
		args++;
	}

	if (badarg) {
		BIO_printf(bio_err, "Usage: pkcs12 [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-export       output PKCS12 file\n");
		BIO_printf(bio_err, "-chain        add certificate chain\n");
		BIO_printf(bio_err, "-inkey file   private key if not infile\n");
		BIO_printf(bio_err, "-certfile f   add all certs in f\n");
		BIO_printf(bio_err, "-CApath arg   - PEM format directory of CA's\n");
		BIO_printf(bio_err, "-CAfile arg   - PEM format file of CA's\n");
		BIO_printf(bio_err, "-name \"name\"  use name as friendly name\n");
		BIO_printf(bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
		BIO_printf(bio_err, "-in  infile   input filename\n");
		BIO_printf(bio_err, "-out outfile  output filename\n");
		BIO_printf(bio_err, "-noout        don't output anything, just verify.\n");
		BIO_printf(bio_err, "-nomacver     don't verify MAC.\n");
		BIO_printf(bio_err, "-nocerts      don't output certificates.\n");
		BIO_printf(bio_err, "-clcerts      only output client certificates.\n");
		BIO_printf(bio_err, "-cacerts      only output CA certificates.\n");
		BIO_printf(bio_err, "-nokeys       don't output private keys.\n");
		BIO_printf(bio_err, "-info         give info about PKCS#12 structure.\n");
		BIO_printf(bio_err, "-des          encrypt private keys with DES\n");
		BIO_printf(bio_err, "-des3         encrypt private keys with triple DES (default)\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err, "-idea         encrypt private keys with idea\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err, "-seed         encrypt private keys with seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
		BIO_printf(bio_err, "              encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err, "              encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err, "-nodes        don't encrypt private keys\n");
		BIO_printf(bio_err, "-noiter       don't use encryption iteration\n");
		BIO_printf(bio_err, "-nomaciter    don't use MAC iteration\n");
		BIO_printf(bio_err, "-maciter      use MAC iteration\n");
		BIO_printf(bio_err, "-nomac        don't generate MAC\n");
		BIO_printf(bio_err, "-twopass      separate MAC, encryption passwords\n");
		BIO_printf(bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
		BIO_printf(bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
		BIO_printf(bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
		BIO_printf(bio_err, "-macalg alg   digest algorithm used in MAC (default SHA1)\n");
		BIO_printf(bio_err, "-keyex        set MS key exchange type\n");
		BIO_printf(bio_err, "-keysig       set MS key signature type\n");
		BIO_printf(bio_err, "-password p   set import/export password source\n");
		BIO_printf(bio_err, "-passin p     input file pass phrase source\n");
		BIO_printf(bio_err, "-passout p    output file pass phrase source\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err, "-engine e     use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err, "-rand file:file:...\n");
		BIO_printf(bio_err, "              load the file (or the files in the directory) into\n");
		BIO_printf(bio_err, "              the random number generator\n");
		BIO_printf(bio_err, "-CSP name     Microsoft CSP name\n");
		BIO_printf(bio_err, "-LMK          Add local machine keyset attribute to private key\n");
		goto end;
	}
#ifndef OPENSSL_NO_ENGINE
	e = setup_engine(bio_err, engine, 0);
#endif

	if (passarg) {
		if (export_cert)
			passargout = passarg;
		else
			passargin = passarg;
	}
	if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
		BIO_printf(bio_err, "Error getting passwords\n");
		goto end;
	}
	if (!cpass) {
		if (export_cert)
			cpass = passout;
		else
			cpass = passin;
	}
	if (cpass) {
		mpass = cpass;
		noprompt = 1;
	} else {
		cpass = pass;
		mpass = macpass;
	}

	ERR_load_crypto_strings();

#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("read files");
#endif

	if (!infile)
		in = BIO_new_fp(stdin, BIO_NOCLOSE);
	else
		in = BIO_new_file(infile, "rb");
	if (!in) {
		BIO_printf(bio_err, "Error opening input file %s\n",
		    infile ? infile : "<stdin>");
		perror(infile);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("write files");
#endif

	if (!outfile) {
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
	} else
		out = BIO_new_file(outfile, "wb");
	if (!out) {
		BIO_printf(bio_err, "Error opening output file %s\n",
		    outfile ? outfile : "<stdout>");
		perror(outfile);
		goto end;
	}
	if (twopass) {
#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("read MAC password");
#endif
		if (EVP_read_pw_string(macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
			goto end;
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
	}
	if (export_cert) {
		EVP_PKEY *key = NULL;
		X509 *ucert = NULL, *x = NULL;
		STACK_OF(X509) * certs = NULL;
		const EVP_MD *macmd = NULL;
		unsigned char *catmp = NULL;
		int i;

		if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
			BIO_printf(bio_err, "Nothing to do!\n");
			goto export_end;
		}
		if (options & NOCERTS)
			chain = 0;

#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("process -export_cert");
		CRYPTO_push_info("reading private key");
#endif
		if (!(options & NOKEYS)) {
			key = load_key(bio_err, keyname ? keyname : infile,
			    FORMAT_PEM, 1, passin, e, "private key");
			if (!key)
				goto export_end;
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from input");
#endif

		/* Load in all certs in input file */
		if (!(options & NOCERTS)) {
			certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
			    "certificates");
			if (!certs)
				goto export_end;

			if (key) {
				/* Look for matching private key */
				for (i = 0; i < sk_X509_num(certs); i++) {
					x = sk_X509_value(certs, i);
					if (X509_check_private_key(x, key)) {
						ucert = x;
						/* Zero keyid and alias */
						X509_keyid_set1(ucert, NULL, 0);
						X509_alias_set1(ucert, NULL, 0);
						/* Remove from list */
						(void) sk_X509_delete(certs, i);
						break;
					}
				}
				if (!ucert) {
					BIO_printf(bio_err, "No certificate matches private key\n");
					goto export_end;
				}
			}
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from input 2");
#endif

		/* Add any more certificates asked for */
		if (certfile) {
			STACK_OF(X509) * morecerts = NULL;
			if (!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
				    NULL, e,
				    "certificates from certfile")))
				goto export_end;
			while (sk_X509_num(morecerts) > 0)
				sk_X509_push(certs, sk_X509_shift(morecerts));
			sk_X509_free(morecerts);
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from certfile");
#endif

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("building chain");
#endif

		/* If chaining get chain from user cert */
		if (chain) {
			int vret;
			STACK_OF(X509) * chain2;
			X509_STORE *store = X509_STORE_new();
			if (!store) {
				BIO_printf(bio_err, "Memory allocation error\n");
				goto export_end;
			}
			if (!X509_STORE_load_locations(store, CAfile, CApath))
				X509_STORE_set_default_paths(store);

			vret = get_cert_chain(ucert, store, &chain2);
			X509_STORE_free(store);

			if (!vret) {
				/* Exclude verified certificate */
				for (i = 1; i < sk_X509_num(chain2); i++)
					sk_X509_push(certs, sk_X509_value(chain2, i));
				/* Free first certificate */
				X509_free(sk_X509_value(chain2, 0));
				sk_X509_free(chain2);
			} else {
				if (vret >= 0)
					BIO_printf(bio_err, "Error %s getting chain.\n",
					    X509_verify_cert_error_string(vret));
				else
					ERR_print_errors(bio_err);
				goto export_end;
			}
		}
		/* Add any CA names */

		for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
			catmp = (unsigned char *) sk_OPENSSL_STRING_value(canames, i);
			X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
		}

		if (csp_name && key)
			EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
			    MBSTRING_ASC, (unsigned char *) csp_name, -1);

		if (add_lmk && key)
			EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading password");
#endif

		if (!noprompt &&
		    EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
			goto export_end;
		}
		if (!twopass)
			strlcpy(macpass, pass, sizeof macpass);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("creating PKCS#12 structure");
#endif

		p12 = PKCS12_create(cpass, name, key, ucert, certs,
		    key_pbe, cert_pbe, iter, -1, keytype);

		if (!p12) {
			ERR_print_errors(bio_err);
			goto export_end;
		}
		if (macalg) {
			macmd = EVP_get_digestbyname(macalg);
			if (!macmd) {
				BIO_printf(bio_err, "Unknown digest algorithm %s\n",
				    macalg);
			}
		}
		if (maciter != -1)
			PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("writing pkcs12");
#endif

		i2d_PKCS12_bio(out, p12);

		ret = 0;

export_end:
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_pop_info();
		CRYPTO_push_info("process -export_cert: freeing");
#endif

		if (key)
			EVP_PKEY_free(key);
		if (certs)
			sk_X509_pop_free(certs, X509_free);
		if (ucert)
			X509_free(ucert);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
		goto end;

	}
	if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
		ERR_print_errors(bio_err);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("read import password");
#endif
	if (!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif

	if (!twopass)
		strlcpy(macpass, pass, sizeof macpass);

	if ((options & INFO) && p12->mac)
		BIO_printf(bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
	if (macver) {
#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("verify MAC");
#endif
		/* If we enter empty password try no password first */
		if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
			/* If mac and crypto pass the same set it to NULL too */
			if (!twopass)
				cpass = NULL;
		} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
			BIO_printf(bio_err, "Mac verify error: invalid password?\n");
			ERR_print_errors(bio_err);
			goto end;
		}
		BIO_printf(bio_err, "MAC verified OK\n");
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("output keys and certificates");
#endif
	if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout)) {
		BIO_printf(bio_err, "Error outputting keys and certificates\n");
		ERR_print_errors(bio_err);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif
	ret = 0;
end:
	if (p12)
		PKCS12_free(p12);
#ifdef CRYPTO_MDEBUG
	CRYPTO_remove_all_info();
#endif
	BIO_free(in);
	BIO_free_all(out);
	if (canames)
		sk_OPENSSL_STRING_free(canames);
	if (passin)
		free(passin);
	if (passout)
		free(passout);
	
	return (ret);
}
コード例 #20
0
ファイル: ocsp.c プロジェクト: lullajd/openssl
int ocsp_main(int argc, char **argv)
{
    BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
    const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
    int trailing_md = 0;
    CA_DB *rdb = NULL;
    EVP_PKEY *key = NULL, *rkey = NULL;
    OCSP_BASICRESP *bs = NULL;
    OCSP_REQUEST *req = NULL;
    OCSP_RESPONSE *resp = NULL;
    STACK_OF(CONF_VALUE) *headers = NULL;
    STACK_OF(OCSP_CERTID) *ids = NULL;
    STACK_OF(OPENSSL_STRING) *reqnames = NULL;
    STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
    STACK_OF(X509) *issuers = NULL;
    X509 *issuer = NULL, *cert = NULL;
    STACK_OF(X509) *rca_cert = NULL;
    X509 *signer = NULL, *rsigner = NULL;
    X509_STORE *store = NULL;
    X509_VERIFY_PARAM *vpm = NULL;
    const char *CAfile = NULL, *CApath = NULL;
    char *header, *value;
    char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
    char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
    char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
    char *rsignfile = NULL, *rkeyfile = NULL;
    char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
    char *signfile = NULL, *keyfile = NULL;
    char *thost = NULL, *tport = NULL, *tpath = NULL;
    int noCAfile = 0, noCApath = 0;
    int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
    int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
    int req_text = 0, resp_text = 0, ret = 1;
#ifndef OPENSSL_NO_SOCK
    int req_timeout = -1;
#endif
    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
    unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
    OPTION_CHOICE o;
    char *prog;

    reqnames = sk_OPENSSL_STRING_new_null();
    if (reqnames == NULL)
        goto end;
    ids = sk_OCSP_CERTID_new_null();
    if (ids == NULL)
        goto end;
    if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
        return 1;

    prog = opt_init(argc, argv, ocsp_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            ret = 0;
            opt_help(ocsp_options);
            goto end;
        case OPT_OUTFILE:
            outfile = opt_arg();
            break;
        case OPT_TIMEOUT:
#ifndef OPENSSL_NO_SOCK
            req_timeout = atoi(opt_arg());
#endif
            break;
        case OPT_URL:
            OPENSSL_free(thost);
            OPENSSL_free(tport);
            OPENSSL_free(tpath);
            thost = tport = tpath = NULL;
            if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
                BIO_printf(bio_err, "%s Error parsing URL\n", prog);
                goto end;
            }
            thost = host;
            tport = port;
            tpath = path;
            break;
        case OPT_HOST:
            host = opt_arg();
            break;
        case OPT_PORT:
            port = opt_arg();
            break;
        case OPT_IGNORE_ERR:
            ignore_err = 1;
            break;
        case OPT_NOVERIFY:
            noverify = 1;
            break;
        case OPT_NONCE:
            add_nonce = 2;
            break;
        case OPT_NO_NONCE:
            add_nonce = 0;
            break;
        case OPT_RESP_NO_CERTS:
            rflags |= OCSP_NOCERTS;
            break;
        case OPT_RESP_KEY_ID:
            rflags |= OCSP_RESPID_KEY;
            break;
        case OPT_NO_CERTS:
            sign_flags |= OCSP_NOCERTS;
            break;
        case OPT_NO_SIGNATURE_VERIFY:
            verify_flags |= OCSP_NOSIGS;
            break;
        case OPT_NO_CERT_VERIFY:
            verify_flags |= OCSP_NOVERIFY;
            break;
        case OPT_NO_CHAIN:
            verify_flags |= OCSP_NOCHAIN;
            break;
        case OPT_NO_CERT_CHECKS:
            verify_flags |= OCSP_NOCHECKS;
            break;
        case OPT_NO_EXPLICIT:
            verify_flags |= OCSP_NOEXPLICIT;
            break;
        case OPT_TRUST_OTHER:
            verify_flags |= OCSP_TRUSTOTHER;
            break;
        case OPT_NO_INTERN:
            verify_flags |= OCSP_NOINTERN;
            break;
        case OPT_BADSIG:
            badsig = 1;
            break;
        case OPT_TEXT:
            req_text = resp_text = 1;
            break;
        case OPT_REQ_TEXT:
            req_text = 1;
            break;
        case OPT_RESP_TEXT:
            resp_text = 1;
            break;
        case OPT_REQIN:
            reqin = opt_arg();
            break;
        case OPT_RESPIN:
            respin = opt_arg();
            break;
        case OPT_SIGNER:
            signfile = opt_arg();
            break;
        case OPT_VAFILE:
            verify_certfile = opt_arg();
            verify_flags |= OCSP_TRUSTOTHER;
            break;
        case OPT_SIGN_OTHER:
            sign_certfile = opt_arg();
            break;
        case OPT_VERIFY_OTHER:
            verify_certfile = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_NOCAFILE:
            noCAfile = 1;
            break;
        case OPT_NOCAPATH:
            noCApath = 1;
            break;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto end;
            vpmtouched++;
            break;
        case OPT_VALIDITY_PERIOD:
            opt_long(opt_arg(), &nsec);
            break;
        case OPT_STATUS_AGE:
            opt_long(opt_arg(), &maxage);
            break;
        case OPT_SIGNKEY:
            keyfile = opt_arg();
            break;
        case OPT_REQOUT:
            reqout = opt_arg();
            break;
        case OPT_RESPOUT:
            respout = opt_arg();
            break;
        case OPT_PATH:
            path = opt_arg();
            break;
        case OPT_ISSUER:
            issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
            if (issuer == NULL)
                goto end;
            if (issuers == NULL) {
                if ((issuers = sk_X509_new_null()) == NULL)
                    goto end;
            }
            sk_X509_push(issuers, issuer);
            break;
        case OPT_CERT:
            X509_free(cert);
            cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
            if (cert == NULL)
                goto end;
            if (cert_id_md == NULL)
                cert_id_md = EVP_sha1();
            if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
                goto end;
            if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
                goto end;
            trailing_md = 0;
            break;
        case OPT_SERIAL:
            if (cert_id_md == NULL)
                cert_id_md = EVP_sha1();
            if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
                goto end;
            if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
                goto end;
            trailing_md = 0;
            break;
        case OPT_INDEX:
            ridx_filename = opt_arg();
            break;
        case OPT_CA:
            rca_filename = opt_arg();
            break;
        case OPT_NMIN:
            opt_int(opt_arg(), &nmin);
            if (ndays == -1)
                ndays = 0;
            break;
        case OPT_REQUEST:
            opt_int(opt_arg(), &accept_count);
            break;
        case OPT_NDAYS:
            ndays = atoi(opt_arg());
            break;
        case OPT_RSIGNER:
            rsignfile = opt_arg();
            break;
        case OPT_RKEY:
            rkeyfile = opt_arg();
            break;
        case OPT_ROTHER:
            rcertfile = opt_arg();
            break;
        case OPT_RMD:   /* Response MessageDigest */
            if (!opt_md(opt_arg(), &rsign_md))
                goto end;
            break;
        case OPT_HEADER:
            header = opt_arg();
            value = strchr(header, '=');
            if (value == NULL) {
                BIO_printf(bio_err, "Missing = in header key=value\n");
                goto opthelp;
            }
            *value++ = '\0';
            if (!X509V3_add_value(header, value, &headers))
                goto end;
            break;
        case OPT_MD:
            if (trailing_md) {
                BIO_printf(bio_err,
                           "%s: Digest must be before -cert or -serial\n",
                           prog);
                goto opthelp;
            }
            if (!opt_md(opt_unknown(), &cert_id_md))
                goto opthelp;
            trailing_md = 1;
            break;
        }
    }

    if (trailing_md) {
        BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
                   prog);
        goto opthelp;
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

    /* Have we anything to do? */
    if (req == NULL&& reqin == NULL
        && respin == NULL && !(port != NULL && ridx_filename != NULL))
        goto opthelp;

    out = bio_open_default(outfile, 'w', FORMAT_TEXT);
    if (out == NULL)
        goto end;

    if (req == NULL && (add_nonce != 2))
        add_nonce = 0;

    if (req == NULL && reqin != NULL) {
        derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        req = d2i_OCSP_REQUEST_bio(derbio, NULL);
        BIO_free(derbio);
        if (req == NULL) {
            BIO_printf(bio_err, "Error reading OCSP request\n");
            goto end;
        }
    }

    if (req == NULL && port != NULL) {
        acbio = init_responder(port);
        if (acbio == NULL)
            goto end;
    }

    if (rsignfile != NULL) {
        if (rkeyfile == NULL)
            rkeyfile = rsignfile;
        rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
        if (rsigner == NULL) {
            BIO_printf(bio_err, "Error loading responder certificate\n");
            goto end;
        }
        if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
                        NULL, "CA certificate"))
            goto end;
        if (rcertfile != NULL) {
            if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
                            "responder other certificates"))
                goto end;
        }
        rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
                        "responder private key");
        if (rkey == NULL)
            goto end;
    }
    if (acbio != NULL)
        BIO_printf(bio_err, "Waiting for OCSP client connections...\n");

redo_accept:

    if (acbio != NULL) {
        if (!do_responder(&req, &cbio, acbio))
            goto end;
        if (req == NULL) {
            resp =
                OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
                                     NULL);
            send_ocsp_response(cbio, resp);
            goto done_resp;
        }
    }

    if (req == NULL
        && (signfile != NULL || reqout != NULL
            || host != NULL || add_nonce || ridx_filename != NULL)) {
        BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
        goto end;
    }

    if (req != NULL && add_nonce)
        OCSP_request_add1_nonce(req, NULL, -1);

    if (signfile != NULL) {
        if (keyfile == NULL)
            keyfile = signfile;
        signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
        if (signer == NULL) {
            BIO_printf(bio_err, "Error loading signer certificate\n");
            goto end;
        }
        if (sign_certfile != NULL) {
            if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
                            "signer certificates"))
                goto end;
        }
        key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
                       "signer private key");
        if (key == NULL)
            goto end;

        if (!OCSP_request_sign
            (req, signer, key, NULL, sign_other, sign_flags)) {
            BIO_printf(bio_err, "Error signing OCSP request\n");
            goto end;
        }
    }

    if (req_text && req != NULL)
        OCSP_REQUEST_print(out, req, 0);

    if (reqout != NULL) {
        derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        i2d_OCSP_REQUEST_bio(derbio, req);
        BIO_free(derbio);
    }

    if (ridx_filename != NULL
        && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
        BIO_printf(bio_err,
                   "Need a responder certificate, key and CA for this operation!\n");
        goto end;
    }

    if (ridx_filename != NULL && rdb == NULL) {
        rdb = load_index(ridx_filename, NULL);
        if (rdb == NULL)
            goto end;
        if (!index_index(rdb))
            goto end;
    }

    if (rdb != NULL) {
        make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey,
                               rsign_md, rother, rflags, nmin, ndays, badsig);
        if (cbio != NULL)
            send_ocsp_response(cbio, resp);
    } else if (host != NULL) {
# ifndef OPENSSL_NO_SOCK
        resp = process_responder(req, host, path,
                                 port, use_ssl, headers, req_timeout);
        if (resp == NULL)
            goto end;
# else
        BIO_printf(bio_err,
                   "Error creating connect BIO - sockets not supported.\n");
        goto end;
# endif
    } else if (respin != NULL) {
        derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
        BIO_free(derbio);
        if (resp == NULL) {
            BIO_printf(bio_err, "Error reading OCSP response\n");
            goto end;
        }
    } else {
        ret = 0;
        goto end;
    }

 done_resp:

    if (respout != NULL) {
        derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        i2d_OCSP_RESPONSE_bio(derbio, resp);
        BIO_free(derbio);
    }

    i = OCSP_response_status(resp);
    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
        BIO_printf(out, "Responder Error: %s (%d)\n",
                   OCSP_response_status_str(i), i);
        if (ignore_err)
            goto redo_accept;
        ret = 0;
        goto end;
    }

    if (resp_text)
        OCSP_RESPONSE_print(out, resp, 0);

    /* If running as responder don't verify our own response */
    if (cbio != NULL) {
        /* If not unlimited, see if we took all we should. */
        if (accept_count != -1 && --accept_count <= 0) {
            ret = 0;
            goto end;
        }
        BIO_free_all(cbio);
        cbio = NULL;
        OCSP_REQUEST_free(req);
        req = NULL;
        OCSP_RESPONSE_free(resp);
        resp = NULL;
        goto redo_accept;
    }
    if (ridx_filename != NULL) {
        ret = 0;
        goto end;
    }

    if (store == NULL) {
        store = setup_verify(CAfile, CApath, noCAfile, noCApath);
        if (!store)
            goto end;
    }
    if (vpmtouched)
        X509_STORE_set1_param(store, vpm);
    if (verify_certfile != NULL) {
        if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
                        "validator certificate"))
            goto end;
    }

    bs = OCSP_response_get1_basic(resp);
    if (bs == NULL) {
        BIO_printf(bio_err, "Error parsing response\n");
        goto end;
    }

    ret = 0;

    if (!noverify) {
        if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
            if (i == -1)
                BIO_printf(bio_err, "WARNING: no nonce in response\n");
            else {
                BIO_printf(bio_err, "Nonce Verify error\n");
                ret = 1;
                goto end;
            }
        }

        i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
        if (i <= 0 && issuers) {
            i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
            if (i > 0)
                ERR_clear_error();
        }
        if (i <= 0) {
            BIO_printf(bio_err, "Response Verify Failure\n");
            ERR_print_errors(bio_err);
            ret = 1;
        } else {
            BIO_printf(bio_err, "Response verify OK\n");
        }
    }

    print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);

 end:
    ERR_print_errors(bio_err);
    X509_free(signer);
    X509_STORE_free(store);
    X509_VERIFY_PARAM_free(vpm);
    EVP_PKEY_free(key);
    EVP_PKEY_free(rkey);
    X509_free(cert);
    sk_X509_pop_free(issuers, X509_free);
    X509_free(rsigner);
    sk_X509_pop_free(rca_cert, X509_free);
    free_index(rdb);
    BIO_free_all(cbio);
    BIO_free_all(acbio);
    BIO_free(out);
    OCSP_REQUEST_free(req);
    OCSP_RESPONSE_free(resp);
    OCSP_BASICRESP_free(bs);
    sk_OPENSSL_STRING_free(reqnames);
    sk_OCSP_CERTID_free(ids);
    sk_X509_pop_free(sign_other, X509_free);
    sk_X509_pop_free(verify_other, X509_free);
    sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
    OPENSSL_free(thost);
    OPENSSL_free(tport);
    OPENSSL_free(tpath);

    return ret;
}
コード例 #21
0
ファイル: verify.c プロジェクト: COCUS-NEXT/strongswan
/**
 * Verify a certificate signature
 */
static int verify()
{
	bool trusted = FALSE, valid = FALSE, revoked = FALSE;
	bool has_ca = FALSE, online = FALSE;
	certificate_t *cert;
	enumerator_t *enumerator;
	auth_cfg_t *auth;
	mem_cred_t *creds;
	char *arg, *file = NULL;

	creds = mem_cred_create();
	lib->credmgr->add_set(lib->credmgr, &creds->set);

	while (TRUE)
	{
		switch (command_getopt(&arg))
		{
			case 'h':
				creds->destroy(creds);
				return command_usage(NULL);
			case 'i':
				file = arg;
				continue;
			case 'c':
				if (load_certs(creds, arg, CERT_X509))
				{
					has_ca = TRUE;
				}
				continue;
			case 'l':
				if (load_certs(creds, arg, CERT_X509_CRL))
				{
					online = TRUE;
				}
				continue;
			case 'o':
				online = TRUE;
				continue;
			case EOF:
				break;
			default:
				creds->destroy(creds);
				return command_usage("invalid --verify option");
		}
		break;
	}

	if (file)
	{
		cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
								  BUILD_FROM_FILE, file, BUILD_END);
	}
	else
	{
		chunk_t chunk;

		set_file_mode(stdin, CERT_ASN1_DER);
		if (!chunk_from_fd(0, &chunk))
		{
			fprintf(stderr, "reading certificate failed: %s\n", strerror(errno));
			goto end;
		}
		cert = lib->creds->create(lib->creds, CRED_CERTIFICATE, CERT_X509,
								  BUILD_BLOB, chunk, BUILD_END);
		free(chunk.ptr);
	}
	if (!cert)
	{
		fprintf(stderr, "parsing certificate failed\n");
		goto end;
	}
	cert = creds->add_cert_ref(creds, !has_ca, cert);

	enumerator = lib->credmgr->create_trusted_enumerator(lib->credmgr,
									KEY_ANY, cert->get_subject(cert), online);
	if (enumerator->enumerate(enumerator, &cert, &auth))
	{
		trusted = TRUE;
		if (cert->get_validity(cert, NULL, NULL, NULL))
		{
			printf("certificate trusted, lifetimes valid");
			valid = TRUE;
		}
		else
		{
			printf("certificate trusted, but no valid lifetime");
		}
		if (online)
		{
			switch ((uintptr_t)auth->get(auth, AUTH_RULE_CRL_VALIDATION))
			{
				case VALIDATION_GOOD:
					printf(", certificate not revoked");
					break;
				case VALIDATION_SKIPPED:
					printf(", no revocation information");
					break;
				case VALIDATION_STALE:
					printf(", revocation information stale");
					break;
				case VALIDATION_FAILED:
					printf(", revocation checking failed");
					break;
				case VALIDATION_ON_HOLD:
					printf(", certificate revocation on hold");
					revoked = TRUE;
					break;
				case VALIDATION_REVOKED:
					printf(", certificate revoked");
					revoked = TRUE;
					break;
			}
		}
		printf("\n");
	}
	enumerator->destroy(enumerator);
	cert->destroy(cert);

	if (!trusted)
	{
		printf("certificate untrusted\n");
	}

end:
	lib->credmgr->remove_set(lib->credmgr, &creds->set);
	creds->destroy(creds);

	if (!trusted)
	{
		return 1;
	}
	if (!valid)
	{
		return 2;
	}
	if (revoked)
	{
		return 3;
	}
	return 0;
}