Exemplo n.º 1
0
static int do_generate(BIO *bio, char *genstr, char *genconf, BUF_MEM *buf)
	{
	CONF *cnf = NULL;
	int len;
	long errline;
	unsigned char *p;
	ASN1_TYPE *atyp = NULL;

	if (genconf)
		{
		cnf = NCONF_new(NULL);
		if (!NCONF_load(cnf, genconf, &errline))
			goto conferr;
		if (!genstr)
			genstr = NCONF_get_string(cnf, "default", "asn1");
		if (!genstr)
			{
			BIO_printf(bio, "Can't find 'asn1' in '%s'\n", genconf);
			goto err;
			}
		}

	atyp = ASN1_generate_nconf(genstr, cnf);
	NCONF_free(cnf);

	if (!atyp)
		return -1;

	len = i2d_ASN1_TYPE(atyp, NULL);

	if (len <= 0)
		goto err;

	if (!BUF_MEM_grow(buf,len))
		goto err;

	p=(unsigned char *)buf->data;

	i2d_ASN1_TYPE(atyp, &p);

	ASN1_TYPE_free(atyp);
	return len;

	conferr:

	if (errline > 0)
		BIO_printf(bio, "Error on line %ld of config file '%s'\n",
							errline, genconf);
	else
		BIO_printf(bio, "Error loading config file '%s'\n", genconf);

	err:
	NCONF_free(cnf);
	ASN1_TYPE_free(atyp);

	return -1;

	}
Exemplo n.º 2
0
/*
 * GetConfigPtr is a public C-level function for getting OpenSSL CONF struct
 * from an OpenSSL::Config(eConfig) instance.  We decided to implement
 * OpenSSL::Config in Ruby level but we need to pass native CONF struct for
 * some OpenSSL features such as X509V3_EXT_*.
 */
CONF *
GetConfigPtr(VALUE obj)
{
    CONF *conf;
    VALUE str;
    BIO *bio;
    long eline = -1;

    OSSL_Check_Kind(obj, cConfig);
    str = rb_funcall(obj, rb_intern("to_s"), 0);
    bio = ossl_obj2bio(str);
    conf = NCONF_new(NULL);
    if(!conf) {
        BIO_free(bio);
        ossl_raise(eConfigError, NULL);
    }
    if(!NCONF_load_bio(conf, bio, &eline)) {
        BIO_free(bio);
        NCONF_free(conf);
        if (eline <= 0) ossl_raise(eConfigError, "wrong config format");
        else ossl_raise(eConfigError, "error in line %d", eline);
        ossl_raise(eConfigError, NULL);
    }
    BIO_free(bio);

    return conf;
}
Exemplo n.º 3
0
static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf)
{
    CONF *cnf = NULL;
    int len;
    unsigned char *p;
    ASN1_TYPE *atyp = NULL;

    if (genconf) {
        if ((cnf = app_load_config(genconf)) == NULL)
            goto err;
        if (!genstr)
            genstr = NCONF_get_string(cnf, "default", "asn1");
        if (!genstr) {
            BIO_printf(bio_err, "Can't find 'asn1' in '%s'\n", genconf);
            goto err;
        }
    }

    atyp = ASN1_generate_nconf(genstr, cnf);
    NCONF_free(cnf);
    cnf = NULL;

    if (!atyp)
        return -1;

    len = i2d_ASN1_TYPE(atyp, NULL);

    if (len <= 0)
        goto err;

    if (!BUF_MEM_grow(buf, len))
        goto err;

    p = (unsigned char *)buf->data;

    i2d_ASN1_TYPE(atyp, &p);

    ASN1_TYPE_free(atyp);
    return len;

 err:
    NCONF_free(cnf);
    ASN1_TYPE_free(atyp);
    return -1;
}
Exemplo n.º 4
0
gboolean
CertKey_GenerateKeyCert(int bits,                 // IN
                        int days,                 // IN
                        const gchar *confFile,    // IN
                        const gchar *keyFile,     // IN
                        const gchar *certFile)    // IN
{
   gboolean ret = FALSE;
   X509 *cert = NULL;
   X509_REQ *req = NULL;
   EVP_PKEY *pkey = NULL;
   CONF *config;
   gchar *err = NULL;

   config = LoadOpenSSLConf(confFile);
   if (!config) {
      goto exit;
   }

   req = GenerateX509CertReq(&pkey, config, bits);
   if (!req) {
      goto exit;
   }

   cert = GenerateX509Cert(req, config, days);
   if (!cert) {
      goto exit;
   }

   if (!X509_set_pubkey(cert, pkey)) {
      Error("Failed to set certificate public key: %s.\n",
            GetSSLError(&err));
      goto exit;
   }

   if (!X509_sign(cert, pkey, EVP_sha256())) {
      Error("Failed to sign the X509 certificate: %s.\n",
            GetSSLError(&err));
      goto exit;
   }

   /*
    * Write private key and certificate PEM files.
    */
   if (WritePemFile(pkey, keyFile, cert, certFile)) {
      ret = TRUE;
   }

exit:
   g_free(err);
   NCONF_free(config);
   EVP_PKEY_free(pkey);
   X509_REQ_free(req);
   X509_free(cert);

   return ret;
}
Exemplo n.º 5
0
Arquivo: conf.c Projeto: 1234-/openssl
int FuzzerTestOneInput(const uint8_t *buf, size_t len) {
    CONF *conf = NCONF_new(NULL);
    BIO *in = BIO_new(BIO_s_mem());
    long eline;

    OPENSSL_assert((size_t)BIO_write(in, buf, len) == len);
    NCONF_load_bio(conf, in, &eline);
    //NCONF_dump_fp(conf, stdout);
    NCONF_free(conf);
    BIO_free(in);

    return 0;
}
Exemplo n.º 6
0
static CONF *
LoadOpenSSLConf(const gchar *fname)              // IN
{
   CONF *config;
   const char *mask;
   gboolean ret = FALSE;
   gchar *err = NULL;

   config = NCONF_new(NULL);
   if (!config) {
      Error("Failed to allocate the OpenSSL config.\n");
      goto exit;
   }

   if (!NCONF_load(config, fname, NULL)) {
      Error("Failed to load the configuration file %s: %s.\n",
            fname, GetSSLError(&err));
      goto exit;
   }

   OPENSSL_load_builtin_modules();

   if (!CONF_modules_load(config, NULL, 0)) {
      Error("Error configuring OpenSSL modules: %s.\n",
            GetSSLError(&err));
      goto exit;
   }

   mask = NCONF_get_string(config, "req", "string_mask");
   if (mask) {
      ASN1_STRING_set_default_mask_asc(mask);
   }

   ret = TRUE;

exit:
   if (!ret) {
      NCONF_free(config);
      config = NULL;
   }
   g_free(err);

   return config;
}
Exemplo n.º 7
0
int test_main(int argc, char **argv)
{
    int result = 0;

    if (argc != 2) {
        TEST_info("Missing file argument");
        goto end;
    }
    if (!TEST_ptr(conf = NCONF_new(NULL))
            /* argv[1] should point to test/ssl_test_ctx_test.conf */
            || !TEST_int_gt(NCONF_load(conf, argv[1], NULL), 0))
        goto end;

    ADD_TEST(test_empty_configuration);
    ADD_TEST(test_good_configuration);
    ADD_ALL_TESTS(test_bad_configuration, OSSL_NELEM(bad_configurations));
    result = run_tests(argv[0]);

end:
    NCONF_free(conf);
    return result;
}
Exemplo n.º 8
0
int test_main(int argc, char **argv)
{
    int result = 0;
    long num_tests;

    if (argc != 2)
        return 1;

    conf = NCONF_new(NULL);
    TEST_check(conf != NULL);

    /* argv[1] should point to the test conf file */
    TEST_check(NCONF_load(conf, argv[1], NULL) > 0);

    TEST_check(NCONF_get_number_e(conf, NULL, "num_tests", &num_tests));

    ADD_ALL_TESTS(test_handshake, (int)(num_tests));
    result = run_tests(argv[0]);

    NCONF_free(conf);
    return result;
}
Exemplo n.º 9
0
int test_main(int argc, char **argv)
{
    int result = 0;

    if (argc != 2)
        return 1;

    conf = NCONF_new(NULL);
    TEST_check(conf != NULL);

    /* argv[1] should point to test/ssl_test_ctx_test.conf */
    TEST_check(NCONF_load(conf, argv[1], NULL) > 0);

    ADD_TEST(test_empty_configuration);
    ADD_TEST(test_good_configuration);
    ADD_ALL_TESTS(test_bad_configuration, OSSL_NELEM(bad_configurations));

    result = run_tests(argv[0]);

    NCONF_free(conf);

    return result;
}
Exemplo n.º 10
0
/*
 * Private
 */
static CONF *
parse_config(VALUE str, CONF *dst)
{
    CONF *conf;
    BIO *bio;
    long eline = -1;

    bio = ossl_obj2bio(str);
    conf = dst ? dst : NCONF_new(NULL);
    if(!conf){
	BIO_free(bio);
	ossl_raise(eConfigError, NULL);
    }
    if(!NCONF_load_bio(conf, bio, &eline)){
	BIO_free(bio);
	if(!dst) NCONF_free(conf);
	if (eline <= 0) ossl_raise(eConfigError, "wrong config format");
	else ossl_raise(eConfigError, "error in line %d", eline);
	ossl_raise(eConfigError, NULL);
    }
    BIO_free(bio);

    return conf;
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
  int                  i;
  long                 i_val, err = 0;
  char                 *key, *s_val;
  STACK_OF(CONF_VALUE) *sec;
  CONF_VALUE           *item;
  CONF                 *conf;
 
  conf = NCONF_new(NCONF_default(  ));
  if (!NCONF_load(conf, CONFFILE, &err))
    {
      if (err == 0)
	int_error("Error opening configuration file");
      else
        {
	  fprintf(stderr, "Error in %s on line %li\n", CONFFILE, err);
	  int_error("Errors parsing configuration file");
        }
    }
  if (!(s_val = NCONF_get_string(conf, NULL, GLOB_VAR)))
    {
      fprintf(stderr, "Error finding \"%s\" in [%s]\n", GLOB_VAR, NULL);
      int_error("Error finding string");
    }
  printf("Sec: %s, Key: %s, Val: %s\n", NULL, GLOB_VAR, s_val);
#if (OPENSSL_VERSION_NUMBER > 0x00907000L)
  if (!(err = NCONF_get_number_e(conf, NULL, GLOB_NUM, &i_val)))
    {
      fprintf(stderr, "Error finding \"%s\" in [%s]\n", GLOB_NUM, NULL);
      int_error("Error finding number");
    }
#else
  if (!(s_val = NCONF_get_string(conf, NULL, GLOB_NUM)))
    {
      fprintf(stderr, "Error finding \"%s\" in [%s]\n", GLOB_VAR, NULL);
      int_error("Error finding number");
    }
  i_val = atoi(s_val);
#endif
  printf("Sec: %s, Key: %s, Val: %i\n", NULL, GLOB_VAR, i_val);
  if (!(key = NCONF_get_string(conf, PARAMS, SEC_NAME)))
    {
      fprintf(stderr, "Error finding \"%s\" in [%s]\n", SEC_NAME, PARAMS);
      int_error("Error finding string");
    }
  printf("Sec: %s, Key: %s, Val: %s\n", PARAMS, SEC_NAME, key);
  if (!(sec = NCONF_get_section(conf, key)))
    {
      fprintf(stderr, "Error finding [%s]\n", key);
      int_error("Error finding string");
    }
  for (i = 0;  i < sk_CONF_VALUE_num(sec);  i++)
    {
      item = sk_CONF_VALUE_value(sec, i);
      printf("Sec: %s, Key: %s, Val: %s\n",
	     item->section, item->name, item->value);
    }
 
  NCONF_free(conf);
  return 0;
}
Exemplo n.º 12
0
int ts_main(int argc, char **argv)
{
    CONF *conf = NULL;
    char *CAfile = NULL, *untrusted = NULL, *engine = NULL, *prog, **helpp;
    char *configfile = default_config_file;
    char *section = NULL, *password = NULL;
    char *data = NULL, *digest = NULL, *rnd = NULL, *policy = NULL;
    char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL;
    char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL;
    const EVP_MD *md = NULL;
    OPTION_CHOICE o, mode = OPT_ERR;
    int ret = 1, no_nonce = 0, cert = 0, text = 0;
    int vpmtouched = 0;
    X509_VERIFY_PARAM *vpm = NULL;
    /* Input is ContentInfo instead of TimeStampResp. */
    int token_in = 0;
    /* Output is ContentInfo instead of TimeStampResp. */
    int token_out = 0;

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

    prog = opt_init(argc, argv, ts_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(ts_options);
            for (helpp = opt_helplist; *helpp; ++helpp)
                BIO_printf(bio_err, "%s\n", *helpp);
            ret = 0;
            goto end;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_SECTION:
            section = opt_arg();
            break;
        case OPT_QUERY:
        case OPT_REPLY:
        case OPT_VERIFY:
            if (mode != OPT_ERR)
                goto opthelp;
            mode = o;
            break;
        case OPT_DATA:
            data = opt_arg();
            break;
        case OPT_DIGEST:
            digest = opt_arg();
            break;
        case OPT_RAND:
            rnd = opt_arg();
            break;
        case OPT_TSPOLICY:
            policy = opt_arg();
            break;
        case OPT_NO_NONCE:
            no_nonce = 1;
            break;
        case OPT_CERT:
            cert = 1;
            break;
        case OPT_IN:
            in = opt_arg();
            break;
        case OPT_TOKEN_IN:
            token_in = 1;
            break;
        case OPT_OUT:
            out = opt_arg();
            break;
        case OPT_TOKEN_OUT:
            token_out = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_QUERYFILE:
            queryfile = opt_arg();
            break;
        case OPT_PASSIN:
            passin = opt_arg();
            break;
        case OPT_INKEY:
            inkey = opt_arg();
            break;
        case OPT_SIGNER:
            signer = opt_arg();
            break;
        case OPT_CHAIN:
            chain = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_UNTRUSTED:
            untrusted = opt_arg();
            break;
        case OPT_ENGINE:
            engine = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_unknown(), &md))
                goto opthelp;
            break;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto end;
            vpmtouched++;
            break;
        }
    }
    if (mode == OPT_ERR || opt_num_rest() != 0)
        goto opthelp;

    /* Seed the random number generator if it is going to be used. */
    if (mode == OPT_QUERY && !no_nonce) {
        if (!app_RAND_load_file(NULL, 1) && rnd == NULL)
            BIO_printf(bio_err, "warning, not much extra random "
                       "data, consider using the -rand option\n");
        if (rnd != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(rnd));
    }

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

    conf = load_config_file(configfile);
    if (configfile != default_config_file && !app_load_modules(conf))
        goto end;

    /* Check parameter consistency and execute the appropriate function. */
    switch (mode) {
    default:
    case OPT_ERR:
        goto opthelp;
    case OPT_QUERY:
        if (vpmtouched)
            goto opthelp;
        if ((data != NULL) && (digest != NULL))
            goto opthelp;
        ret = !query_command(data, digest, md, policy, no_nonce, cert,
                             in, out, text);
        break;
    case OPT_REPLY:
        if (vpmtouched)
            goto opthelp;
        if ((in != NULL) && (queryfile != NULL))
            goto opthelp;
        if (in == NULL) {
            if ((conf == NULL) || (token_in != 0))
                goto opthelp;
        }
        ret = !reply_command(conf, section, engine, queryfile,
                             password, inkey, md, signer, chain, policy,
                             in, token_in, out, token_out, text);
        break;
    case OPT_VERIFY:
        if ((in == NULL) || !EXACTLY_ONE(queryfile, data, digest))
            goto opthelp;
        ret = !verify_command(data, digest, queryfile, in, token_in,
                              CApath, CAfile, untrusted,
                              vpmtouched ? vpm : NULL);
    }

 end:
    X509_VERIFY_PARAM_free(vpm);
    app_RAND_write_file(NULL);
    NCONF_free(conf);
    OPENSSL_free(password);
    return (ret);
}
Exemplo n.º 13
0
int main(int Argc, char *ARGV[])
{
    ARGS arg;
#define PROG_NAME_SIZE	39
    char pname[PROG_NAME_SIZE+1];
    FUNCTION f,*fp;
    MS_STATIC const char *prompt;
    MS_STATIC char buf[1024];
    char *to_free=NULL;
    int n,i,ret=0;
    int argc;
    char **argv,*p;
    LHASH_OF(FUNCTION) *prog=NULL;
    long errline;

#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* 2011-03-22 SMS.
     * If we have 32-bit pointers everywhere, then we're safe, and
     * we bypass this mess, as on non-VMS systems.  (See ARGV,
     * above.)
     * Problem 1: Compaq/HP C before V7.3 always used 32-bit
     * pointers for argv[].
     * Fix 1: For a 32-bit argv[], when we're using 64-bit pointers
     * everywhere else, we always allocate and use a 64-bit
     * duplicate of argv[].
     * Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed
     * to NULL-terminate a 64-bit argv[].  (As this was written, the
     * compiler ECO was available only on IA64.)
     * Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a
     * 64-bit argv[argc] for NULL, and, if necessary, use a
     * (properly) NULL-terminated (64-bit) duplicate of argv[].
     * The same code is used in either case to duplicate argv[].
     * Some of these decisions could be handled in preprocessing,
     * but the code tends to get even uglier, and the penalty for
     * deciding at compile- or run-time is tiny.
     */
    char **Argv = NULL;
    int free_Argv = 0;

    if ((sizeof( _Argv) < 8)        /* 32-bit argv[]. */
# if !defined( VMS_TRUST_ARGV)
            || (_Argv[ Argc] != NULL)      /* Untrusted argv[argc] not NULL. */
# endif
       )
    {
        int i;
        Argv = OPENSSL_malloc( (Argc+ 1)* sizeof( char *));
        if (Argv == NULL)
        {
            ret = -1;
            goto end;
        }
        for(i = 0; i < Argc; i++)
            Argv[i] = _Argv[i];
        Argv[ Argc] = NULL;     /* Certain NULL termination. */
        free_Argv = 1;
    }
    else
    {
        /* Use the known-good 32-bit argv[] (which needs the
         * type cast to satisfy the compiler), or the trusted or
         * tested-good 64-bit argv[] as-is. */
        Argv = (char **)_Argv;
    }
#endif /* defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) */

    arg.data=NULL;
    arg.count=0;

    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 (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
    {
        if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))
        {
            CRYPTO_malloc_debug_init();
            CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
        }
        else
        {
            /* OPENSSL_DEBUG_MEMORY=off */
            CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
        }
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
    if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
    {
        CRYPTO_set_locking_callback(lock_dbg_cb);
    }

    apps_startup();

    /* Lets load up our environment a little */
    p=getenv("OPENSSL_CONF");
    if (p == NULL)
        p=getenv("SSLEAY_CONF");
    if (p == NULL)
        p=to_free=make_config_name();

    default_config_file=p;

    config=NCONF_new(NULL);
    i=NCONF_load(config,p,&errline);
    if (i == 0)
    {
        if (ERR_GET_REASON(ERR_peek_last_error())
                == CONF_R_NO_SUCH_FILE)
        {
            BIO_printf(bio_err,
                       "WARNING: can't open config file: %s\n",p);
            ERR_clear_error();
            NCONF_free(config);
            config = NULL;
        }
        else
        {
            ERR_print_errors(bio_err);
            NCONF_free(config);
            exit(1);
        }
    }

    prog=prog_init();

    /* first check the program name */
    program_name(Argv[0],pname,sizeof pname);

    f.name=pname;
    fp=lh_FUNCTION_retrieve(prog,&f);
    if (fp != NULL)
    {
        Argv[0]=pname;
        ret=fp->func(Argc,Argv);
        goto end;
    }

    /* ok, now check that there are not arguments, if there are,
     * run with them, shifting the ssleay off the front */
    if (Argc != 1)
    {
        Argc--;
        Argv++;
        ret=do_cmd(prog,Argc,Argv);
        if (ret < 0) ret=0;
        goto end;
    }

    /* ok, lets enter the old 'OpenSSL>' mode */

    for (;;)
    {
        ret=0;
        p=buf;
        n=sizeof buf;
        i=0;
        for (;;)
        {
            p[0]='\0';
            if (i++)
                prompt=">";
            else	prompt="OpenSSL> ";
            fputs(prompt,stdout);
            fflush(stdout);
            if (!fgets(p,n,stdin))
                goto end;
            if (p[0] == '\0') goto end;
            i=strlen(p);
            if (i <= 1) break;
            if (p[i-2] != '\\') break;
            i-=2;
            p+=i;
            n-=i;
        }
        if (!chopup_args(&arg,buf,&argc,&argv)) break;

        ret=do_cmd(prog,argc,argv);
        if (ret < 0)
        {
            ret=0;
            goto end;
        }
        if (ret != 0)
            BIO_printf(bio_err,"error in %s\n",argv[0]);
        (void)BIO_flush(bio_err);
    }
    BIO_printf(bio_err,"bad exit\n");
    ret=1;
end:
    if (to_free)
        OPENSSL_free(to_free);
    if (config != NULL)
    {
        NCONF_free(config);
        config=NULL;
    }
    if (prog != NULL) lh_FUNCTION_free(prog);
    if (arg.data != NULL) OPENSSL_free(arg.data);

    apps_shutdown();

    CRYPTO_mem_leaks(bio_err);
    if (bio_err != NULL)
    {
        BIO_free(bio_err);
        bio_err=NULL;
    }
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* Free any duplicate Argv[] storage. */
    if (free_Argv)
    {
        OPENSSL_free(Argv);
    }
#endif
    OPENSSL_EXIT(ret);
}
Exemplo n.º 14
0
int
ts_main(int argc, char **argv)
{
	int ret = 1;
	char *configfile = NULL;
	char *section = NULL;
	CONF *conf = NULL;
	enum mode {
		CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY
	} mode = CMD_NONE;
	char *data = NULL;
	char *digest = NULL;
	const EVP_MD *md = NULL;
	char *policy = NULL;
	int no_nonce = 0;
	int cert = 0;
	char *in = NULL;
	char *out = NULL;
	int text = 0;
	char *queryfile = NULL;
	char *passin = NULL;	/* Password source. */
	char *password = NULL;	/* Password itself. */
	char *inkey = NULL;
	char *signer = NULL;
	char *chain = NULL;
	char *ca_path = NULL;
	char *ca_file = NULL;
	char *untrusted = NULL;
	char *engine = NULL;
	/* Input is ContentInfo instead of TimeStampResp. */
	int token_in = 0;
	/* Output is ContentInfo instead of TimeStampResp. */
	int token_out = 0;

	for (argc--, argv++; argc > 0; argc--, argv++) {
		if (strcmp(*argv, "-config") == 0) {
			if (argc-- < 1)
				goto usage;
			configfile = *++argv;
		} else if (strcmp(*argv, "-section") == 0) {
			if (argc-- < 1)
				goto usage;
			section = *++argv;
		} else if (strcmp(*argv, "-query") == 0) {
			if (mode != CMD_NONE)
				goto usage;
			mode = CMD_QUERY;
		} else if (strcmp(*argv, "-data") == 0) {
			if (argc-- < 1)
				goto usage;
			data = *++argv;
		} else if (strcmp(*argv, "-digest") == 0) {
			if (argc-- < 1)
				goto usage;
			digest = *++argv;
		} else if (strcmp(*argv, "-policy") == 0) {
			if (argc-- < 1)
				goto usage;
			policy = *++argv;
		} else if (strcmp(*argv, "-no_nonce") == 0) {
			no_nonce = 1;
		} else if (strcmp(*argv, "-cert") == 0) {
			cert = 1;
		} else if (strcmp(*argv, "-in") == 0) {
			if (argc-- < 1)
				goto usage;
			in = *++argv;
		} else if (strcmp(*argv, "-token_in") == 0) {
			token_in = 1;
		} else if (strcmp(*argv, "-out") == 0) {
			if (argc-- < 1)
				goto usage;
			out = *++argv;
		} else if (strcmp(*argv, "-token_out") == 0) {
			token_out = 1;
		} else if (strcmp(*argv, "-text") == 0) {
			text = 1;
		} else if (strcmp(*argv, "-reply") == 0) {
			if (mode != CMD_NONE)
				goto usage;
			mode = CMD_REPLY;
		} else if (strcmp(*argv, "-queryfile") == 0) {
			if (argc-- < 1)
				goto usage;
			queryfile = *++argv;
		} else if (strcmp(*argv, "-passin") == 0) {
			if (argc-- < 1)
				goto usage;
			passin = *++argv;
		} else if (strcmp(*argv, "-inkey") == 0) {
			if (argc-- < 1)
				goto usage;
			inkey = *++argv;
		} else if (strcmp(*argv, "-signer") == 0) {
			if (argc-- < 1)
				goto usage;
			signer = *++argv;
		} else if (strcmp(*argv, "-chain") == 0) {
			if (argc-- < 1)
				goto usage;
			chain = *++argv;
		} else if (strcmp(*argv, "-verify") == 0) {
			if (mode != CMD_NONE)
				goto usage;
			mode = CMD_VERIFY;
		} else if (strcmp(*argv, "-CApath") == 0) {
			if (argc-- < 1)
				goto usage;
			ca_path = *++argv;
		} else if (strcmp(*argv, "-CAfile") == 0) {
			if (argc-- < 1)
				goto usage;
			ca_file = *++argv;
		} else if (strcmp(*argv, "-untrusted") == 0) {
			if (argc-- < 1)
				goto usage;
			untrusted = *++argv;
		} else if (strcmp(*argv, "-engine") == 0) {
			if (argc-- < 1)
				goto usage;
			engine = *++argv;
		} else if ((md = EVP_get_digestbyname(*argv + 1)) != NULL) {
			/* empty. */
		} else
			goto usage;
	}

	/* Get the password if required. */
	if (mode == CMD_REPLY && passin &&
	    !app_passwd(bio_err, passin, NULL, &password, NULL)) {
		BIO_printf(bio_err, "Error getting password.\n");
		goto cleanup;
	}
	/*
	 * Check consistency of parameters and execute the appropriate
	 * function.
	 */
	switch (mode) {
	case CMD_NONE:
		goto usage;
	case CMD_QUERY:
		/*
		 * Data file and message imprint cannot be specified at the
		 * same time.
		 */
		ret = data != NULL && digest != NULL;
		if (ret)
			goto usage;
		/* Load the config file for possible policy OIDs. */
		conf = load_config_file(configfile);
		ret = !query_command(data, digest, md, policy, no_nonce, cert,
		    in, out, text);
		break;
	case CMD_REPLY:
		conf = load_config_file(configfile);
		if (in == NULL) {
			ret = !(queryfile != NULL && conf != NULL && !token_in);
			if (ret)
				goto usage;
		} else {
			/* 'in' and 'queryfile' are exclusive. */
			ret = !(queryfile == NULL);
			if (ret)
				goto usage;
		}

		ret = !reply_command(conf, section, engine, queryfile,
		    password, inkey, signer, chain, policy,
		    in, token_in, out, token_out, text);
		break;
	case CMD_VERIFY:
		ret = !(((queryfile && !data && !digest) ||
		    (!queryfile && data && !digest) ||
		    (!queryfile && !data && digest)) && in != NULL);
		if (ret)
			goto usage;

		ret = !verify_command(data, digest, queryfile, in, token_in,
		    ca_path, ca_file, untrusted);
	}

	goto cleanup;

usage:
	BIO_printf(bio_err, "usage:\n"
	    "ts -query [-config configfile] "
	    "[-data file_to_hash] [-digest digest_bytes]"
	    "[-md2|-md4|-md5|-sha|-sha1|-ripemd160] "
	    "[-policy object_id] [-no_nonce] [-cert] "
	    "[-in request.tsq] [-out request.tsq] [-text]\n");
	BIO_printf(bio_err, "or\n"
	    "ts -reply [-config configfile] [-section tsa_section] "
	    "[-queryfile request.tsq] [-passin password] "
	    "[-signer tsa_cert.pem] [-inkey private_key.pem] "
	    "[-chain certs_file.pem] [-policy object_id] "
	    "[-in response.tsr] [-token_in] "
	    "[-out response.tsr] [-token_out] [-text] [-engine id]\n");
	BIO_printf(bio_err, "or\n"
	    "ts -verify [-data file_to_hash] [-digest digest_bytes] "
	    "[-queryfile request.tsq] "
	    "-in response.tsr [-token_in] "
	    "-CApath ca_path -CAfile ca_file.pem "
	    "-untrusted cert_file.pem\n");

cleanup:
	/* Clean up. */
	NCONF_free(conf);
	free(password);
	OBJ_cleanup();

	return (ret);
}
Exemplo n.º 15
0
int x509_main(int argc, char **argv)
{
    ASN1_INTEGER *sno = NULL;
    ASN1_OBJECT *objtmp;
    BIO *out = NULL;
    CONF *extconf = NULL;
    EVP_PKEY *Upkey = NULL, *CApkey = NULL, *fkey = NULL;
    STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
    STACK_OF(OPENSSL_STRING) *sigopts = NULL;
    X509 *x = NULL, *xca = NULL;
    X509_REQ *req = NULL, *rq = NULL;
    X509_STORE *ctx = NULL;
    const EVP_MD *digest = NULL;
    char *CAkeyfile = NULL, *CAserial = NULL, *fkeyfile = NULL, *alias = NULL;
    char *checkhost = NULL, *checkemail = NULL, *checkip = NULL;
    char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL;
    char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL;
    char buf[256], *prog;
    int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0, pprint = 0;
    int C = 0, CAformat = FORMAT_PEM, CAkeyformat = FORMAT_PEM;
    int fingerprint = 0, reqfile = 0, need_rand = 0, checkend = 0;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyformat = FORMAT_PEM;
    int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0;
    int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0;
    int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0;
    int ret = 1, i, num = 0, badsig = 0, clrext = 0, nocert = 0;
    int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0;
    int checkoffset = 0, enddate = 0;
    unsigned long nmflag = 0, certflag = 0;
    OPTION_CHOICE o;
    ENGINE *e = NULL;
#ifndef OPENSSL_NO_MD5
    int subject_hash_old = 0, issuer_hash_old = 0;
#endif

    ctx = X509_STORE_new();
    if (ctx == NULL)
        goto end;
    X509_STORE_set_verify_cb(ctx, callb);

    prog = opt_init(argc, argv, x509_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(x509_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat))
                goto opthelp;
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &keyformat))
                goto opthelp;
            break;
        case OPT_CAFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &CAformat))
                goto opthelp;
            break;
        case OPT_CAKEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &CAkeyformat))
                goto opthelp;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_REQ:
            reqfile = need_rand = 1;
            break;

        case OPT_SIGOPT:
            if (!sigopts)
                sigopts = sk_OPENSSL_STRING_new_null();
            if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
                goto opthelp;
            break;
#ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
        case OPT_FORCE_VERSION:
            force_version = atoi(opt_arg()) - 1;
            break;
#endif
        case OPT_DAYS:
            days = atoi(opt_arg());
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_EXTFILE:
            extfile = opt_arg();
            break;
        case OPT_EXTENSIONS:
            extsect = opt_arg();
            break;
        case OPT_SIGNKEY:
            keyfile = opt_arg();
            sign_flag = ++num;
            need_rand = 1;
            break;
        case OPT_CA:
            CAfile = opt_arg();
            CA_flag = ++num;
            need_rand = 1;
            break;
        case OPT_CAKEY:
            CAkeyfile = opt_arg();
            break;
        case OPT_CASERIAL:
            CAserial = opt_arg();
            break;
        case OPT_SET_SERIAL:
            if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL)
                goto opthelp;
            break;
        case OPT_FORCE_PUBKEY:
            fkeyfile = opt_arg();
            break;
        case OPT_ADDTRUST:
            if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
                BIO_printf(bio_err,
                           "%s: Invalid trust object value %s\n",
                           prog, opt_arg());
                goto opthelp;
            }
            if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL)
                goto end;
            sk_ASN1_OBJECT_push(trust, objtmp);
            trustout = 1;
            break;
        case OPT_ADDREJECT:
            if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) {
                BIO_printf(bio_err,
                           "%s: Invalid reject object value %s\n",
                           prog, opt_arg());
                goto opthelp;
            }
            if (reject == NULL
                && (reject = sk_ASN1_OBJECT_new_null()) == NULL)
                goto end;
            sk_ASN1_OBJECT_push(reject, objtmp);
            trustout = 1;
            break;
        case OPT_SETALIAS:
            alias = opt_arg();
            trustout = 1;
            break;
        case OPT_CERTOPT:
            if (!set_cert_ex(&certflag, opt_arg()))
                goto opthelp;
            break;
        case OPT_NAMEOPT:
            if (!set_name_ex(&nmflag, opt_arg()))
                goto opthelp;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_C:
            C = ++num;
            break;
        case OPT_EMAIL:
            email = ++num;
            break;
        case OPT_OCSP_URI:
            ocsp_uri = ++num;
            break;
        case OPT_SERIAL:
            serial = ++num;
            break;
        case OPT_NEXT_SERIAL:
            next_serial = ++num;
            break;
        case OPT_MODULUS:
            modulus = ++num;
            break;
        case OPT_PUBKEY:
            pubkey = ++num;
            break;
        case OPT_X509TOREQ:
            x509req = ++num;
            break;
        case OPT_TEXT:
            text = ++num;
            break;
        case OPT_SUBJECT:
            subject = ++num;
            break;
        case OPT_ISSUER:
            issuer = ++num;
            break;
        case OPT_FINGERPRINT:
            fingerprint = ++num;
            break;
        case OPT_HASH:
            subject_hash = ++num;
            break;
        case OPT_ISSUER_HASH:
            issuer_hash = ++num;
            break;
        case OPT_PURPOSE:
            pprint = ++num;
            break;
        case OPT_STARTDATE:
            startdate = ++num;
            break;
        case OPT_ENDDATE:
            enddate = ++num;
            break;
        case OPT_NOOUT:
            noout = ++num;
            break;
        case OPT_NOCERT:
            nocert = 1;
            break;
        case OPT_TRUSTOUT:
            trustout = 1;
            break;
        case OPT_CLRTRUST:
            clrtrust = ++num;
            break;
        case OPT_CLRREJECT:
            clrreject = ++num;
            break;
        case OPT_ALIAS:
            aliasout = ++num;
            break;
        case OPT_CACREATESERIAL:
            CA_createserial = ++num;
            break;
        case OPT_CLREXT:
            clrext = 1;
            break;
        case OPT_OCSPID:
            ocspid = ++num;
            break;
        case OPT_BADSIG:
            badsig = 1;
            break;
#ifndef OPENSSL_NO_MD5
        case OPT_SUBJECT_HASH_OLD:
            subject_hash_old = ++num;
            break;
        case OPT_ISSUER_HASH_OLD:
            issuer_hash_old = ++num;
            break;
#endif
        case OPT_DATES:
            startdate = ++num;
            enddate = ++num;
            break;
        case OPT_CHECKEND:
            checkoffset = atoi(opt_arg());
            checkend = 1;
            break;
        case OPT_CHECKHOST:
            checkhost = opt_arg();
            break;
        case OPT_CHECKEMAIL:
            checkemail = opt_arg();
            break;
        case OPT_CHECKIP:
            checkip = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_unknown(), &digest))
                goto opthelp;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();
    if (argc != 0) {
        BIO_printf(bio_err, "%s: Unknown parameter %s\n", prog, argv[0]);
        goto opthelp;
    }

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

    if (need_rand)
        app_RAND_load_file(NULL, 0);

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

    if (!X509_STORE_set_default_paths(ctx)) {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (fkeyfile) {
        fkey = load_pubkey(fkeyfile, keyformat, 0, NULL, e, "Forced key");
        if (fkey == NULL)
            goto end;
    }

    if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) {
        CAkeyfile = CAfile;
    } else if ((CA_flag) && (CAkeyfile == NULL)) {
        BIO_printf(bio_err,
                   "need to specify a CAkey if using the CA command\n");
        goto end;
    }

    if (extfile) {
        long errorline = -1;
        X509V3_CTX ctx2;
        extconf = NCONF_new(NULL);
        if (!NCONF_load(extconf, extfile, &errorline)) {
            if (errorline <= 0)
                BIO_printf(bio_err,
                           "error loading the config file '%s'\n", extfile);
            else
                BIO_printf(bio_err,
                           "error on line %ld of config file '%s'\n",
                           errorline, extfile);
            goto end;
        }
        if (!extsect) {
            extsect = NCONF_get_string(extconf, "default", "extensions");
            if (!extsect) {
                ERR_clear_error();
                extsect = "default";
            }
        }
        X509V3_set_ctx_test(&ctx2);
        X509V3_set_nconf(&ctx2, extconf);
        if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
            BIO_printf(bio_err,
                       "Error Loading extension section %s\n", extsect);
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (reqfile) {
        EVP_PKEY *pkey;
        BIO *in;

        if (!sign_flag && !CA_flag) {
            BIO_printf(bio_err, "We need a private key to sign with\n");
            goto end;
        }
        in = bio_open_default(infile, "r");
        if (in == NULL)
            goto end;
        req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
        BIO_free(in);

        if (req == NULL) {
            ERR_print_errors(bio_err);
            goto end;
        }

        if ((req->req_info == NULL) ||
            (req->req_info->pubkey == NULL) ||
            (req->req_info->pubkey->public_key == NULL) ||
            (req->req_info->pubkey->public_key->data == NULL)) {
            BIO_printf(bio_err,
                       "The certificate request appears to corrupted\n");
            BIO_printf(bio_err, "It does not contain a public key\n");
            goto end;
        }
        if ((pkey = X509_REQ_get_pubkey(req)) == NULL) {
            BIO_printf(bio_err, "error unpacking public key\n");
            goto end;
        }
        i = X509_REQ_verify(req, pkey);
        EVP_PKEY_free(pkey);
        if (i < 0) {
            BIO_printf(bio_err, "Signature verification error\n");
            ERR_print_errors(bio_err);
            goto end;
        }
        if (i == 0) {
            BIO_printf(bio_err,
                       "Signature did not match the certificate request\n");
            goto end;
        } else
            BIO_printf(bio_err, "Signature ok\n");

        print_name(bio_err, "subject=", X509_REQ_get_subject_name(req),
                   nmflag);

        if ((x = X509_new()) == NULL)
            goto end;

        if (sno == NULL) {
            sno = ASN1_INTEGER_new();
            if (!sno || !rand_serial(NULL, sno))
                goto end;
            if (!X509_set_serialNumber(x, sno))
                goto end;
            ASN1_INTEGER_free(sno);
            sno = NULL;
        } else if (!X509_set_serialNumber(x, sno))
            goto end;

        if (!X509_set_issuer_name(x, req->req_info->subject))
            goto end;
        if (!X509_set_subject_name(x, req->req_info->subject))
            goto end;

        X509_gmtime_adj(X509_get_notBefore(x), 0);
        X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL);
        if (fkey)
            X509_set_pubkey(x, fkey);
        else {
            pkey = X509_REQ_get_pubkey(req);
            X509_set_pubkey(x, pkey);
            EVP_PKEY_free(pkey);
        }
    } else
        x = load_cert(infile, informat, NULL, e, "Certificate");

    if (x == NULL)
        goto end;
    if (CA_flag) {
        xca = load_cert(CAfile, CAformat, NULL, e, "CA Certificate");
        if (xca == NULL)
            goto end;
    }

    if (!noout || text || next_serial) {
        OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3");

    }

    if (alias)
        X509_alias_set1(x, (unsigned char *)alias, -1);

    if (clrtrust)
        X509_trust_clear(x);
    if (clrreject)
        X509_reject_clear(x);

    if (trust) {
        for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
            objtmp = sk_ASN1_OBJECT_value(trust, i);
            X509_add1_trust_object(x, objtmp);
        }
    }

    if (reject) {
        for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
            objtmp = sk_ASN1_OBJECT_value(reject, i);
            X509_add1_reject_object(x, objtmp);
        }
    }

    if (num) {
        for (i = 1; i <= num; i++) {
            if (issuer == i) {
                print_name(out, "issuer= ", X509_get_issuer_name(x), nmflag);
            } else if (subject == i) {
                print_name(out, "subject= ",
                           X509_get_subject_name(x), nmflag);
            } else if (serial == i) {
                BIO_printf(out, "serial=");
                i2a_ASN1_INTEGER(out, X509_get_serialNumber(x));
                BIO_printf(out, "\n");
            } else if (next_serial == i) {
                BIGNUM *bnser;
                ASN1_INTEGER *ser;
                ser = X509_get_serialNumber(x);
                bnser = ASN1_INTEGER_to_BN(ser, NULL);
                if (!bnser)
                    goto end;
                if (!BN_add_word(bnser, 1))
                    goto end;
                ser = BN_to_ASN1_INTEGER(bnser, NULL);
                if (!ser)
                    goto end;
                BN_free(bnser);
                i2a_ASN1_INTEGER(out, ser);
                ASN1_INTEGER_free(ser);
                BIO_puts(out, "\n");
            } else if ((email == i) || (ocsp_uri == i)) {
                int j;
                STACK_OF(OPENSSL_STRING) *emlst;
                if (email == i)
                    emlst = X509_get1_email(x);
                else
                    emlst = X509_get1_ocsp(x);
                for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
                    BIO_printf(out, "%s\n",
                               sk_OPENSSL_STRING_value(emlst, j));
                X509_email_free(emlst);
            } else if (aliasout == i) {
                unsigned char *alstr;
                alstr = X509_alias_get0(x, NULL);
                if (alstr)
                    BIO_printf(out, "%s\n", alstr);
                else
                    BIO_puts(out, "<No Alias>\n");
            } else if (subject_hash == i) {
                BIO_printf(out, "%08lx\n", X509_subject_name_hash(x));
            }
#ifndef OPENSSL_NO_MD5
            else if (subject_hash_old == i) {
                BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x));
            }
#endif
            else if (issuer_hash == i) {
                BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x));
            }
#ifndef OPENSSL_NO_MD5
            else if (issuer_hash_old == i) {
                BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x));
            }
#endif
            else if (pprint == i) {
                X509_PURPOSE *ptmp;
                int j;
                BIO_printf(out, "Certificate purposes:\n");
                for (j = 0; j < X509_PURPOSE_get_count(); j++) {
                    ptmp = X509_PURPOSE_get0(j);
                    purpose_print(out, x, ptmp);
                }
            } else if (modulus == i) {
                EVP_PKEY *pkey;

                pkey = X509_get_pubkey(x);
                if (pkey == NULL) {
                    BIO_printf(bio_err, "Modulus=unavailable\n");
                    ERR_print_errors(bio_err);
                    goto end;
                }
                BIO_printf(out, "Modulus=");
#ifndef OPENSSL_NO_RSA
                if (pkey->type == EVP_PKEY_RSA)
                    BN_print(out, pkey->pkey.rsa->n);
                else
#endif
#ifndef OPENSSL_NO_DSA
                if (pkey->type == EVP_PKEY_DSA)
                    BN_print(out, pkey->pkey.dsa->pub_key);
                else
#endif
                    BIO_printf(out, "Wrong Algorithm type");
                BIO_printf(out, "\n");
                EVP_PKEY_free(pkey);
            } else if (pubkey == i) {
                EVP_PKEY *pkey;

                pkey = X509_get_pubkey(x);
                if (pkey == NULL) {
                    BIO_printf(bio_err, "Error getting public key\n");
                    ERR_print_errors(bio_err);
                    goto end;
                }
                PEM_write_bio_PUBKEY(out, pkey);
                EVP_PKEY_free(pkey);
            } else if (C == i) {
                unsigned char *d;
                char *m;
                int len;

                X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof buf);
                BIO_printf(out, "/*\n"
                                " * Subject: %s\n", buf);

                m = X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof buf);
                BIO_printf(out, " * Issuer:  %s\n"
                                " */\n", buf);

                len = i2d_X509(x, NULL);
                m = app_malloc(len, "x509 name buffer");
                d = (unsigned char *)m;
                len = i2d_X509_NAME(X509_get_subject_name(x), &d);
                print_array(out, "the_subject_name", len, (unsigned char *)m);
                d = (unsigned char *)m;
                len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d);
                print_array(out, "the_public_key", len, (unsigned char *)m);
                d = (unsigned char *)m;
                len = i2d_X509(x, &d);
                print_array(out, "the_certificate", len, (unsigned char *)m);
                OPENSSL_free(m);
            } else if (text == i) {
                X509_print_ex(out, x, nmflag, certflag);
            } else if (startdate == i) {
                BIO_puts(out, "notBefore=");
                ASN1_TIME_print(out, X509_get_notBefore(x));
                BIO_puts(out, "\n");
            } else if (enddate == i) {
                BIO_puts(out, "notAfter=");
                ASN1_TIME_print(out, X509_get_notAfter(x));
                BIO_puts(out, "\n");
            } else if (fingerprint == i) {
                int j;
                unsigned int n;
                unsigned char md[EVP_MAX_MD_SIZE];
                const EVP_MD *fdig = digest;

                if (!fdig)
                    fdig = EVP_sha1();

                if (!X509_digest(x, fdig, md, &n)) {
                    BIO_printf(bio_err, "out of memory\n");
                    goto end;
                }
                BIO_printf(out, "%s Fingerprint=",
                           OBJ_nid2sn(EVP_MD_type(fdig)));
                for (j = 0; j < (int)n; j++) {
                    BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n)
                               ? '\n' : ':');
                }
            }

            /* should be in the library */
            else if ((sign_flag == i) && (x509req == 0)) {
                BIO_printf(bio_err, "Getting Private key\n");
                if (Upkey == NULL) {
                    Upkey = load_key(keyfile, keyformat, 0,
                                     passin, e, "Private key");
                    if (Upkey == NULL)
                        goto end;
                }

                assert(need_rand);
                if (!sign(x, Upkey, days, clrext, digest, extconf, extsect))
                    goto end;
            } else if (CA_flag == i) {
                BIO_printf(bio_err, "Getting CA Private Key\n");
                if (CAkeyfile != NULL) {
                    CApkey = load_key(CAkeyfile, CAkeyformat,
                                      0, passin, e, "CA Private Key");
                    if (CApkey == NULL)
                        goto end;
                }

                assert(need_rand);
                if (!x509_certify(ctx, CAfile, digest, x, xca,
                                  CApkey, sigopts,
                                  CAserial, CA_createserial, days, clrext,
                                  extconf, extsect, sno, reqfile))
                    goto end;
            } else if (x509req == i) {
                EVP_PKEY *pk;

                BIO_printf(bio_err, "Getting request Private Key\n");
                if (keyfile == NULL) {
                    BIO_printf(bio_err, "no request key file specified\n");
                    goto end;
                } else {
                    pk = load_key(keyfile, keyformat, 0,
                                  passin, e, "request key");
                    if (pk == NULL)
                        goto end;
                }

                BIO_printf(bio_err, "Generating certificate request\n");

                rq = X509_to_X509_REQ(x, pk, digest);
                EVP_PKEY_free(pk);
                if (rq == NULL) {
                    ERR_print_errors(bio_err);
                    goto end;
                }
                if (!noout) {
                    X509_REQ_print(out, rq);
                    PEM_write_bio_X509_REQ(out, rq);
                }
                noout = 1;
            } else if (ocspid == i) {
                X509_ocspid_print(out, x);
            }
        }
    }

    if (checkend) {
        time_t tcheck = time(NULL) + checkoffset;

        if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0) {
            BIO_printf(out, "Certificate will expire\n");
            ret = 1;
        } else {
            BIO_printf(out, "Certificate will not expire\n");
            ret = 0;
        }
        goto end;
    }

    print_cert_checks(out, x, checkhost, checkemail, checkip);

    if (noout || nocert) {
        ret = 0;
        goto end;
    }

    if (badsig)
        x->signature->data[x->signature->length - 1] ^= 0x1;

    if (outformat == FORMAT_ASN1)
        i = i2d_X509_bio(out, x);
    else if (outformat == FORMAT_PEM) {
        if (trustout)
            i = PEM_write_bio_X509_AUX(out, x);
        else
            i = PEM_write_bio_X509(out, x);
    } else if (outformat == FORMAT_NETSCAPE) {
        NETSCAPE_X509 nx;
        ASN1_OCTET_STRING hdr;

        hdr.data = (unsigned char *)NETSCAPE_CERT_HDR;
        hdr.length = strlen(NETSCAPE_CERT_HDR);
        nx.header = &hdr;
        nx.cert = x;

        i = ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509), out, &nx);
    } else {
        BIO_printf(bio_err, "bad output format specified for outfile\n");
        goto end;
    }
    if (!i) {
        BIO_printf(bio_err, "unable to write certificate\n");
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;
 end:
    if (need_rand)
        app_RAND_write_file(NULL);
    OBJ_cleanup();
    NCONF_free(extconf);
    BIO_free_all(out);
    X509_STORE_free(ctx);
    X509_REQ_free(req);
    X509_free(x);
    X509_free(xca);
    EVP_PKEY_free(Upkey);
    EVP_PKEY_free(CApkey);
    EVP_PKEY_free(fkey);
    sk_OPENSSL_STRING_free(sigopts);
    X509_REQ_free(rq);
    ASN1_INTEGER_free(sno);
    sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
    sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
    OPENSSL_free(passin);
    return (ret);
}
Exemplo n.º 16
0
int spkac_main(int argc, char **argv)
{
    BIO *out = NULL;
    CONF *conf = NULL;
    ENGINE *e = NULL;
    EVP_PKEY *pkey = NULL;
    NETSCAPE_SPKI *spki = NULL;
    char *challenge = NULL, *keyfile = NULL;
    char *infile = NULL, *outfile = NULL, *passinarg = NULL, *passin = NULL;
    char *spkstr = NULL, *prog;
    const char *spkac = "SPKAC", *spksect = "default";
    int i, ret = 1, verify = 0, noout = 0, pubkey = 0;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, spkac_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(spkac_options);
            ret = 0;
            goto end;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_NOOUT:
            noout = 1;
            break;
        case OPT_PUBKEY:
            pubkey = 1;
            break;
        case OPT_VERIFY:
            verify = 1;
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_KEY:
            keyfile = opt_arg();
            break;
        case OPT_CHALLENGE:
            challenge = opt_arg();
            break;
        case OPT_SPKAC:
            spkac = opt_arg();
            break;
        case OPT_SPKSECT:
            spksect = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

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

    if (keyfile) {
        pkey = load_key(strcmp(keyfile, "-") ? keyfile : NULL,
                        FORMAT_PEM, 1, passin, e, "private key");
        if (!pkey) {
            goto end;
        }
        spki = NETSCAPE_SPKI_new();
        if (challenge)
            ASN1_STRING_set(spki->spkac->challenge,
                            challenge, (int)strlen(challenge));
        NETSCAPE_SPKI_set_pubkey(spki, pkey);
        NETSCAPE_SPKI_sign(spki, pkey, EVP_md5());
        spkstr = NETSCAPE_SPKI_b64_encode(spki);

        out = bio_open_default(outfile, 'w', FORMAT_TEXT);
        if (out == NULL)
            goto end;
        BIO_printf(out, "SPKAC=%s\n", spkstr);
        OPENSSL_free(spkstr);
        ret = 0;
        goto end;
    }

    if ((conf = app_load_config(infile)) == NULL)
        goto end;

    spkstr = NCONF_get_string(conf, spksect, spkac);

    if (spkstr == NULL) {
        BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac);
        ERR_print_errors(bio_err);
        goto end;
    }

    spki = NETSCAPE_SPKI_b64_decode(spkstr, -1);

    if (!spki) {
        BIO_printf(bio_err, "Error loading SPKAC\n");
        ERR_print_errors(bio_err);
        goto end;
    }

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

    if (!noout)
        NETSCAPE_SPKI_print(out, spki);
    pkey = NETSCAPE_SPKI_get_pubkey(spki);
    if (verify) {
        i = NETSCAPE_SPKI_verify(spki, pkey);
        if (i > 0)
            BIO_printf(bio_err, "Signature OK\n");
        else {
            BIO_printf(bio_err, "Signature Failure\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }
    if (pubkey)
        PEM_write_bio_PUBKEY(out, pkey);

    ret = 0;

 end:
    NCONF_free(conf);
    NETSCAPE_SPKI_free(spki);
    BIO_free_all(out);
    EVP_PKEY_free(pkey);
    OPENSSL_free(passin);
    return (ret);
}
Exemplo n.º 17
0
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	int i,badops=0, ret = 1;
	BIO *in = NULL,*out = NULL;
	int verify=0,noout=0,pubkey=0;
	char *infile = NULL,*outfile = NULL,*prog;
	char *passargin = NULL, *passin = NULL;
	const char *spkac = "SPKAC", *spksect = "default";
	char *spkstr = NULL;
	char *challenge = NULL, *keyfile = NULL;
	CONF *conf = NULL;
	NETSCAPE_SPKI *spki = NULL;
	EVP_PKEY *pkey = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif

	apps_startup();

	if (!bio_err) bio_err = BIO_new_fp(OPENSSL_TYPE__FILE_STDERR, BIO_NOCLOSE);

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

	prog=argv[0];
	argc--;
	argv++;
	while (argc >= 1)
		{
		if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-key") == 0)
			{
			if (--argc < 1) goto bad;
			keyfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-challenge") == 0)
			{
			if (--argc < 1) goto bad;
			challenge= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-spkac") == 0)
			{
			if (--argc < 1) goto bad;
			spkac= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-spksect") == 0)
			{
			if (--argc < 1) goto bad;
			spksect= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0)
			noout=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-pubkey") == 0)
			pubkey=1;
		else if (TINYCLR_SSL_STRCMP(*argv,"-verify") == 0)
			verify=1;
		else badops = 1;
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		BIO_printf(bio_err,"%s [options]\n",prog);
		BIO_printf(bio_err,"where options are\n");
		BIO_printf(bio_err," -in arg        input file\n");
		BIO_printf(bio_err," -out arg       output file\n");
		BIO_printf(bio_err," -key arg       create SPKAC using private key\n");
		BIO_printf(bio_err," -passin arg    input file pass phrase source\n");
		BIO_printf(bio_err," -challenge arg challenge string\n");
		BIO_printf(bio_err," -spkac arg     alternative SPKAC name\n");
		BIO_printf(bio_err," -noout         don't print SPKAC\n");
		BIO_printf(bio_err," -pubkey        output public key\n");
		BIO_printf(bio_err," -verify        verify SPKAC signature\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e      use engine e, possibly a hardware device.\n");
#endif
		goto end;
		}

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

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

	if(keyfile) {
		pkey = load_key(bio_err,
				TINYCLR_SSL_STRCMP(keyfile, "-") ? keyfile : NULL,
				FORMAT_PEM, 1, passin, e, "private key");
		if(!pkey) {
			goto end;
		}
		spki = NETSCAPE_SPKI_new();
		if(challenge) ASN1_STRING_set(spki->spkac->challenge,
						 challenge, (int)TINYCLR_SSL_STRLEN(challenge));
		NETSCAPE_SPKI_set_pubkey(spki, pkey);
		NETSCAPE_SPKI_sign(spki, pkey, EVP_md5());
		spkstr = NETSCAPE_SPKI_b64_encode(spki);

		if (outfile) out = BIO_new_file(outfile, "w");
		else {
			out = BIO_new_fp(OPENSSL_TYPE__FILE_STDOUT, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
			{
			    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
			    out = BIO_push(tmpbio, out);
			}
#endif
		}

		if(!out) {
			BIO_printf(bio_err, "Error opening output file\n");
			ERR_print_errors(bio_err);
			goto end;
		}
		BIO_printf(out, "SPKAC=%s\n", spkstr);
		OPENSSL_free(spkstr);
		ret = 0;
		goto end;
	}

	

	if (infile) in = BIO_new_file(infile, "r");
	else in = BIO_new_fp(OPENSSL_TYPE__FILE_STDIN, BIO_NOCLOSE);

	if(!in) {
		BIO_printf(bio_err, "Error opening input file\n");
		ERR_print_errors(bio_err);
		goto end;
	}

	conf = NCONF_new(NULL);
	i = NCONF_load_bio(conf, in, NULL);

	if(!i) {
		BIO_printf(bio_err, "Error parsing config file\n");
		ERR_print_errors(bio_err);
		goto end;
	}

	spkstr = NCONF_get_string(conf, spksect, spkac);
		
	if(!spkstr) {
		BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac);
		ERR_print_errors(bio_err);
		goto end;
	}

	spki = NETSCAPE_SPKI_b64_decode(spkstr, -1);
	
	if(!spki) {
		BIO_printf(bio_err, "Error loading SPKAC\n");
		ERR_print_errors(bio_err);
		goto end;
	}

	if (outfile) out = BIO_new_file(outfile, "w");
	else {
		out = BIO_new_fp(OPENSSL_TYPE__FILE_STDOUT, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
		{
		    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		    out = BIO_push(tmpbio, out);
		}
#endif
	}

	if(!out) {
		BIO_printf(bio_err, "Error opening output file\n");
		ERR_print_errors(bio_err);
		goto end;
	}

	if(!noout) NETSCAPE_SPKI_print(out, spki);
	pkey = NETSCAPE_SPKI_get_pubkey(spki);
	if(verify) {
		i = NETSCAPE_SPKI_verify(spki, pkey);
		if (i > 0) BIO_printf(bio_err, "Signature OK\n");
		else {
			BIO_printf(bio_err, "Signature Failure\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if(pubkey) PEM_write_bio_PUBKEY(out, pkey);

	ret = 0;

end:
	NCONF_free(conf);
	NETSCAPE_SPKI_free(spki);
	BIO_free(in);
	BIO_free_all(out);
	EVP_PKEY_free(pkey);
	if(passin) OPENSSL_free(passin);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Exemplo n.º 18
0
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	int ret=1;
	X509_REQ *req=NULL;
	X509 *x=NULL,*xca=NULL;
	ASN1_OBJECT *objtmp;
	STACK_OF(OPENSSL_STRING) *sigopts = NULL;
	EVP_PKEY *Upkey=NULL,*CApkey=NULL;
	ASN1_INTEGER *sno = NULL;
	int i,num,badops=0;
	BIO *out=NULL;
	BIO *STDout=NULL;
	STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
	int informat,outformat,keyformat,CAformat,CAkeyformat;
	char *infile=NULL,*outfile=NULL,*keyfile=NULL,*CAfile=NULL;
	char *CAkeyfile=NULL,*CAserial=NULL;
	char *alias=NULL;
	int text=0,serial=0,subject=0,issuer=0,startdate=0,enddate=0;
	int next_serial=0;
	int subject_hash=0,issuer_hash=0,ocspid=0;
#ifndef OPENSSL_NO_MD5
	int subject_hash_old=0,issuer_hash_old=0;
#endif
	int noout=0,sign_flag=0,CA_flag=0,CA_createserial=0,email=0;
	int ocsp_uri=0;
	int trustout=0,clrtrust=0,clrreject=0,aliasout=0,clrext=0;
	int C=0;
	int x509req=0,days=DEF_DAYS,modulus=0,pubkey=0;
	int pprint = 0;
	const char **pp;
	X509_STORE *ctx=NULL;
	X509_REQ *rq=NULL;
	int fingerprint=0;
	char buf[256];
	const EVP_MD *md_alg,*digest=NULL;
	CONF *extconf = NULL;
	char *extsect = NULL, *extfile = NULL, *passin = NULL, *passargin = NULL;
	int need_rand = 0;
	int checkend=0,checkoffset=0;
	unsigned long nmflag = 0, certflag = 0;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif

	reqfile=0;

	apps_startup();

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

	if (!load_config(bio_err, NULL))
		goto end;
	STDout=BIO_new_fp(stdout,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
	{
	BIO *tmpbio = BIO_new(BIO_f_linebuffer());
	STDout = BIO_push(tmpbio, STDout);
	}
#endif

	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;
	keyformat=FORMAT_PEM;
	CAformat=FORMAT_PEM;
	CAkeyformat=FORMAT_PEM;

	ctx=X509_STORE_new();
	if (ctx == NULL) goto end;
	X509_STORE_set_verify_cb(ctx,callb);

	argc--;
	argv++;
	num=0;
	while (argc >= 1)
		{
		if 	(strcmp(*argv,"-inform") == 0)
			{
			if (--argc < 1) goto bad;
			informat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-outform") == 0)
			{
			if (--argc < 1) goto bad;
			outformat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-keyform") == 0)
			{
			if (--argc < 1) goto bad;
			keyformat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-req") == 0)
			{
			reqfile=1;
			need_rand = 1;
			}
		else if (strcmp(*argv,"-CAform") == 0)
			{
			if (--argc < 1) goto bad;
			CAformat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-CAkeyform") == 0)
			{
			if (--argc < 1) goto bad;
			CAkeyformat=str2fmt(*(++argv));
			}
		else if (strcmp(*argv,"-sigopt") == 0)
			{
			if (--argc < 1)
				goto bad;
			if (!sigopts)
				sigopts = sk_OPENSSL_STRING_new_null();
			if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
				goto bad;
			}
		else if (strcmp(*argv,"-days") == 0)
			{
			if (--argc < 1) goto bad;
			days=atoi(*(++argv));
			if (days == 0)
				{
				BIO_printf(STDout,"bad number of days\n");
				goto bad;
				}
			}
		else if (strcmp(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (strcmp(*argv,"-extfile") == 0)
			{
			if (--argc < 1) goto bad;
			extfile= *(++argv);
			}
		else if (strcmp(*argv,"-extensions") == 0)
			{
			if (--argc < 1) goto bad;
			extsect= *(++argv);
			}
		else if (strcmp(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (strcmp(*argv,"-signkey") == 0)
			{
			if (--argc < 1) goto bad;
			keyfile= *(++argv);
			sign_flag= ++num;
			need_rand = 1;
			}
		else if (strcmp(*argv,"-CA") == 0)
			{
			if (--argc < 1) goto bad;
			CAfile= *(++argv);
			CA_flag= ++num;
			need_rand = 1;
			}
		else if (strcmp(*argv,"-CAkey") == 0)
			{
			if (--argc < 1) goto bad;
			CAkeyfile= *(++argv);
			}
		else if (strcmp(*argv,"-CAserial") == 0)
			{
			if (--argc < 1) goto bad;
			CAserial= *(++argv);
			}
		else if (strcmp(*argv,"-set_serial") == 0)
			{
			if (--argc < 1) goto bad;
			if (!(sno = s2i_ASN1_INTEGER(NULL, *(++argv))))
				goto bad;
			}
		else if (strcmp(*argv,"-addtrust") == 0)
			{
			if (--argc < 1) goto bad;
			if (!(objtmp = OBJ_txt2obj(*(++argv), 0)))
				{
				BIO_printf(bio_err,
					"Invalid trust object value %s\n", *argv);
				goto bad;
				}
			if (!trust) trust = sk_ASN1_OBJECT_new_null();
			sk_ASN1_OBJECT_push(trust, objtmp);
			trustout = 1;
			}
		else if (strcmp(*argv,"-addreject") == 0)
			{
			if (--argc < 1) goto bad;
			if (!(objtmp = OBJ_txt2obj(*(++argv), 0)))
				{
				BIO_printf(bio_err,
					"Invalid reject object value %s\n", *argv);
				goto bad;
				}
			if (!reject) reject = sk_ASN1_OBJECT_new_null();
			sk_ASN1_OBJECT_push(reject, objtmp);
			trustout = 1;
			}
		else if (strcmp(*argv,"-setalias") == 0)
			{
			if (--argc < 1) goto bad;
			alias= *(++argv);
			trustout = 1;
			}
		else if (strcmp(*argv,"-certopt") == 0)
			{
			if (--argc < 1) goto bad;
			if (!set_cert_ex(&certflag, *(++argv))) goto bad;
			}
		else if (strcmp(*argv,"-nameopt") == 0)
			{
			if (--argc < 1) goto bad;
			if (!set_name_ex(&nmflag, *(++argv))) goto bad;
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if (strcmp(*argv,"-C") == 0)
			C= ++num;
		else if (strcmp(*argv,"-email") == 0)
			email= ++num;
		else if (strcmp(*argv,"-ocsp_uri") == 0)
			ocsp_uri= ++num;
		else if (strcmp(*argv,"-serial") == 0)
			serial= ++num;
		else if (strcmp(*argv,"-next_serial") == 0)
			next_serial= ++num;
		else if (strcmp(*argv,"-modulus") == 0)
			modulus= ++num;
		else if (strcmp(*argv,"-pubkey") == 0)
			pubkey= ++num;
		else if (strcmp(*argv,"-x509toreq") == 0)
			x509req= ++num;
		else if (strcmp(*argv,"-text") == 0)
			text= ++num;
		else if (strcmp(*argv,"-hash") == 0
			|| strcmp(*argv,"-subject_hash") == 0)
			subject_hash= ++num;
#ifndef OPENSSL_NO_MD5
		else if (strcmp(*argv,"-subject_hash_old") == 0)
			subject_hash_old= ++num;
#endif
		else if (strcmp(*argv,"-issuer_hash") == 0)
			issuer_hash= ++num;
#ifndef OPENSSL_NO_MD5
		else if (strcmp(*argv,"-issuer_hash_old") == 0)
			issuer_hash_old= ++num;
#endif
		else if (strcmp(*argv,"-subject") == 0)
			subject= ++num;
		else if (strcmp(*argv,"-issuer") == 0)
			issuer= ++num;
		else if (strcmp(*argv,"-fingerprint") == 0)
			fingerprint= ++num;
		else if (strcmp(*argv,"-dates") == 0)
			{
			startdate= ++num;
			enddate= ++num;
			}
		else if (strcmp(*argv,"-purpose") == 0)
			pprint= ++num;
		else if (strcmp(*argv,"-startdate") == 0)
			startdate= ++num;
		else if (strcmp(*argv,"-enddate") == 0)
			enddate= ++num;
		else if (strcmp(*argv,"-checkend") == 0)
			{
			if (--argc < 1) goto bad;
			checkoffset=atoi(*(++argv));
			checkend=1;
			}
		else if (strcmp(*argv,"-noout") == 0)
			noout= ++num;
		else if (strcmp(*argv,"-trustout") == 0)
			trustout= 1;
		else if (strcmp(*argv,"-clrtrust") == 0)
			clrtrust= ++num;
		else if (strcmp(*argv,"-clrreject") == 0)
			clrreject= ++num;
		else if (strcmp(*argv,"-alias") == 0)
			aliasout= ++num;
		else if (strcmp(*argv,"-CAcreateserial") == 0)
			CA_createserial= ++num;
		else if (strcmp(*argv,"-clrext") == 0)
			clrext = 1;
#if 1 /* stay backwards-compatible with 0.9.5; this should go away soon */
		else if (strcmp(*argv,"-crlext") == 0)
			{
			BIO_printf(bio_err,"use -clrext instead of -crlext\n");
			clrext = 1;
			}
#endif
		else if (strcmp(*argv,"-ocspid") == 0)
			ocspid= ++num;
		else if ((md_alg=EVP_get_digestbyname(*argv + 1)))
			{
			/* ok */
			digest=md_alg;
			}
		else
			{
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		for (pp=x509_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);
		goto end;
		}

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

	if (need_rand)
		app_RAND_load_file(NULL, bio_err, 0);

	ERR_load_crypto_strings();

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

	if (!X509_STORE_set_default_paths(ctx))
		{
		ERR_print_errors(bio_err);
		goto end;
		}

	if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM))
		{ CAkeyfile=CAfile; }
	else if ((CA_flag) && (CAkeyfile == NULL))
		{
		BIO_printf(bio_err,"need to specify a CAkey if using the CA command\n");
		goto end;
		}

	if (extfile)
		{
		long errorline = -1;
		X509V3_CTX ctx2;
		extconf = NCONF_new(NULL);
		if (!NCONF_load(extconf, extfile,&errorline))
			{
			if (errorline <= 0)
				BIO_printf(bio_err,
					"error loading the config file '%s'\n",
								extfile);
                	else
                        	BIO_printf(bio_err,
				       "error on line %ld of config file '%s'\n"
							,errorline,extfile);
			goto end;
			}
		if (!extsect)
			{
			extsect = NCONF_get_string(extconf, "default", "extensions");
			if (!extsect)
				{
				ERR_clear_error();
				extsect = "default";
				}
			}
		X509V3_set_ctx_test(&ctx2);
		X509V3_set_nconf(&ctx2, extconf);
		if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL))
			{
			BIO_printf(bio_err,
				"Error Loading extension section %s\n",
								 extsect);
			ERR_print_errors(bio_err);
			goto end;
			}
		}


	if (reqfile)
		{
		EVP_PKEY *pkey;
		BIO *in;

		if (!sign_flag && !CA_flag)
			{
			BIO_printf(bio_err,"We need a private key to sign with\n");
			goto end;
			}
		in=BIO_new(BIO_s_file());
		if (in == NULL)
			{
			ERR_print_errors(bio_err);
			goto end;
			}

		if (infile == NULL)
			BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT);
		else
			{
			if (BIO_read_filename(in,infile) <= 0)
				{
				perror(infile);
				BIO_free(in);
				goto end;
				}
			}
		req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
		BIO_free(in);

		if (req == NULL)
			{
			ERR_print_errors(bio_err);
			goto end;
			}

		if (	(req->req_info == NULL) ||
			(req->req_info->pubkey == NULL) ||
			(req->req_info->pubkey->public_key == NULL) ||
			(req->req_info->pubkey->public_key->data == NULL))
			{
			BIO_printf(bio_err,"The certificate request appears to corrupted\n");
			BIO_printf(bio_err,"It does not contain a public key\n");
			goto end;
			}
		if ((pkey=X509_REQ_get_pubkey(req)) == NULL)
	                {
	                BIO_printf(bio_err,"error unpacking public key\n");
	                goto end;
	                }
		i=X509_REQ_verify(req,pkey);
		EVP_PKEY_free(pkey);
		if (i < 0)
			{
			BIO_printf(bio_err,"Signature verification error\n");
			ERR_print_errors(bio_err);
			goto end;
			}
	        if (i == 0)
			{
			BIO_printf(bio_err,"Signature did not match the certificate request\n");
			goto end;
			}
		else
			BIO_printf(bio_err,"Signature ok\n");

		print_name(bio_err, "subject=", X509_REQ_get_subject_name(req), nmflag);

		if ((x=X509_new()) == NULL) goto end;

		if (sno == NULL)
			{
			sno = ASN1_INTEGER_new();
			if (!sno || !rand_serial(NULL, sno))
				goto end;
			if (!X509_set_serialNumber(x, sno)) 
				goto end;
			ASN1_INTEGER_free(sno);
			sno = NULL;
			}
		else if (!X509_set_serialNumber(x, sno)) 
			goto end;

		if (!X509_set_issuer_name(x,req->req_info->subject)) goto end;
		if (!X509_set_subject_name(x,req->req_info->subject)) goto end;

		X509_gmtime_adj(X509_get_notBefore(x),0);
	        X509_time_adj_ex(X509_get_notAfter(x),days, 0, NULL);

		pkey = X509_REQ_get_pubkey(req);
		X509_set_pubkey(x,pkey);
		EVP_PKEY_free(pkey);
		}
	else
		x=load_cert(bio_err,infile,informat,NULL,e,"Certificate");

	if (x == NULL) goto end;
	if (CA_flag)
		{
		xca=load_cert(bio_err,CAfile,CAformat,NULL,e,"CA Certificate");
		if (xca == NULL) goto end;
		}

	if (!noout || text || next_serial)
		{
		OBJ_create("2.99999.3",
			"SET.ex3","SET x509v3 extension 3");

		out=BIO_new(BIO_s_file());
		if (out == NULL)
			{
			ERR_print_errors(bio_err);
			goto end;
			}
		if (outfile == NULL)
			{
			BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
			{
			BIO *tmpbio = BIO_new(BIO_f_linebuffer());
			out = BIO_push(tmpbio, out);
			}
#endif
			}
		else
			{
			if (BIO_write_filename(out,outfile) <= 0)
				{
				perror(outfile);
				goto end;
				}
			}
		}

	if (alias) X509_alias_set1(x, (unsigned char *)alias, -1);

	if (clrtrust) X509_trust_clear(x);
	if (clrreject) X509_reject_clear(x);

	if (trust)
		{
		for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++)
			{
			objtmp = sk_ASN1_OBJECT_value(trust, i);
			X509_add1_trust_object(x, objtmp);
			}
		}

	if (reject)
		{
		for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++)
			{
			objtmp = sk_ASN1_OBJECT_value(reject, i);
			X509_add1_reject_object(x, objtmp);
			}
		}

	if (num)
		{
		for (i=1; i<=num; i++)
			{
			if (issuer == i)
				{
				print_name(STDout, "issuer= ",
					X509_get_issuer_name(x), nmflag);
				}
			else if (subject == i) 
				{
				print_name(STDout, "subject= ",
					X509_get_subject_name(x), nmflag);
				}
			else if (serial == i)
				{
				BIO_printf(STDout,"serial=");
				i2a_ASN1_INTEGER(STDout,
					X509_get_serialNumber(x));
				BIO_printf(STDout,"\n");
				}
			else if (next_serial == i)
				{
				BIGNUM *bnser;
				ASN1_INTEGER *ser;
				ser = X509_get_serialNumber(x);
				bnser = ASN1_INTEGER_to_BN(ser, NULL);
				if (!bnser)
					goto end;
				if (!BN_add_word(bnser, 1))
					goto end;
				ser = BN_to_ASN1_INTEGER(bnser, NULL);
				if (!ser)
					goto end;
				BN_free(bnser);
				i2a_ASN1_INTEGER(out, ser);
				ASN1_INTEGER_free(ser);
				BIO_puts(out, "\n");
				}
			else if ((email == i) || (ocsp_uri == i))
				{
				int j;
				STACK_OF(OPENSSL_STRING) *emlst;
				if (email == i)
					emlst = X509_get1_email(x);
				else
					emlst = X509_get1_ocsp(x);
				for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
					BIO_printf(STDout, "%s\n",
						   sk_OPENSSL_STRING_value(emlst, j));
				X509_email_free(emlst);
				}
			else if (aliasout == i)
				{
				unsigned char *alstr;
				alstr = X509_alias_get0(x, NULL);
				if (alstr) BIO_printf(STDout,"%s\n", alstr);
				else BIO_puts(STDout,"<No Alias>\n");
				}
			else if (subject_hash == i)
				{
				BIO_printf(STDout,"%08lx\n",X509_subject_name_hash(x));
				}
#ifndef OPENSSL_NO_MD5
			else if (subject_hash_old == i)
				{
				BIO_printf(STDout,"%08lx\n",X509_subject_name_hash_old(x));
				}
#endif
			else if (issuer_hash == i)
				{
				BIO_printf(STDout,"%08lx\n",X509_issuer_name_hash(x));
				}
#ifndef OPENSSL_NO_MD5
			else if (issuer_hash_old == i)
				{
				BIO_printf(STDout,"%08lx\n",X509_issuer_name_hash_old(x));
				}
#endif
			else if (pprint == i)
				{
				X509_PURPOSE *ptmp;
				int j;
				BIO_printf(STDout, "Certificate purposes:\n");
				for (j = 0; j < X509_PURPOSE_get_count(); j++)
					{
					ptmp = X509_PURPOSE_get0(j);
					purpose_print(STDout, x, ptmp);
					}
				}
			else
				if (modulus == i)
				{
				EVP_PKEY *pkey;

				pkey=X509_get_pubkey(x);
				if (pkey == NULL)
					{
					BIO_printf(bio_err,"Modulus=unavailable\n");
					ERR_print_errors(bio_err);
					goto end;
					}
				BIO_printf(STDout,"Modulus=");
#ifndef OPENSSL_NO_RSA
				if (pkey->type == EVP_PKEY_RSA)
					BN_print(STDout,pkey->pkey.rsa->n);
				else
#endif
#ifndef OPENSSL_NO_DSA
				if (pkey->type == EVP_PKEY_DSA)
					BN_print(STDout,pkey->pkey.dsa->pub_key);
				else
#endif
					BIO_printf(STDout,"Wrong Algorithm type");
				BIO_printf(STDout,"\n");
				EVP_PKEY_free(pkey);
				}
			else
				if (pubkey == i)
				{
				EVP_PKEY *pkey;

				pkey=X509_get_pubkey(x);
				if (pkey == NULL)
					{
					BIO_printf(bio_err,"Error getting public key\n");
					ERR_print_errors(bio_err);
					goto end;
					}
				PEM_write_bio_PUBKEY(STDout, pkey);
				EVP_PKEY_free(pkey);
				}
			else
				if (C == i)
				{
				unsigned char *d;
				char *m;
				int y,z;

				X509_NAME_oneline(X509_get_subject_name(x),
					buf,sizeof buf);
				BIO_printf(STDout,"/* subject:%s */\n",buf);
				m=X509_NAME_oneline(
					X509_get_issuer_name(x),buf,
					sizeof buf);
				BIO_printf(STDout,"/* issuer :%s */\n",buf);

				z=i2d_X509(x,NULL);
				m=OPENSSL_malloc(z);

				d=(unsigned char *)m;
				z=i2d_X509_NAME(X509_get_subject_name(x),&d);
				BIO_printf(STDout,"unsigned char XXX_subject_name[%d]={\n",z);
				d=(unsigned char *)m;
				for (y=0; y<z; y++)
					{
					BIO_printf(STDout,"0x%02X,",d[y]);
					if ((y & 0x0f) == 0x0f) BIO_printf(STDout,"\n");
					}
				if (y%16 != 0) BIO_printf(STDout,"\n");
				BIO_printf(STDout,"};\n");

				z=i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x),&d);
				BIO_printf(STDout,"unsigned char XXX_public_key[%d]={\n",z);
				d=(unsigned char *)m;
				for (y=0; y<z; y++)
					{
					BIO_printf(STDout,"0x%02X,",d[y]);
					if ((y & 0x0f) == 0x0f)
						BIO_printf(STDout,"\n");
					}
				if (y%16 != 0) BIO_printf(STDout,"\n");
				BIO_printf(STDout,"};\n");

				z=i2d_X509(x,&d);
				BIO_printf(STDout,"unsigned char XXX_certificate[%d]={\n",z);
				d=(unsigned char *)m;
				for (y=0; y<z; y++)
					{
					BIO_printf(STDout,"0x%02X,",d[y]);
					if ((y & 0x0f) == 0x0f)
						BIO_printf(STDout,"\n");
					}
				if (y%16 != 0) BIO_printf(STDout,"\n");
				BIO_printf(STDout,"};\n");

				OPENSSL_free(m);
				}
			else if (text == i)
				{
				X509_print_ex(out,x,nmflag, certflag);
				}
			else if (startdate == i)
				{
				BIO_puts(STDout,"notBefore=");
				ASN1_TIME_print(STDout,X509_get_notBefore(x));
				BIO_puts(STDout,"\n");
				}
			else if (enddate == i)
				{
				BIO_puts(STDout,"notAfter=");
				ASN1_TIME_print(STDout,X509_get_notAfter(x));
				BIO_puts(STDout,"\n");
				}
			else if (fingerprint == i)
				{
				int j;
				unsigned int n;
				unsigned char md[EVP_MAX_MD_SIZE];
				const EVP_MD *fdig = digest;

				if (!fdig)
					fdig = EVP_sha1();

				if (!X509_digest(x,fdig,md,&n))
					{
					BIO_printf(bio_err,"out of memory\n");
					goto end;
					}
				BIO_printf(STDout,"%s Fingerprint=",
						OBJ_nid2sn(EVP_MD_type(fdig)));
				for (j=0; j<(int)n; j++)
					{
					BIO_printf(STDout,"%02X%c",md[j],
						(j+1 == (int)n)
						?'\n':':');
					}
				}

			/* should be in the library */
			else if ((sign_flag == i) && (x509req == 0))
				{
				BIO_printf(bio_err,"Getting Private key\n");
				if (Upkey == NULL)
					{
					Upkey=load_key(bio_err,
						keyfile, keyformat, 0,
						passin, e, "Private key");
					if (Upkey == NULL) goto end;
					}

				assert(need_rand);
				if (!sign(x,Upkey,days,clrext,digest,
						 extconf, extsect)) goto end;
				}
			else if (CA_flag == i)
				{
				BIO_printf(bio_err,"Getting CA Private Key\n");
				if (CAkeyfile != NULL)
					{
					CApkey=load_key(bio_err,
						CAkeyfile, CAkeyformat,
						0, passin, e,
						"CA Private Key");
					if (CApkey == NULL) goto end;
					}
				
				assert(need_rand);
				if (!x509_certify(ctx,CAfile,digest,x,xca,
					CApkey, sigopts,
					CAserial,CA_createserial,days, clrext,
					extconf, extsect, sno))
					goto end;
				}
			else if (x509req == i)
				{
				EVP_PKEY *pk;

				BIO_printf(bio_err,"Getting request Private Key\n");
				if (keyfile == NULL)
					{
					BIO_printf(bio_err,"no request key file specified\n");
					goto end;
					}
				else
					{
					pk=load_key(bio_err,
						keyfile, keyformat, 0,
						passin, e, "request key");
					if (pk == NULL) goto end;
					}

				BIO_printf(bio_err,"Generating certificate request\n");

				rq=X509_to_X509_REQ(x,pk,digest);
				EVP_PKEY_free(pk);
				if (rq == NULL)
					{
					ERR_print_errors(bio_err);
					goto end;
					}
				if (!noout)
					{
					X509_REQ_print(out,rq);
					PEM_write_bio_X509_REQ(out,rq);
					}
				noout=1;
				}
			else if (ocspid == i)
				{
				X509_ocspid_print(out, x);
				}
			}
		}

	if (checkend)
		{
		time_t tcheck=time(NULL) + checkoffset;

		if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0)
			{
			BIO_printf(out,"Certificate will expire\n");
			ret=1;
			}
		else
			{
			BIO_printf(out,"Certificate will not expire\n");
			ret=0;
			}
		goto end;
		}

	if (noout)
		{
		ret=0;
		goto end;
		}

	if 	(outformat == FORMAT_ASN1)
		i=i2d_X509_bio(out,x);
	else if (outformat == FORMAT_PEM)
		{
		if (trustout) i=PEM_write_bio_X509_AUX(out,x);
		else i=PEM_write_bio_X509(out,x);
		}
	else if (outformat == FORMAT_NETSCAPE)
		{
		NETSCAPE_X509 nx;
		ASN1_OCTET_STRING hdr;

		hdr.data=(unsigned char *)NETSCAPE_CERT_HDR;
		hdr.length=strlen(NETSCAPE_CERT_HDR);
		nx.header= &hdr;
		nx.cert=x;

		i=ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509),out,&nx);
		}
	else	{
		BIO_printf(bio_err,"bad output format specified for outfile\n");
		goto end;
		}
	if (!i)
		{
		BIO_printf(bio_err,"unable to write certificate\n");
		ERR_print_errors(bio_err);
		goto end;
		}
	ret=0;
end:
	if (need_rand)
		app_RAND_write_file(NULL, bio_err);
	OBJ_cleanup();
	NCONF_free(extconf);
	BIO_free_all(out);
	BIO_free_all(STDout);
	X509_STORE_free(ctx);
	X509_REQ_free(req);
	X509_free(x);
	X509_free(xca);
	EVP_PKEY_free(Upkey);
	EVP_PKEY_free(CApkey);
	if (sigopts)
		sk_OPENSSL_STRING_free(sigopts);
	X509_REQ_free(rq);
	ASN1_INTEGER_free(sno);
	sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
	sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
	if (passin) OPENSSL_free(passin);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Exemplo n.º 19
0
int main(int argc, char **argv)
{
    char *filename = ZOOK_CONF;
    CONF *conf;
    long eline = 0;
    char *portstr, *svcs;
    int sockfd;
    pid_t disppid;
    int i, status;

    /* read configuration
       http://linux.die.net/man/5/config
       http://www.openssl.org/docs/apps/config.html
     */
    if (argc > 1)
        filename = argv[1];
    conf = NCONF_new(NULL);
    if (!NCONF_load(conf, filename, &eline))
    {
        if (eline)
            errx(1, "Failed parsing %s:%ld", filename, eline);
        else
            errx(1, "Failed opening %s", filename);
    }

    /* http server port, default 80 */
    if (!(portstr = NCONF_get_string(conf, "zook", "port")))
        portstr = "80";
    sockfd = start_server(portstr);
    warnx("Listening on port %s", portstr);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);

    /* launch the dispatch daemon */
    disppid = launch_svc(conf, "zookd");
    /* launch http services */
    if ((svcs = NCONF_get_string(conf, "zook", "http_svcs")))
        CONF_parse_list(svcs, ',', 1, &service_parse_cb, conf);

    /* send the server socket to zookd */
    if (sendfd(svcfds[0], &nsvcs, sizeof(nsvcs), sockfd) < 0)
        err(1, "sendfd to zookd");
    close(sockfd);

    /* send all svc sockets with their url patterns to http services */
    for (i = 1; i < nsvcs; ++i)
    {
        char *url = NCONF_get_string(conf, svcnames[i], "url");
        if (!url)
            url = ".*";
        sendfd(svcfds[0], url, strlen(url) + 1, svcfds[i]);
        close(svcfds[i]);
    }
    close(svcfds[0]);

    /* launch non-http services */
    if ((svcs = NCONF_get_string(conf, "zook", "extra_svcs")))
        CONF_parse_list(svcs, ',', 1, &service_parse_cb, conf);

    NCONF_free(conf);

    /* wait for zookd */
    waitpid(disppid, &status, 0);
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
    FUNCTION f, *fp;
    LHASH_OF(FUNCTION) *prog = NULL;
    char **copied_argv = NULL;
    char *p, *pname;
    char buf[1024];
    const char *prompt;
    ARGS arg;
    int first, n, i, ret = 0;

    arg.argv = NULL;
    arg.size = 0;

    /* Set up some of the environment. */
    default_config_file = make_config_name();
    bio_in = dup_bio_in(FORMAT_TEXT);
    bio_out = dup_bio_out(FORMAT_TEXT);
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);

#if defined( OPENSSL_SYS_VMS)
    copied_argv = argv = copy_argv(&argc, argv);
#endif

    p = getenv("OPENSSL_DEBUG_MEMORY");
    if (p == NULL)
        /* if not set, use compiled-in default */
        ;
    else if (strcmp(p, "off") != 0) {
        CRYPTO_malloc_debug_init();
        CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    } else {
        CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
    CRYPTO_set_locking_callback(lock_dbg_cb);

    if (getenv("OPENSSL_FIPS")) {
#ifdef OPENSSL_FIPS
        if (!FIPS_mode_set(1)) {
            ERR_load_crypto_strings();
            ERR_print_errors(bio_err);
            return 1;
        }
#else
        BIO_printf(bio_err, "FIPS mode not supported.\n");
        return 1;
#endif
    }

    if (!apps_startup())
        goto end;

    prog = prog_init();
    pname = opt_progname(argv[0]);

    /* first check the program name */
    f.name = pname;
    fp = lh_FUNCTION_retrieve(prog, &f);
    if (fp != NULL) {
        argv[0] = pname;
        ret = fp->func(argc, argv);
        goto end;
    }

    /* If there is stuff on the command line, run with that. */
    if (argc != 1) {
        argc--;
        argv++;
        ret = do_cmd(prog, argc, argv);
        if (ret < 0)
            ret = 0;
        goto end;
    }

    /* ok, lets enter interactive mode */
    for (;;) {
        ret = 0;
        /* Read a line, continue reading if line ends with \ */
        for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) {
            prompt = first ? "OpenSSL> " : "> ";
            p[0] = '\0';
#ifndef READLINE
            fputs(prompt, stdout);
            fflush(stdout);
            if (!fgets(p, n, stdin))
                goto end;
            if (p[0] == '\0')
                goto end;
            i = strlen(p);
            if (i <= 1)
                break;
            if (p[i - 2] != '\\')
                break;
            i -= 2;
            p += i;
            n -= i;
#else
            {
                extern char *readline(const char *);
                extern void add_history(const char *cp);
                char *text;

                char *text = readline(prompt);
                if (text == NULL)
                    goto end;
                i = strlen(text);
                if (i == 0 || i > n)
                    break;
                if (text[i - 1] != '\\') {
                    p += strlen(strcpy(p, text));
                    free(text);
                    add_history(buf);
                    break;
                }

                text[i - 1] = '\0';
                p += strlen(strcpy(p, text));
                free(text);
                n -= i;
            }
#endif
        }

        if (!chopup_args(&arg, buf)) {
            BIO_printf(bio_err, "Can't parse (no memory?)\n");
            break;
        }

        ret = do_cmd(prog, arg.argc, arg.argv);
        if (ret == EXIT_THE_PROGRAM) {
            ret = 0;
            goto end;
        }
        if (ret != 0)
            BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
        (void)BIO_flush(bio_out);
        (void)BIO_flush(bio_err);
    }
    ret = 1;
 end:
    OPENSSL_free(copied_argv);
    OPENSSL_free(default_config_file);
    NCONF_free(config);
    config = NULL;
    lh_FUNCTION_free(prog);
    OPENSSL_free(arg.argv);

    BIO_free(bio_in);
    BIO_free_all(bio_out);
    apps_shutdown();
    CRYPTO_mem_leaks(bio_err);
    BIO_free(bio_err);
    return (ret);
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
    BIO *sbio = NULL, *out = NULL;
    int i, len, rv;
    char tmpbuf[1024];
    SSL_CTX *ctx = NULL;
    SSL_CONF_CTX *cctx = NULL;
    SSL *ssl = NULL;
    CONF *conf = NULL;
    STACK_OF(CONF_VALUE) *sect = NULL;
    CONF_VALUE *cnf;
    const char *connect_str = "localhost:4433";
    long errline = -1;

    ERR_load_crypto_strings();
    ERR_load_SSL_strings();
    SSL_library_init();

    conf = NCONF_new(NULL);

    if (NCONF_load(conf, "connect.cnf", &errline) <= 0) {
        if (errline <= 0)
            fprintf(stderr, "Error processing config file\n");
        else
            fprintf(stderr, "Error on line %ld\n", errline);
        goto end;
    }

    sect = NCONF_get_section(conf, "default");

    if (sect == NULL) {
        fprintf(stderr, "Error retrieving default section\n");
        goto end;
    }

    ctx = SSL_CTX_new(SSLv3_client_method());
    cctx = SSL_CONF_CTX_new();
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
    SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
    for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
        cnf = sk_CONF_VALUE_value(sect, i);
        rv = SSL_CONF_cmd(cctx, cnf->name, cnf->value);
        if (rv > 0)
            continue;
        if (rv != -2) {
            fprintf(stderr, "Error processing %s = %s\n",
                    cnf->name, cnf->value);
            ERR_print_errors_fp(stderr);
            goto end;
        }
        if (!strcmp(cnf->name, "Connect")) {
            connect_str = cnf->value;
        } else {
            fprintf(stderr, "Unknown configuration option %s\n", cnf->name);
            goto end;
        }
    }

    if (!SSL_CONF_CTX_finish(cctx)) {
        fprintf(stderr, "Finish error\n");
        ERR_print_errors_fp(stderr);
        goto err;
    }

    /*
     * We'd normally set some stuff like the verify paths and * mode here
     * because as things stand this will connect to * any server whose
     * certificate is signed by any CA.
     */

    sbio = BIO_new_ssl_connect(ctx);

    BIO_get_ssl(sbio, &ssl);

    if (!ssl) {
        fprintf(stderr, "Can't locate SSL pointer\n");
        goto end;
    }

    /* Don't want any retries */
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    /* We might want to do other things with ssl here */

    BIO_set_conn_hostname(sbio, connect_str);

    out = BIO_new_fp(stdout, BIO_NOCLOSE);
    if (BIO_do_connect(sbio) <= 0) {
        fprintf(stderr, "Error connecting to server\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    if (BIO_do_handshake(sbio) <= 0) {
        fprintf(stderr, "Error establishing SSL connection\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    /* Could examine ssl here to get connection info */

    BIO_puts(sbio, "GET / HTTP/1.0\n\n");
    for (;;) {
        len = BIO_read(sbio, tmpbuf, 1024);
        if (len <= 0)
            break;
        BIO_write(out, tmpbuf, len);
    }
 end:
    SSL_CONF_CTX_free(cctx);
    BIO_free_all(sbio);
    BIO_free(out);
    NCONF_free(conf);
    return 0;
}
Exemplo n.º 22
0
int
spkac_main(int argc, char **argv)
{
	int i, ret = 1;
	BIO *in = NULL, *out = NULL;
	char *passin = NULL;
	char *spkstr = NULL;
	CONF *conf = NULL;
	NETSCAPE_SPKI *spki = NULL;
	EVP_PKEY *pkey = NULL;

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

	memset(&spkac_config, 0, sizeof(spkac_config));
	spkac_config.spkac = "SPKAC";
	spkac_config.spksect = "default";

	if (options_parse(argc, argv, spkac_options, NULL, NULL) != 0) {
		spkac_usage();
		return (1);
	}

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

	if (spkac_config.keyfile) {
		pkey = load_key(bio_err,
		    strcmp(spkac_config.keyfile, "-") ? spkac_config.keyfile
		    : NULL, FORMAT_PEM, 1, passin, "private key");
		if (!pkey) {
			goto end;
		}
		spki = NETSCAPE_SPKI_new();
		if (spkac_config.challenge)
			ASN1_STRING_set(spki->spkac->challenge,
			    spkac_config.challenge,
			    (int) strlen(spkac_config.challenge));
		NETSCAPE_SPKI_set_pubkey(spki, pkey);
		NETSCAPE_SPKI_sign(spki, pkey, EVP_md5());
		spkstr = NETSCAPE_SPKI_b64_encode(spki);
		if (spkstr == NULL) {
			BIO_printf(bio_err, "Error encoding SPKAC\n");
			ERR_print_errors(bio_err);
			goto end;
		}

		if (spkac_config.outfile)
			out = BIO_new_file(spkac_config.outfile, "w");
		else
			out = BIO_new_fp(stdout, BIO_NOCLOSE);

		if (!out) {
			BIO_printf(bio_err, "Error opening output file\n");
			ERR_print_errors(bio_err);
		} else {
			BIO_printf(out, "SPKAC=%s\n", spkstr);
			ret = 0;
		}
		free(spkstr);
		goto end;
	}
	if (spkac_config.infile)
		in = BIO_new_file(spkac_config.infile, "r");
	else
		in = BIO_new_fp(stdin, BIO_NOCLOSE);

	if (!in) {
		BIO_printf(bio_err, "Error opening input file\n");
		ERR_print_errors(bio_err);
		goto end;
	}
	conf = NCONF_new(NULL);
	i = NCONF_load_bio(conf, in, NULL);

	if (!i) {
		BIO_printf(bio_err, "Error parsing config file\n");
		ERR_print_errors(bio_err);
		goto end;
	}
	spkstr = NCONF_get_string(conf, spkac_config.spksect,
	    spkac_config.spkac);

	if (!spkstr) {
		BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n",
		    spkac_config.spkac);
		ERR_print_errors(bio_err);
		goto end;
	}
	spki = NETSCAPE_SPKI_b64_decode(spkstr, -1);

	if (!spki) {
		BIO_printf(bio_err, "Error loading SPKAC\n");
		ERR_print_errors(bio_err);
		goto end;
	}
	if (spkac_config.outfile)
		out = BIO_new_file(spkac_config.outfile, "w");
	else {
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
	}

	if (!out) {
		BIO_printf(bio_err, "Error opening output file\n");
		ERR_print_errors(bio_err);
		goto end;
	}
	if (!spkac_config.noout)
		NETSCAPE_SPKI_print(out, spki);
	pkey = NETSCAPE_SPKI_get_pubkey(spki);
	if (spkac_config.verify) {
		i = NETSCAPE_SPKI_verify(spki, pkey);
		if (i > 0)
			BIO_printf(bio_err, "Signature OK\n");
		else {
			BIO_printf(bio_err, "Signature Failure\n");
			ERR_print_errors(bio_err);
			goto end;
		}
	}
	if (spkac_config.pubkey)
		PEM_write_bio_PUBKEY(out, pkey);

	ret = 0;

end:
	NCONF_free(conf);
	NETSCAPE_SPKI_free(spki);
	BIO_free(in);
	BIO_free_all(out);
	EVP_PKEY_free(pkey);
	free(passin);

	return (ret);
}
Exemplo n.º 23
0
int ts_main(int argc, char **argv)
{
    CONF *conf = NULL;
    char *CAfile = NULL, *untrusted = NULL, *engine = NULL, *prog, **helpp;
    char *configfile = NULL, *section = NULL, *password = NULL;
    char *data = NULL, *digest = NULL, *rnd = NULL, *policy = NULL;
    char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL;
    char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL;
    const EVP_MD *md = NULL;
    OPTION_CHOICE o, mode = OPT_ERR;
    int ret = 1, no_nonce = 0, cert = 0, text = 0;
    /* Input is ContentInfo instead of TimeStampResp. */
    int token_in = 0;
    /* Output is ContentInfo instead of TimeStampResp. */
    int token_out = 0;

    prog = opt_init(argc, argv, ts_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(ts_options);
            for (helpp = opt_helplist; *helpp; ++helpp)
                BIO_printf(bio_err, "%s\n", *helpp);
            ret = 0;
            goto end;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_SECTION:
            section = opt_arg();
            break;
        case OPT_QUERY:
        case OPT_REPLY:
        case OPT_VERIFY:
            if (mode != OPT_ERR)
                goto opthelp;
            mode = o;
            break;
        case OPT_DATA:
            data = opt_arg();
            break;
        case OPT_DIGEST:
            digest = opt_arg();
            break;
        case OPT_RAND:
            rnd = opt_arg();
            break;
        case OPT_POLICY:
            policy = opt_arg();
            break;
        case OPT_NO_NONCE:
            no_nonce = 1;
            break;
        case OPT_CERT:
            cert = 1;
            break;
        case OPT_IN:
            in = opt_arg();
            break;
        case OPT_TOKEN_IN:
            token_in = 1;
            break;
        case OPT_OUT:
            out = opt_arg();
            break;
        case OPT_TOKEN_OUT:
            token_out = 1;
            break;
        case OPT_TEXT:
            text = 1;
            break;
        case OPT_QUERYFILE:
            queryfile = opt_arg();
            break;
        case OPT_PASSIN:
            passin = opt_arg();
            break;
        case OPT_INKEY:
            inkey = opt_arg();
            break;
        case OPT_SIGNER:
            signer = opt_arg();
            break;
        case OPT_CHAIN:
            chain = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_UNTRUSTED:
            untrusted = opt_arg();
            break;
        case OPT_ENGINE:
            engine = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_unknown(), &md))
                goto opthelp;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();
    if (mode == OPT_ERR || argc != 0)
        goto opthelp;

    /* Seed the random number generator if it is going to be used. */
    if (mode == OPT_QUERY && !no_nonce) {
        if (!app_RAND_load_file(NULL, 1) && rnd == NULL)
            BIO_printf(bio_err, "warning, not much extra random "
                       "data, consider using the -rand option\n");
        if (rnd != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(rnd));
    }

    /* Get the password if required. */
    if (mode == OPT_REPLY && passin &&
        !app_passwd(passin, NULL, &password, NULL)) {
        BIO_printf(bio_err, "Error getting password.\n");
        goto end;
    }

    /*
     * Check consistency of parameters and execute the appropriate function.
     */
    switch (mode) {
    default:
    case OPT_ERR:
        goto opthelp;
    case OPT_QUERY:
        /*
         * Data file and message imprint cannot be specified at the same
         * time.
         */
        ret = data != NULL && digest != NULL;
        if (ret)
            goto opthelp;
        /* Load the config file for possible policy OIDs. */
        conf = load_config_file(configfile);
        ret = !query_command(data, digest, md, policy, no_nonce, cert,
                             in, out, text);
        break;
    case OPT_REPLY:
        conf = load_config_file(configfile);
        if (in == NULL) {
            ret = !(queryfile != NULL && conf != NULL && !token_in);
            if (ret)
                goto opthelp;
        } else {
            /* 'in' and 'queryfile' are exclusive. */
            ret = !(queryfile == NULL);
            if (ret)
                goto opthelp;
        }
        ret = !reply_command(conf, section, engine, queryfile,
                             password, inkey, signer, chain, policy,
                             in, token_in, out, token_out, text);
        break;
    case OPT_VERIFY:
        ret = !(((queryfile && !data && !digest)
                 || (!queryfile && data && !digest)
                 || (!queryfile && !data && digest))
                && in != NULL);
        if (ret)
            goto opthelp;

        ret = !verify_command(data, digest, queryfile, in, token_in,
                              CApath, CAfile, untrusted);
    }

 end:
    /* Clean up. */
    app_RAND_write_file(NULL);
    NCONF_free(conf);
    OPENSSL_free(password);
    OBJ_cleanup();

    return (ret);
}
Exemplo n.º 24
0
int srp_main(int argc, char **argv)
{
    CA_DB *db = NULL;
    CONF *conf = NULL;
    int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i;
    int doupdatedb = 0, mode = OPT_ERR;
    char *user = NULL, *passinarg = NULL, *passoutarg = NULL;
    char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL;
    char *randfile = NULL, *section = NULL;
    char **gNrow = NULL, *configfile = NULL;
    char *srpvfile = NULL, **pp, *prog;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, srp_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(srp_options);
            ret = 0;
            goto end;
        case OPT_VERBOSE:
            verbose++;
            break;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_NAME:
            section = opt_arg();
            break;
        case OPT_SRPVFILE:
            srpvfile = opt_arg();
            break;
        case OPT_ADD:
        case OPT_DELETE:
        case OPT_MODIFY:
        case OPT_LIST:
            if (mode != OPT_ERR) {
                BIO_printf(bio_err,
                           "%s: Only one of -add/delete-modify/-list\n",
                           prog);
                goto opthelp;
            }
            mode = o;
            break;
        case OPT_GN:
            gN = opt_arg();
            break;
        case OPT_USERINFO:
            userinfo = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (srpvfile && configfile) {
        BIO_printf(bio_err,
                   "-srpvfile and -configfile cannot be specified together.\n");
        goto end;
    }
    if (mode == OPT_ERR) {
        BIO_printf(bio_err,
                   "Exactly one of the options -add, -delete, -modify -list must be specified.\n");
        goto opthelp;
    }
    if ((mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD)
        && argc < 1) {
        BIO_printf(bio_err,
                   "Need at least one user for options -add, -delete, -modify. \n");
        goto opthelp;
    }
    if ((passin || passout) && argc != 1) {
        BIO_printf(bio_err,
                   "-passin, -passout arguments only valid with one user.\n");
        goto opthelp;
    }

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

    if (!srpvfile) {
        if (!configfile)
            configfile = default_config_file;

        if (verbose)
            BIO_printf(bio_err, "Using configuration from %s\n",
                       configfile);
        conf = app_load_config(configfile);
        if (conf == NULL)
            goto end;
        if (configfile != default_config_file && !app_load_modules(conf))
            goto end;

        /* Lets get the config section we are using */
        if (section == NULL) {
            if (verbose)
                BIO_printf(bio_err,
                           "trying to read " ENV_DEFAULT_SRP
                           " in " BASE_SECTION "\n");

            section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP);
            if (section == NULL)
                goto end;
        }

        if (randfile == NULL)
            randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

        if (verbose)
            BIO_printf(bio_err,
                       "trying to read " ENV_DATABASE " in section \"%s\"\n",
                       section);

        srpvfile = lookup_conf(conf, section, ENV_DATABASE);
        if (srpvfile == NULL)
            goto end;
    }
    if (randfile == NULL)
        ERR_clear_error();
    else
        app_RAND_load_file(randfile, 0);

    if (verbose)
        BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
                   srpvfile);

    db = load_index(srpvfile, NULL);
    if (db == NULL)
        goto end;

    /* Lets check some fields */
    for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
        pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

        if (pp[DB_srptype][0] == DB_SRP_INDEX) {
            maxgN = i;
            if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0)
                gNindex = i;

            print_index(db, i, verbose > 1);
        }
    }

    if (verbose)
        BIO_printf(bio_err, "Database initialised\n");

    if (gNindex >= 0) {
        gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
        print_entry(db, gNindex, verbose > 1, "Default g and N");
    } else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
        BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
        goto end;
    } else {
        if (verbose)
            BIO_printf(bio_err, "Database has no g N information.\n");
        gNrow = NULL;
    }

    if (verbose > 1)
        BIO_printf(bio_err, "Starting user processing\n");

    if (argc > 0)
        user = *(argv++);

    while (mode == OPT_LIST || user) {
        int userindex = -1;

        if (user != NULL && verbose > 1)
            BIO_printf(bio_err, "Processing user \"%s\"\n", user);
        if ((userindex = get_index(db, user, 'U')) >= 0) {
            print_user(db, userindex, (verbose > 0) || mode == OPT_LIST);
        }

        if (mode == OPT_LIST) {
            if (user == NULL) {
                BIO_printf(bio_err, "List all users\n");

                for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
                    print_user(db, i, 1);
                }
            } else if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, ignored. t\n", user);
                errors++;
            }
        } else if (mode == OPT_ADD) {
            if (userindex >= 0) {
                /* reactivation of a new user */
                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
                row[DB_srptype][0] = 'V';

                doupdatedb = 1;
            } else {
                char *row[DB_NUMBER];
                char *gNid;
                row[DB_srpverifier] = NULL;
                row[DB_srpsalt] = NULL;
                row[DB_srpinfo] = NULL;
                if (!
                    (gNid =
                     srp_create_user(user, &(row[DB_srpverifier]),
                                     &(row[DB_srpsalt]),
                                     gNrow ? gNrow[DB_srpsalt] : gN,
                                     gNrow ? gNrow[DB_srpverifier] : NULL,
                                     passout, verbose))) {
                    BIO_printf(bio_err,
                               "Cannot create srp verifier for user \"%s\", operation abandoned .\n",
                               user);
                    errors++;
                    goto end;
                }
                row[DB_srpid] = OPENSSL_strdup(user);
                row[DB_srptype] = OPENSSL_strdup("v");
                row[DB_srpgN] = OPENSSL_strdup(gNid);

                if ((row[DB_srpid] == NULL)
                    || (row[DB_srpgN] == NULL)
                    || (row[DB_srptype] == NULL)
                    || (row[DB_srpverifier] == NULL)
                    || (row[DB_srpsalt] == NULL)
                    || (userinfo
                        && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))
                    || !update_index(db, row)) {
                    OPENSSL_free(row[DB_srpid]);
                    OPENSSL_free(row[DB_srpgN]);
                    OPENSSL_free(row[DB_srpinfo]);
                    OPENSSL_free(row[DB_srptype]);
                    OPENSSL_free(row[DB_srpverifier]);
                    OPENSSL_free(row[DB_srpsalt]);
                    goto end;
                }
                doupdatedb = 1;
            }
        } else if (mode == OPT_MODIFY) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored.\n",
                           user);
                errors++;
            } else {

                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                char type = row[DB_srptype][0];
                if (type == 'v') {
                    BIO_printf(bio_err,
                               "user \"%s\" already updated, operation ignored.\n",
                               user);
                    errors++;
                } else {
                    char *gNid;

                    if (row[DB_srptype][0] == 'V') {
                        int user_gN;
                        char **irow = NULL;
                        if (verbose)
                            BIO_printf(bio_err,
                                       "Verifying password for user \"%s\"\n",
                                       user);
                        if ((user_gN =
                             get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
                            irow =
                                sk_OPENSSL_PSTRING_value(db->db->data,
                                                         userindex);

                        if (!srp_verify_user
                            (user, row[DB_srpverifier], row[DB_srpsalt],
                             irow ? irow[DB_srpsalt] : row[DB_srpgN],
                             irow ? irow[DB_srpverifier] : NULL, passin,
                             verbose)) {
                            BIO_printf(bio_err,
                                       "Invalid password for user \"%s\", operation abandoned.\n",
                                       user);
                            errors++;
                            goto end;
                        }
                    }
                    if (verbose)
                        BIO_printf(bio_err, "Password for user \"%s\" ok.\n",
                                   user);

                    if (!
                        (gNid =
                         srp_create_user(user, &(row[DB_srpverifier]),
                                         &(row[DB_srpsalt]),
                                         gNrow ? gNrow[DB_srpsalt] : NULL,
                                         gNrow ? gNrow[DB_srpverifier] : NULL,
                                         passout, verbose))) {
                        BIO_printf(bio_err,
                                   "Cannot create srp verifier for user \"%s\", operation abandoned.\n",
                                   user);
                        errors++;
                        goto end;
                    }

                    row[DB_srptype][0] = 'v';
                    row[DB_srpgN] = OPENSSL_strdup(gNid);

                    if (row[DB_srpid] == NULL
                        || row[DB_srpgN] == NULL
                        || row[DB_srptype] == NULL
                        || row[DB_srpverifier] == NULL
                        || row[DB_srpsalt] == NULL
                        || (userinfo
                            && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo))
                                == NULL)))
                        goto end;

                    doupdatedb = 1;
                }
            }
        } else if (mode == OPT_DELETE) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored. t\n",
                           user);
                errors++;
            } else {
                char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);

                BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
                xpp[DB_srptype][0] = 'R';
                doupdatedb = 1;
            }
        }
        if (--argc > 0)
            user = *(argv++);
        else {
            user = NULL;
        }
    }

    if (verbose)
        BIO_printf(bio_err, "User procession done.\n");

    if (doupdatedb) {
        /* Lets check some fields */
        for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
            pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

            if (pp[DB_srptype][0] == 'v') {
                pp[DB_srptype][0] = 'V';
                print_user(db, i, verbose);
            }
        }

        if (verbose)
            BIO_printf(bio_err, "Trying to update srpvfile.\n");
        if (!save_index(srpvfile, "new", db))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "Temporary srpvfile created.\n");
        if (!rotate_index(srpvfile, "new", "old"))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "srpvfile updated.\n");
    }

    ret = (errors != 0);
 end:
    if (errors != 0)
        if (verbose)
            BIO_printf(bio_err, "User errors %d.\n", errors);

    if (verbose)
        BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);

    OPENSSL_free(passin);
    OPENSSL_free(passout);
    if (ret)
        ERR_print_errors(bio_err);
    if (randfile)
        app_RAND_write_file(randfile);
    NCONF_free(conf);
    free_index(db);
    return (ret);
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
	ARGS arg;
#define PROG_NAME_SIZE	39
	char pname[PROG_NAME_SIZE + 1];
	FUNCTION f, *fp;
	const char *prompt;
	char buf[1024];
	char *to_free = NULL;
	int n, i, ret = 0;
	char *p;
	LHASH_OF(FUNCTION) * prog = NULL;
	long errline;

	arg.data = NULL;
	arg.count = 0;

	if (pledge("stdio cpath wpath rpath inet dns proc flock tty", NULL) == -1) {
		fprintf(stderr, "openssl: pledge: %s\n", strerror(errno));
		exit(1);
	}

	bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
	if (bio_err == NULL) {
		fprintf(stderr, "openssl: failed to initialise bio_err\n");
		exit(1);
	}

	if (BIO_sock_init() != 1) {
		BIO_printf(bio_err, "BIO_sock_init failed\n");
		exit(1);
	}

	CRYPTO_set_locking_callback(lock_dbg_cb);

	openssl_startup();

	/* Lets load up our environment a little */
	p = getenv("OPENSSL_CONF");
	if (p == NULL) {
		p = to_free = make_config_name();
		if (p == NULL) {
			BIO_printf(bio_err, "error making config file name\n");
			goto end;
		}
	}

	default_config_file = p;

	config = NCONF_new(NULL);
	i = NCONF_load(config, p, &errline);
	if (i == 0) {
		if (ERR_GET_REASON(ERR_peek_last_error()) ==
		    CONF_R_NO_SUCH_FILE) {
			BIO_printf(bio_err,
			    "WARNING: can't open config file: %s\n", p);
			ERR_clear_error();
			NCONF_free(config);
			config = NULL;
		} else {
			ERR_print_errors(bio_err);
			NCONF_free(config);
			exit(1);
		}
	}

	if (!load_config(bio_err, NULL)) {
		BIO_printf(bio_err, "failed to load configuration\n");
		goto end;
	}

	prog = prog_init();

	/* first check the program name */
	program_name(argv[0], pname, sizeof pname);

	f.name = pname;
	fp = lh_FUNCTION_retrieve(prog, &f);
	if (fp != NULL) {
		argv[0] = pname;

		single_execution = 1;
		ret = fp->func(argc, argv);
		goto end;
	}
	/*
	 * ok, now check that there are not arguments, if there are, run with
	 * them, shifting the ssleay off the front
	 */
	if (argc != 1) {
		argc--;
		argv++;

		single_execution = 1;
		ret = do_cmd(prog, argc, argv);
		if (ret < 0)
			ret = 0;
		goto end;
	}
	/* ok, lets enter the old 'OpenSSL>' mode */

	for (;;) {
		ret = 0;
		p = buf;
		n = sizeof buf;
		i = 0;
		for (;;) {
			p[0] = '\0';
			if (i++)
				prompt = ">";
			else
				prompt = "OpenSSL> ";
			fputs(prompt, stdout);
			fflush(stdout);
			if (!fgets(p, n, stdin))
				goto end;
			if (p[0] == '\0')
				goto end;
			i = strlen(p);
			if (i <= 1)
				break;
			if (p[i - 2] != '\\')
				break;
			i -= 2;
			p += i;
			n -= i;
		}
		if (!chopup_args(&arg, buf, &argc, &argv))
			break;

		ret = do_cmd(prog, argc, argv);
		if (ret < 0) {
			ret = 0;
			goto end;
		}
		if (ret != 0)
			BIO_printf(bio_err, "error in %s\n", argv[0]);
		(void) BIO_flush(bio_err);
	}
	BIO_printf(bio_err, "bad exit\n");
	ret = 1;

end:
	free(to_free);

	if (config != NULL) {
		NCONF_free(config);
		config = NULL;
	}
	if (prog != NULL)
		lh_FUNCTION_free(prog);
	free(arg.data);

	openssl_shutdown();

	if (bio_err != NULL) {
		BIO_free(bio_err);
		bio_err = NULL;
	}
	return (ret);
}
Exemplo n.º 26
0
int MAIN(int argc, char **argv)
	{
	int ret = 1;
	char *configfile = NULL;
	char *section = NULL;
	CONF *conf = NULL;
	enum mode {
	CMD_NONE, CMD_QUERY, CMD_REPLY, CMD_VERIFY 
	} mode = CMD_NONE;
	char *data = NULL;
	char *digest = NULL;
	const EVP_MD *md = NULL;
	char *rnd = NULL;
	char *policy = NULL;
	int no_nonce = 0;
	int cert = 0;
	char *in = NULL;
	char *out = NULL;
	int text = 0;
	char *queryfile = NULL;
	char *passin = NULL;	/* Password source. */
	char *password =NULL;	/* Password itself. */
	char *inkey = NULL;
	char *signer = NULL;
	char *chain = NULL;
	char *ca_path = NULL;
	char *ca_file = NULL;
	char *untrusted = NULL;
	char *engine = NULL;
	/* Input is ContentInfo instead of TimeStampResp. */
	int token_in = 0;	
	/* Output is ContentInfo instead of TimeStampResp. */
	int token_out = 0;
	int free_bio_err = 0;

	ERR_load_crypto_strings();
	apps_startup();

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

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

	for (argc--, argv++; argc > 0; argc--, argv++)
		{
		if (strcmp(*argv, "-config") == 0)
			{
			if (argc-- < 1) goto usage;
			configfile = *++argv;
			}
		else if (strcmp(*argv, "-section") == 0)
			{
			if (argc-- < 1) goto usage;
			section = *++argv;
			}
		else if (strcmp(*argv, "-query") == 0)
			{
			if (mode != CMD_NONE) goto usage;
			mode = CMD_QUERY;
			}
		else if (strcmp(*argv, "-data") == 0)
			{
			if (argc-- < 1) goto usage;
			data = *++argv;
			}
		else if (strcmp(*argv, "-digest") == 0)
			{
			if (argc-- < 1) goto usage;
			digest = *++argv;
			}
		else if (strcmp(*argv, "-rand") == 0)
			{
			if (argc-- < 1) goto usage;
			rnd = *++argv;
			}
		else if (strcmp(*argv, "-policy") == 0)
			{
			if (argc-- < 1) goto usage;
			policy = *++argv;
			}
		else if (strcmp(*argv, "-no_nonce") == 0)
			{
			no_nonce = 1;
			}
		else if (strcmp(*argv, "-cert") == 0)
			{
			cert = 1;
			}
		else if (strcmp(*argv, "-in") == 0)
			{
			if (argc-- < 1) goto usage;
			in = *++argv;
			}
		else if (strcmp(*argv, "-token_in") == 0)
			{
			token_in = 1;
			}
		else if (strcmp(*argv, "-out") == 0)
			{
			if (argc-- < 1) goto usage;
			out = *++argv;
			}
		else if (strcmp(*argv, "-token_out") == 0)
			{
			token_out = 1;
			}
		else if (strcmp(*argv, "-text") == 0)
			{
			text = 1;
			}
		else if (strcmp(*argv, "-reply") == 0)
			{
			if (mode != CMD_NONE) goto usage;
			mode = CMD_REPLY;
			}
		else if (strcmp(*argv, "-queryfile") == 0)
			{
			if (argc-- < 1) goto usage;
			queryfile = *++argv;
			}
		else if (strcmp(*argv, "-passin") == 0)
			{
			if (argc-- < 1) goto usage;
			passin = *++argv;
			}
		else if (strcmp(*argv, "-inkey") == 0)
			{
			if (argc-- < 1) goto usage;
			inkey = *++argv;
			}
		else if (strcmp(*argv, "-signer") == 0)
			{
			if (argc-- < 1) goto usage;
			signer = *++argv;
			}
		else if (strcmp(*argv, "-chain") == 0)
			{
			if (argc-- < 1) goto usage;
			chain = *++argv;
			}
		else if (strcmp(*argv, "-verify") == 0)
			{
			if (mode != CMD_NONE) goto usage;
			mode = CMD_VERIFY;
			}
		else if (strcmp(*argv, "-CApath") == 0)
			{
			if (argc-- < 1) goto usage;
			ca_path = *++argv;
			}
		else if (strcmp(*argv, "-CAfile") == 0)
			{
			if (argc-- < 1) goto usage;
			ca_file = *++argv;
			}
		else if (strcmp(*argv, "-untrusted") == 0)
			{
			if (argc-- < 1) goto usage;
			untrusted = *++argv;
			}
		else if (strcmp(*argv, "-engine") == 0)
			{
			if (argc-- < 1) goto usage;
			engine = *++argv;
			}
		else if ((md = EVP_get_digestbyname(*argv + 1)) != NULL)
			{
			/* empty. */
			}
		else
			goto usage;
		}
	
	/* Seed the random number generator if it is going to be used. */
	if (mode == CMD_QUERY && !no_nonce)
		{
		if (!app_RAND_load_file(NULL, bio_err, 1) && rnd == NULL)
			BIO_printf(bio_err, "warning, not much extra random "
				   "data, consider using the -rand option\n");
		if (rnd != NULL)
			BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
				   app_RAND_load_files(rnd));
		}

	/* Get the password if required. */
	if(mode == CMD_REPLY && passin &&
	   !app_passwd(bio_err, passin, NULL, &password, NULL))
		{
		BIO_printf(bio_err,"Error getting password.\n");
		goto cleanup;
		}

	/* Check consistency of parameters and execute 
	   the appropriate function. */
	switch (mode)
		{
	case CMD_NONE:
		goto usage;
	case CMD_QUERY:
		/* Data file and message imprint cannot be specified
		   at the same time. */
		ret = data != NULL && digest != NULL;
		if (ret) goto usage;
		/* Load the config file for possible policy OIDs. */
		conf = load_config_file(configfile);
		ret = !query_command(data, digest, md, policy, no_nonce, cert,
				     in, out, text);
		break;
	case CMD_REPLY:
		conf = load_config_file(configfile);
		if (in == NULL)
			{
			ret = !(queryfile != NULL && conf != NULL && !token_in);
			if (ret) goto usage;
			}
		else
			{
			/* 'in' and 'queryfile' are exclusive. */
			ret = !(queryfile == NULL);
			if (ret) goto usage;
			}

		ret = !reply_command(conf, section, engine, queryfile, 
				     password, inkey, signer, chain, policy, 
				     in, token_in, out, token_out, text);
		break;
	case CMD_VERIFY:
		ret = !(((queryfile && !data && !digest)
			 || (!queryfile && data && !digest)
			 || (!queryfile && !data && digest))
			&& in != NULL);
		if (ret) goto usage;

		ret = !verify_command(data, digest, queryfile, in, token_in,
				      ca_path, ca_file, untrusted);
		}

	goto cleanup;

 usage:
	BIO_printf(bio_err, "usage:\n"
		   "ts -query [-rand file%cfile%c...] [-config configfile] "
		   "[-data file_to_hash] [-digest digest_bytes]"
		   "[-md2|-md4|-md5|-sha|-sha1|-mdc2|-ripemd160] "
		   "[-policy object_id] [-no_nonce] [-cert] "
		   "[-in request.tsq] [-out request.tsq] [-text]\n",
		   LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
	BIO_printf(bio_err, "or\n"
		   "ts -reply [-config configfile] [-section tsa_section] "
		   "[-queryfile request.tsq] [-passin password] "
		   "[-signer tsa_cert.pem] [-inkey private_key.pem] "
		   "[-chain certs_file.pem] [-policy object_id] "
		   "[-in response.tsr] [-token_in] "
		   "[-out response.tsr] [-token_out] [-text] [-engine id]\n");
	BIO_printf(bio_err, "or\n"
		   "ts -verify [-data file_to_hash] [-digest digest_bytes] "
		   "[-queryfile request.tsq] "
		   "-in response.tsr [-token_in] "
		   "-CApath ca_path -CAfile ca_file.pem "
		   "-untrusted cert_file.pem\n");
 cleanup:
	/* Clean up. */
	app_RAND_write_file(NULL, bio_err);
	NCONF_free(conf);
	OPENSSL_free(password);
	OBJ_cleanup();
	if (free_bio_err)
		{
		BIO_free_all(bio_err);
		bio_err = NULL;
		}

	OPENSSL_EXIT(ret);
	}
Exemplo n.º 27
0
int MAIN(int argc, char **argv)
	{
	int add_user = 0;
	int list_user= 0;
	int delete_user= 0;
	int modify_user= 0;
	char * user = NULL;

	char *passargin = NULL, *passargout = NULL;
	char *passin = NULL, *passout = NULL;
        char * gN = NULL;
	int gNindex = -1;
	char ** gNrow = NULL;
	int maxgN = -1;

	char * userinfo = NULL;

	int badops=0;
	int ret=1;
	int errors=0;
	int verbose=0;
	int doupdatedb=0;
	char *configfile=NULL;
	char *dbfile=NULL;
	CA_DB *db=NULL;
	char **pp ;
	int i;
	long errorline = -1;
	char *randfile=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	char *tofree=NULL;
	DB_ATTR db_attr;

#ifdef EFENCE
EF_PROTECT_FREE=1;
EF_PROTECT_BELOW=1;
EF_ALIGNMENT=0;
#endif

	apps_startup();

	conf = NULL;
	section = NULL;

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

	argc--;
	argv++;
	while (argc >= 1 && badops == 0)
		{
		if	(strcmp(*argv,"-verbose") == 0)
			verbose++;
		else if	(strcmp(*argv,"-config") == 0)
			{
			if (--argc < 1) goto bad;
			configfile= *(++argv);
			}
		else if (strcmp(*argv,"-name") == 0)
			{
			if (--argc < 1) goto bad;
			section= *(++argv);
			}
		else if	(strcmp(*argv,"-srpvfile") == 0)
			{
			if (--argc < 1) goto bad;
			dbfile= *(++argv);
			}
		else if (strcmp(*argv,"-add") == 0)
			add_user=1;
		else if (strcmp(*argv,"-delete") == 0)
			delete_user=1;
		else if (strcmp(*argv,"-modify") == 0)
			modify_user=1;
		else if (strcmp(*argv,"-list") == 0)
			list_user=1;
		else if (strcmp(*argv,"-gn") == 0)
			{
			if (--argc < 1) goto bad;
			gN= *(++argv);
			}
		else if (strcmp(*argv,"-userinfo") == 0)
			{
			if (--argc < 1) goto bad;
			userinfo= *(++argv);
			}
		else if (strcmp(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (strcmp(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif

		else if (**argv == '-')
			{
bad:
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		else 
			break;
	
		argc--;
		argv++;
		}

	if (dbfile && configfile)
		{
		BIO_printf(bio_err,"-dbfile and -configfile cannot be specified together.\n");
		badops = 1;
		}
	if (add_user+delete_user+modify_user+list_user != 1)
		{
		BIO_printf(bio_err,"Exactly one of the options -add, -delete, -modify -list must be specified.\n");
		badops = 1;
		}
	if (delete_user+modify_user+delete_user== 1 && argc <= 0)
		{
		BIO_printf(bio_err,"Need at least one user for options -add, -delete, -modify. \n");
		badops = 1;
		}
	if ((passin || passout) && argc != 1 )
		{
		BIO_printf(bio_err,"-passin, -passout arguments only valid with one user.\n");
		badops = 1;
		}

	if (badops)
		{
		for (pp=srp_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);

		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 err;
		}

	ERR_load_crypto_strings();

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

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

        if (!dbfile)
		{


	/*****************************************************************/
		tofree=NULL;
		if (configfile == NULL) configfile = getenv("OPENSSL_CONF");
		if (configfile == NULL) configfile = getenv("SSLEAY_CONF");
		if (configfile == NULL)
			{
			const char *s=X509_get_default_cert_area();
			size_t len;

#ifdef OPENSSL_SYS_VMS
			len = strlen(s)+sizeof(CONFIG_FILE);
			tofree=OPENSSL_malloc(len);
			strcpy(tofree,s);
#else
			len = strlen(s)+sizeof(CONFIG_FILE)+1;
			tofree=OPENSSL_malloc(len);
			BUF_strlcpy(tofree,s,len);
			BUF_strlcat(tofree,"/",len);
#endif
			BUF_strlcat(tofree,CONFIG_FILE,len);
			configfile=tofree;
			}

		VERBOSE BIO_printf(bio_err,"Using configuration from %s\n",configfile);
		conf = NCONF_new(NULL);
		if (NCONF_load(conf,configfile,&errorline) <= 0)
			{
			if (errorline <= 0)
				BIO_printf(bio_err,"error loading the config file '%s'\n",
					configfile);
			else
				BIO_printf(bio_err,"error on line %ld of config file '%s'\n"
					,errorline,configfile);
			goto err;
			}
		if(tofree)
			{
			OPENSSL_free(tofree);
			tofree = NULL;
			}

		if (!load_config(bio_err, conf))
			goto err;

	/* Lets get the config section we are using */
		if (section == NULL)
			{
			VERBOSE BIO_printf(bio_err,"trying to read " ENV_DEFAULT_SRP " in \" BASE_SECTION \"\n");

			section=NCONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_SRP);
			if (section == NULL)
				{
				lookup_fail(BASE_SECTION,ENV_DEFAULT_SRP);
				goto err;
				}
			}
         
		if (randfile == NULL && conf)
	        	randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

	
		VERBOSE BIO_printf(bio_err,"trying to read " ENV_DATABASE " in section \"%s\"\n",section);

		if ((dbfile=NCONF_get_string(conf,section,ENV_DATABASE)) == NULL)
			{
			lookup_fail(section,ENV_DATABASE);
			goto err;
			}

        	}
	if (randfile == NULL)
		ERR_clear_error();
       	else 
		app_RAND_load_file(randfile, bio_err, 0);

	VERBOSE BIO_printf(bio_err,"Trying to read SRP verifier file \"%s\"\n",dbfile);

	db = load_index(dbfile, &db_attr);
	if (db == NULL) goto err;

	/* Lets check some fields */
	for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
		{
		pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
	
		if (pp[DB_srptype][0] == DB_SRP_INDEX)
			{
			maxgN = i;
			if (gNindex < 0 && gN != NULL && !strcmp(gN, pp[DB_srpid]))
				gNindex = i;

			print_index(db, bio_err, i, verbose > 1);
			}
		}
	
	VERBOSE BIO_printf(bio_err, "Database initialised\n");

	if (gNindex >= 0)
		{
		gNrow = sk_OPENSSL_PSTRING_value(db->db->data,gNindex);
		print_entry(db, bio_err, gNindex, verbose > 1, "Default g and N");
		}
	else if (maxgN > 0 && !SRP_get_default_gN(gN))
		{
		BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
		goto err;
		}
	else
		{
		VERBOSE BIO_printf(bio_err, "Database has no g N information.\n");
		gNrow = NULL;
		}
	

	VVERBOSE BIO_printf(bio_err,"Starting user processing\n");

	if (argc > 0)
		user = *(argv++) ;

	while (list_user || user)
		{
		int userindex = -1;
		if (user) 
			VVERBOSE BIO_printf(bio_err, "Processing user \"%s\"\n", user);
		if ((userindex = get_index(db, user, 'U')) >= 0)
			{
			print_user(db, bio_err, userindex, (verbose > 0) || list_user);
			}
		
		if (list_user)
			{
			if (user == NULL)
				{
				BIO_printf(bio_err,"List all users\n");

				for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
					{
					print_user(db,bio_err, i, 1);
					}
				list_user = 0;
				}
			else if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n",
					   user);
				errors++;
				}
			}
		else if (add_user)
			{
			if (userindex >= 0)
				{
				/* reactivation of a new user */
				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
				row[DB_srptype][0] = 'V';

				doupdatedb = 1;
				}
			else
				{
				char *row[DB_NUMBER] ; char *gNid;
				row[DB_srpverifier] = NULL;
				row[DB_srpsalt] = NULL;
				row[DB_srpinfo] = NULL;
				if (!(gNid = srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:gN,gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
					{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user);
						errors++;
						goto err;
					}
				row[DB_srpid] = BUF_strdup(user);
				row[DB_srptype] = BUF_strdup("v");
				row[DB_srpgN] = BUF_strdup(gNid);

				if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
					(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))) || 
					!update_index(db, bio_err, row))
					{
					if (row[DB_srpid]) OPENSSL_free(row[DB_srpid]);
					if (row[DB_srpgN]) OPENSSL_free(row[DB_srpgN]);
					if (row[DB_srpinfo]) OPENSSL_free(row[DB_srpinfo]);
					if (row[DB_srptype]) OPENSSL_free(row[DB_srptype]);
					if (row[DB_srpverifier]) OPENSSL_free(row[DB_srpverifier]);
					if (row[DB_srpsalt]) OPENSSL_free(row[DB_srpsalt]);
					goto err;
					}
				doupdatedb = 1;
				}
			}
		else if (modify_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err,"user \"%s\" does not exist, operation ignored.\n",user);
				errors++;
				}
			else
				{

				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				char type = row[DB_srptype][0];
				if (type == 'v')
					{
					BIO_printf(bio_err,"user \"%s\" already updated, operation ignored.\n",user);
					errors++;
					}
				else
					{
					char *gNid;

					if (row[DB_srptype][0] == 'V')
						{
						int user_gN;
						char **irow = NULL;
						VERBOSE BIO_printf(bio_err,"Verifying password for user \"%s\"\n",user);
						if ( (user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
							irow = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex);

 						if (!srp_verify_user(user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, bio_err, verbose))
							{
							BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user);
							errors++;
							goto err;
							}
						} 
					VERBOSE BIO_printf(bio_err,"Password for user \"%s\" ok.\n",user);

					if (!(gNid=srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:NULL, gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
						{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user);
						errors++;
						goto err;
						}

					row[DB_srptype][0] = 'v';
					row[DB_srpgN] = BUF_strdup(gNid);
 
					if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
						(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))))  
						goto err;

					doupdatedb = 1;
					}
				}
			}
		else if (delete_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user);
				errors++;
				}
			else
				{
				char **xpp = sk_OPENSSL_PSTRING_value(db->db->data,userindex);
				BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);

				xpp[DB_srptype][0] = 'R';
				
				doupdatedb = 1;
				}
			}
		if (--argc > 0)
			user = *(argv++) ;
		else
			{
			user = NULL;
			list_user = 0;
			}
		}

	VERBOSE BIO_printf(bio_err,"User procession done.\n");


	if (doupdatedb)
		{
		/* Lets check some fields */
		for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
			{
			pp = sk_OPENSSL_PSTRING_value(db->db->data,i);
	
			if (pp[DB_srptype][0] == 'v')
				{
				pp[DB_srptype][0] = 'V';
				print_user(db, bio_err, i, verbose);
				}
			}

		VERBOSE BIO_printf(bio_err, "Trying to update srpvfile.\n");
		if (!save_index(dbfile, "new", db)) goto err;
				
		VERBOSE BIO_printf(bio_err, "Temporary srpvfile created.\n");
		if (!rotate_index(dbfile, "new", "old")) goto err;

		VERBOSE BIO_printf(bio_err, "srpvfile updated.\n");
		}

	ret = (errors != 0);
err:
	if (errors != 0)
	VERBOSE BIO_printf(bio_err,"User errors %d.\n",errors);

	VERBOSE BIO_printf(bio_err,"SRP terminating with code %d.\n",ret);
	if(tofree)
		OPENSSL_free(tofree);
	if (ret) ERR_print_errors(bio_err);
	if (randfile) app_RAND_write_file(randfile, bio_err);
	if (conf) NCONF_free(conf);
	if (db) free_index(db);

	OBJ_cleanup();
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
int main(int Argc, char *Argv[])
	{
	ARGS arg;
#define PROG_NAME_SIZE	39
	char pname[PROG_NAME_SIZE+1];
	FUNCTION f,*fp;
	MS_STATIC const char *prompt;
	MS_STATIC char buf[1024];
	char *to_free=NULL;
	int n,i,ret=0;
	int argc;
	char **argv,*p;
	LHASH_OF(FUNCTION) *prog=NULL;
	long errline;
 
	arg.data=NULL;
	arg.count=0;

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

	if (TINYCLR_SSL_GETENV("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
		{
		if (!(0 == TINYCLR_SSL_STRCMP(TINYCLR_SSL_GETENV("OPENSSL_DEBUG_MEMORY"), "off")))
			{
			CRYPTO_malloc_debug_init();
			CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
			}
		else
			{
			/* OPENSSL_DEBUG_MEMORY=off */
			CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
			}
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
	if (TINYCLR_SSL_GETENV("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
		{
		CRYPTO_set_locking_callback(lock_dbg_cb);
		}

	apps_startup();

	/* Lets load up our environment a little */
	p=TINYCLR_SSL_GETENV("OPENSSL_CONF");
	if (p == NULL)
		p=TINYCLR_SSL_GETENV("SSLEAY_CONF");
	if (p == NULL)
		p=to_free=make_config_name();

	default_config_file=p;

	config=NCONF_new(NULL);
	i=NCONF_load(config,p,&errline);
	if (i == 0)
		{
		if (ERR_GET_REASON(ERR_peek_last_error())
		    == CONF_R_NO_SUCH_FILE)
			{
			BIO_printf(bio_err,
				   "WARNING: can't open config file: %s\n",p);
			ERR_clear_error();
			NCONF_free(config);
			config = NULL;
			}
		else
			{
			ERR_print_errors(bio_err);
			NCONF_free(config);
			TINYCLR_SSL_EXIT(1);
			}
		}

	prog=prog_init();

	/* first check the program name */
	program_name(Argv[0],pname,sizeof pname);

	f.name=pname;
	fp=lh_FUNCTION_retrieve(prog,&f);
	if (fp != NULL)
		{
		Argv[0]=pname;
		ret=fp->func(Argc,Argv);
		goto end;
		}

	/* ok, now check that there are not arguments, if there are,
	 * run with them, shifting the ssleay off the front */
	if (Argc != 1)
		{
		Argc--;
		Argv++;
		ret=do_cmd(prog,Argc,Argv);
		if (ret < 0) ret=0;
		goto end;
		}

	/* ok, lets enter the old 'OpenSSL>' mode */
	
	for (;;)
		{
		ret=0;
		p=buf;
		n=sizeof buf;
		i=0;
		for (;;)
			{
			p[0]='\0';
			if (i++)
				prompt=">";
			else	prompt="OpenSSL> ";
			TINYCLR_SSL_FPUTS(prompt,OPENSSL_TYPE__FILE_STDOUT);
			TINYCLR_SSL_FFLUSH(OPENSSL_TYPE__FILE_STDOUT);
			if (!TINYCLR_SSL_FGETS(p,n,OPENSSL_TYPE__FILE_STDIN))
				goto end;
			if (p[0] == '\0') goto end;
			i=TINYCLR_SSL_STRLEN(p);
			if (i <= 1) break;
			if (p[i-2] != '\\') break;
			i-=2;
			p+=i;
			n-=i;
			}
		if (!chopup_args(&arg,buf,&argc,&argv)) break;

		ret=do_cmd(prog,argc,argv);
		if (ret < 0)
			{
			ret=0;
			goto end;
			}
		if (ret != 0)
			BIO_printf(bio_err,"error in %s\n",argv[0]);
		(void)BIO_flush(bio_err);
		}
	BIO_printf(bio_err,"bad exit\n");
	ret=1;
end:
	if (to_free)
		OPENSSL_free(to_free);
	if (config != NULL)
		{
		NCONF_free(config);
		config=NULL;
		}
	if (prog != NULL) lh_FUNCTION_free(prog);
	if (arg.data != NULL) OPENSSL_free(arg.data);

	apps_shutdown();

	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err=NULL;
		}
	OPENSSL_EXIT(ret);
	}
Exemplo n.º 29
0
int openssl_main(int Argc, char *Argv[])
#endif
	{
	ARGS arg;
#define PROG_NAME_SIZE	39
	char pname[PROG_NAME_SIZE+1];
	FUNCTION f,*fp;
	MS_STATIC const char *prompt;
	MS_STATIC char buf[1024];
	char *to_free=NULL;
	int n,i,ret=0;
	int argc;
	char **argv,*p;
	LHASH *prog=NULL;
	long errline;

	arg.data=NULL;
	arg.count=0;

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
#ifdef SYMBIAN
        BIO_set_fp(bio_err,fp_stderr,BIO_NOCLOSE|BIO_FP_TEXT);
#else
        BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
#endif
	if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
		{
		if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))
			{
			CRYPTO_malloc_debug_init();
			CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
			}
		else
			{
			/* OPENSSL_DEBUG_MEMORY=off */
			CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
			}
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
	if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
		{
		CRYPTO_set_locking_callback(lock_dbg_cb);
		}

	apps_startup();

	/* Lets load up our environment a little */
	p=getenv("OPENSSL_CONF");
	if (p == NULL)
		p=getenv("SSLEAY_CONF");
	if (p == NULL)
		p=to_free=make_config_name();

	default_config_file=p;

	config=NCONF_new(NULL);
	i=NCONF_load(config,p,&errline);
	if (i == 0)
		{
		NCONF_free(config);
		config = NULL;
		ERR_clear_error();
		}

	prog=prog_init();

	/* first check the program name */
	program_name(Argv[0],pname,sizeof pname);

	f.name=pname;
	fp=(FUNCTION *)lh_retrieve(prog,&f);
	if (fp != NULL)
		{
		Argv[0]=pname;
		ret=fp->func(Argc,Argv);
		goto end;
		}

	/* ok, now check that there are not arguments, if there are,
	 * run with them, shifting the ssleay off the front */
	if (Argc != 1)
		{
		Argc--;
		Argv++;
		ret=do_cmd(prog,Argc,Argv);
		if (ret < 0) ret=0;
		goto end;
		}

	/* ok, lets enter the old 'OpenSSL>' mode */

	for (;;)
		{
		ret=0;
		p=buf;
		n=sizeof buf;
		i=0;
		for (;;)
			{
			p[0]='\0';
			if (i++)
				prompt=">";
			else	prompt="OpenSSL> ";
#ifndef SYMBIAN
			fputs(prompt,stdout);
			fflush(stdout);
			fgets(p,n,stdin);
#else
            fputs(prompt,stdout);
			fflush(stdout);
			fgets(p,n,stdin);

#endif
			if (p[0] == '\0') goto end;
			i=strlen(p);
			if (i <= 1) break;
			if (p[i-2] != '\\') break;
			i-=2;
			p+=i;
			n-=i;
			}
		if (!chopup_args(&arg,buf,&argc,&argv)) break;

		ret=do_cmd(prog,argc,argv);
		if (ret < 0)
			{
			ret=0;
			goto end;
			}
		if (ret != 0)
			BIO_printf(bio_err,"error in %s\n",argv[0]);
		(void)BIO_flush(bio_err);
		}
	BIO_printf(bio_err,"bad exit\n");
	ret=1;
end:
	if (to_free)
		OPENSSL_free(to_free);
	if (config != NULL)
		{
		NCONF_free(config);
		config=NULL;
		}
	if (prog != NULL) lh_free(prog);
	if (arg.data != NULL) OPENSSL_free(arg.data);

	apps_shutdown();

	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err=NULL;
		}

	return ret;
//	OPENSSL_EXIT(ret);
	}
Exemplo n.º 30
0
PKI_X509_EXTENSION *PKI_X509_EXTENSION_value_new_profile ( 
		PKI_X509_PROFILE *profile, PKI_CONFIG *oids, 
			PKI_CONFIG_ELEMENT *extNode, PKI_TOKEN *tk ) {

	/* TODO: Implement the extended version of the extensions, this
	   should allow better extensions management. That is, the value
	   will be encoded as:

		extName=@section

		[ section ]
		extName=value
		otherVal=val
		otherVal=val
		...

	   The corresponding XML should be:

		<pki:extension name=".." critical=".." >
		   <pki:value name="" type=".." tag=".."> .. </pki:value>
		   <pki:value name="" type=".." tag=".."> .. </pki:value>
		</pki:extension>

	  */

	PKI_CONFIG_ELEMENT *valNode = NULL;
	PKI_X509_EXTENSION *ret = NULL;
	PKI_X509_EXTENSION_VALUE *ext = NULL;

	xmlChar *type_s = NULL;
	xmlChar *tag_s = NULL;
	xmlChar *oid_s = NULL;
	xmlChar *value_s = NULL;
	xmlChar *name_s = NULL;
	xmlChar *crit_s = NULL;

	PKI_OID *oid = NULL;


	X509V3_CTX v3_ctx;
	CONF *conf = NULL;

	char *envValString = NULL;
	char *valString = NULL;
	int crit = 0;

	if( !profile || !extNode ) {
		PKI_log_debug("ERROR, no profile or extNode provided in "
				"PKI_X509_EXTENSION_value_new_profile()");
		return (NULL);
	}

	if((crit_s = xmlGetProp( extNode, BAD_CAST "critical" )) != NULL ) {
		if( strncmp_nocase( (char *) crit_s, "n", 1 ) == 0) {
			crit = 0;
		} else {
			crit = 1;
		}
	}

	if((name_s = xmlGetProp( extNode, BAD_CAST "name" )) == NULL ) {
		PKI_log_debug("ERROR, no name property in node %s", 
							extNode->name);
		if( crit_s ) xmlFree ( crit_s );
		return (NULL);
	}

	if ((oid = PKI_OID_get((char *) name_s)) == NULL)
	{
		if ((oid = PKI_CONFIG_OID_search(oids, (char *)name_s)) == NULL)
		{
			PKI_ERROR(PKI_ERR_OBJECT_CREATE, NULL);
			return NULL;
		}
	}
	else
	{
		PKI_OID_free ( oid );
	}

	/*
	int nid = NID_undef;
	if((nid = OBJ_sn2nid( (char *) name_s )) == NID_undef ) {
		PKI_OID *oid = NULL;

		oid = PKI_CONFIG_OID_search ( oids, (char *) name_s );
		if( !oid ) {
			PKI_log_debug( "ERROR, can not create object (%s)!",
				name_s );
			return( NULL );
		}
	}
	*/

	if ((valString = (char *) PKI_Malloc(BUFF_MAX_SIZE)) == NULL)
	{
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		if( name_s ) xmlFree ( name_s );
		if( crit_s ) xmlFree (crit_s);
		return( NULL );
	}

	memset( valString, 0, BUFF_MAX_SIZE );

	if( crit == 1 ) snprintf( valString, BUFF_MAX_SIZE -1, "%s", "critical" );

	for (valNode = extNode->children; valNode; valNode = valNode->next)
	{
		if ((valNode->type == XML_ELEMENT_NODE) &&
				((strncmp_nocase((char *)(valNode->name),"value",5)) == 0))
		{
			char tmp[BUFF_MAX_SIZE];

			type_s = xmlGetProp( valNode, BAD_CAST "type" );
			tag_s = xmlGetProp( valNode, BAD_CAST "tag" );
			oid_s = xmlGetProp( valNode, BAD_CAST "oid" );

			value_s = xmlNodeListGetString( profile, 
						valNode->xmlChildrenNode, 0);

			if( oid_s ) {
				/* Let's be sure the OID is created */
				if((oid = PKI_CONFIG_OID_search(oids, 
						(char *) value_s)) == NULL ) {
					PKI_log_debug ("WARNING, no oid "
						"created for %s!", oid_s );
				} else {
					PKI_OID_free ( oid );
				}
			}

			memset((unsigned char * )tmp, 0, BUFF_MAX_SIZE );

			if( tag_s ) {
				snprintf( tmp, BUFF_MAX_SIZE - 1, "%s;", 
					_ext_txt( tag_s ) );
			}

			if( type_s == NULL ) {
				if( !oid_s ) {
					strncat( tmp, (char *) value_s, 
							BUFF_MAX_SIZE - strlen( tmp ));
				} else {
					if( value_s && (strlen((char *) value_s) > 0) ) {
						strncat( tmp, (char *) oid_s, 
						 	BUFF_MAX_SIZE - strlen( tmp ) );
						strncat( tmp, ":", 
							BUFF_MAX_SIZE - strlen ( tmp ));
						strncat( tmp, (char *) value_s,
							BUFF_MAX_SIZE - strlen (tmp ));
					} else {
						strncat( tmp, "OID:", 
							BUFF_MAX_SIZE - strlen(tmp));
						strncat( tmp, (char *) oid_s, 
							BUFF_MAX_SIZE - strlen( tmp ));
					}
				}
			} else {
				strncat( tmp, (char *) _ext_txt(type_s), 
						BUFF_MAX_SIZE - strlen( tmp ));
				if( value_s && (strlen((char*)value_s) > 0) ) {
					if(strcmp_nocase( (char*) type_s, "ia5org")) {
					    strncat( tmp, ":", 
						BUFF_MAX_SIZE - strlen( tmp ));
					} else {
					    strncat( tmp, ",", 
						BUFF_MAX_SIZE - strlen( tmp ));
					}
					strncat( tmp, (char *) value_s, 
						BUFF_MAX_SIZE - strlen( tmp ));
				}
			}
				
			if( strlen( valString ) > 0 ) {
				strncat( valString, ",", BUFF_MAX_SIZE - 1);
			}

			strncat( valString, (char *) tmp, BUFF_MAX_SIZE - 1 );

			if( type_s ) xmlFree ( type_s );
			if( oid_s ) xmlFree ( oid_s );
			if( tag_s ) xmlFree ( tag_s );
			if( value_s ) xmlFree ( value_s );
        	}
	}
	//PKI_log_debug("INFO, Encoding %s=%s", name_s, valString);

	v3_ctx.db = NULL;
	v3_ctx.db_meth = NULL;
	v3_ctx.crl = NULL;
	v3_ctx.flags = 0;

	if ( tk ) {
		v3_ctx.issuer_cert  =  (X509 *)
			PKI_X509_get_value ( tk->cacert );
		v3_ctx.subject_cert =  (X509 *)
			PKI_X509_get_value ( tk->cert );
		v3_ctx.subject_req  =  (X509_REQ *)
			PKI_X509_get_value ( tk->req );
	} else {
		v3_ctx.issuer_cert = NULL;
		v3_ctx.subject_cert = NULL;
		v3_ctx.subject_req = NULL;
	}

	/* Sets the ctx.db and ctx.method */
	conf = NCONF_new( NULL );
	X509V3_set_nconf(&v3_ctx, conf);

	if((envValString = get_env_string( valString )) != NULL ) {
		PKI_log_debug("EXT STRING => %s=%s", name_s, envValString);
		ext = X509V3_EXT_conf(NULL, &v3_ctx, (char *) name_s, 
						(char *) envValString);
		PKI_Free ( envValString );
	} else {
		ext = X509V3_EXT_conf(NULL, &v3_ctx, (char *) name_s, 
						(char *) valString);
	}

	if( !ext ) {
		PKI_log_debug("EXT::ERR::%s",
			ERR_error_string(ERR_get_error(), NULL ));
		return NULL;
	}

	if(( ret = PKI_X509_EXTENSION_new()) == NULL ) {
		PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
		X509_EXTENSION_free ( ext );
		return NULL;
	}

	ret->value = ext;
	ret->oid = ext->object;

	if( name_s ) xmlFree ( name_s );
	if( crit_s ) xmlFree (crit_s );

	if( valString ) PKI_Free ( valString );
	if( conf ) NCONF_free ( conf );

	return ( ret );
}