Ejemplo n.º 1
0
void test1()
{
  char *       filename = "server/server.crt";
  X509 *       x509 = NULL;
  X509 *       rc = NULL;
  FILE *       fp = NULL;
  X509_NAME *  name = NULL;
  char         buf[1024];
  int          nid = NID_undef;
  size_t       name_len = 0;
  char         cnbuf[1024];

  assert( (fp = fopen(filename,"rb")) != NULL );
  assert( (rc = PEM_read_X509(fp, &x509, (pem_password_cb *)0, NULL)) != NULL );
  assert( (name = X509_get_subject_name(x509)) != NULL );

  X509_NAME_oneline(X509_get_subject_name(x509), buf, sizeof(buf));
  assert( strcmp(buf,"/C=HU/ST=Hungary/L=Budapest/O=BeckGround Ltd./[email protected]/[email protected]") == 0 );
  printf("%s\n",buf);

  assert( (nid = OBJ_txt2nid("commonName")) != NID_undef );
  assert( (name_len = X509_NAME_get_text_by_NID(name, nid, cnbuf, sizeof(cnbuf))) > 0 );
  assert( strcmp(cnbuf,"*****@*****.**") == 0 );
  printf("%s\n",cnbuf);

  X509_free(x509);
  rc = x509 = NULL;
  fclose( fp );
}
Ejemplo n.º 2
0
std::string genCommonName(X509* cert) {
  if (cert == nullptr) {
    return "";
  }

  X509_NAME* subject_name = nullptr;
  OSX_OPENSSL(subject_name = X509_get_subject_name(cert));
  if (subject_name == nullptr) {
    return "";
  }

  int nid = 0;
  OSX_OPENSSL(nid = OBJ_txt2nid("CN"));

  int index = 0;
  OSX_OPENSSL(index = X509_NAME_get_index_by_NID(subject_name, nid, -1));
  if (index == -1) {
    return "";
  }

  X509_NAME_ENTRY* commonNameEntry = nullptr;
  OSX_OPENSSL(commonNameEntry = X509_NAME_get_entry(subject_name, index));
  if (commonNameEntry == nullptr) {
    return "";
  }

  ASN1_STRING* commonNameData = nullptr;
  OSX_OPENSSL(commonNameData = X509_NAME_ENTRY_get_data(commonNameEntry));

  unsigned char* data = nullptr;
  OSX_OPENSSL(data = ASN1_STRING_data(commonNameData));
  return std::string(reinterpret_cast<char*>(data));
}
Ejemplo n.º 3
0
x509name NewX509::getX509name(int _throw)
{
	x509name x;
	int j, row, nid;

	try {
		for (j = 0; j<EXPLICIT_NAME_CNT; j++) {
			nid = name_nid[j];
			x.addEntryByNid(nid, name_ptr[j]->text());
		}
		row = extDNlist->rowCount();
		for (j=0; j<row; j++) {
			QStringList l = extDNlist->getRow(j);
			nid = OBJ_txt2nid(CCHAR(l[0]));
			x.addEntryByNid(nid, l[1]);
		}
	} catch (errorEx &err) {
		if (!err.isEmpty()) {
			if (_throw)
				throw err;
			else
				QMessageBox::warning(this, XCA_TITLE, err.getString());
		}
	}
	return x;
}
Ejemplo n.º 4
0
std::string genCommonName(X509* cert) {
  if (cert == nullptr) {
    return "";
  }

  auto subject_name = X509_get_subject_name(cert);
  if (subject_name == nullptr) {
    return "";
  }

  auto nid = OBJ_txt2nid("CN");
  auto index = X509_NAME_get_index_by_NID(subject_name, nid, -1);
  if (index == -1) {
    return "";
  }

  auto commonNameEntry = X509_NAME_get_entry(subject_name, index);
  if (commonNameEntry == nullptr) {
    return "";
  }

  auto commonNameData = X509_NAME_ENTRY_get_data(commonNameEntry);
  auto data = ASN1_STRING_data(commonNameData);
  return std::string(reinterpret_cast<char*>(data));
}
Ejemplo n.º 5
0
/*  get encryption parameters from crypto network settings
	FIXME For now we use environment var CRYPT_PARAMS as place to 
	store these settings. Actually, it is better to use engine control   command, read from configuration file to set them */
const struct gost_cipher_info *get_encryption_params(ASN1_OBJECT *obj)
	{
	int nid;
	struct gost_cipher_info *param;
	if (!obj)
		{
		const char * params = get_gost_engine_param(GOST_PARAM_CRYPT_PARAMS);
		if (!params || !strlen(params)) 
			return &gost_cipher_list[1];

		nid = OBJ_txt2nid(params);
		if (nid == NID_undef)
			{
			GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS,
				GOST_R_INVALID_CIPHER_PARAM_OID);
			return NULL;
			}	
		}
	else
		{
		nid= OBJ_obj2nid(obj);
		}
	for (param=gost_cipher_list;param->sblock!=NULL && param->nid!=nid; 
		 param++);
	if (!param->sblock)
		{
		GOSTerr(GOST_F_GET_ENCRYPTION_PARAMS,GOST_R_INVALID_CIPHER_PARAMS);
		return NULL;
		}	
	return param;
	}
Ejemplo n.º 6
0
static int pkey_gost_ec_ctrl_str_256(EVP_PKEY_CTX *ctx,
                                     const char *type, const char *value)
{
    int param_nid = 0;

    if (strcmp(type, param_ctrl_string) == 0) {
        if (!value) {
            return 0;
        }
        if (strlen(value) == 1) {
            switch (toupper((unsigned char)value[0])) {
            case 'A':
                param_nid = NID_id_GostR3410_2001_CryptoPro_A_ParamSet;
                break;
            case 'B':
                param_nid = NID_id_GostR3410_2001_CryptoPro_B_ParamSet;
                break;
            case 'C':
                param_nid = NID_id_GostR3410_2001_CryptoPro_C_ParamSet;
                break;
            case '0':
                param_nid = NID_id_GostR3410_2001_TestParamSet;
                break;
            default:
                return 0;
            }
        } else if ((strlen(value) == 2)
                   && (toupper((unsigned char)value[0]) == 'X')) {
            switch (toupper((unsigned char)value[1])) {
            case 'A':
                param_nid = NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet;
                break;
            case 'B':
                param_nid = NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet;
                break;
            default:
                return 0;
            }
        } else {
            R3410_ec_params *p = R3410_2001_paramset;
            param_nid = OBJ_txt2nid(value);
            if (param_nid == NID_undef) {
                return 0;
            }
            for (; p->nid != NID_undef; p++) {
                if (p->nid == param_nid)
                    break;
            }
            if (p->nid == NID_undef) {
                GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_256,
                        GOST_R_INVALID_PARAMSET);
                return 0;
            }
        }

        return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET,
                              param_nid, NULL);
    }
    return -2;
}
Ejemplo n.º 7
0
/*
 * Returns specified field of specified X509_NAME structure
 *
 * Common part of ssl_client_dn and ssl_issuer_dn functions.
 *
 * Parameter: X509_NAME *name - either subject or issuer of certificate
 * Parameter: text fieldName  - field name string like 'CN' or commonName
 *			  to be looked up in the OpenSSL ASN1 OID database
 *
 * Returns result of ASN1_STRING_to_text applied to appropriate
 * part of name
 */
Datum
X509_NAME_field_to_text(X509_NAME *name, text *fieldName)
{
	char	   *sp;
	char	   *string_fieldname;
	char	   *dp;
	size_t		name_len = VARSIZE(fieldName) - VARHDRSZ;
	int			nid,
				index,
				i;
	ASN1_STRING *data;

	string_fieldname = palloc(name_len + 1);
	sp = VARDATA(fieldName);
	dp = string_fieldname;
	for (i = 0; i < name_len; i++)
		*dp++ = *sp++;
	*dp = '\0';
	nid = OBJ_txt2nid(string_fieldname);
	if (nid == NID_undef)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid X.509 field name: \"%s\"",
						string_fieldname)));
	pfree(string_fieldname);
	index = X509_NAME_get_index_by_NID(name, nid, -1);
	if (index < 0)
		return (Datum) 0;
	data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, index));
	return ASN1_STRING_to_text(data);
}
static int
openssl_iostream_set(struct ssl_iostream *ssl_io,
		     const struct ssl_iostream_settings *set,
		     const char **error_r)
{
	const struct ssl_iostream_settings *ctx_set = ssl_io->ctx->set;
	int verify_flags;

	if (set->verbose)
		SSL_set_info_callback(ssl_io->ssl, openssl_info_callback);

       if (set->cipher_list != NULL &&
	    strcmp(ctx_set->cipher_list, set->cipher_list) != 0) {
		if (!SSL_set_cipher_list(ssl_io->ssl, set->cipher_list)) {
			*error_r = t_strdup_printf(
				"Can't set cipher list to '%s': %s",
				set->cipher_list, openssl_iostream_error());
			return -1;
		}
	}
	if (set->protocols != NULL) {
		SSL_clear_options(ssl_io->ssl, OPENSSL_ALL_PROTOCOL_OPTIONS);
		SSL_set_options(ssl_io->ssl,
				openssl_get_protocol_options(set->protocols));
	}

	if (set->cert != NULL && strcmp(ctx_set->cert, set->cert) != 0) {
		if (openssl_iostream_use_certificate(ssl_io, set->cert, error_r) < 0)
			return -1;
	}
	if (set->key != NULL && strcmp(ctx_set->key, set->key) != 0) {
		if (openssl_iostream_use_key(ssl_io, set, error_r) < 0)
			return -1;
	}
	if (set->verify_remote_cert) {
		if (ssl_io->ctx->client_ctx)
			verify_flags = SSL_VERIFY_NONE;
		else
			verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
		SSL_set_verify(ssl_io->ssl, verify_flags,
			       openssl_iostream_verify_client_cert);
	}

	if (set->cert_username_field != NULL) {
		ssl_io->username_nid = OBJ_txt2nid(set->cert_username_field);
		if (ssl_io->username_nid == NID_undef) {
			*error_r = t_strdup_printf(
				"Invalid cert_username_field: %s",
				set->cert_username_field);
			return -1;
		}
	} else {
		ssl_io->username_nid = ssl_io->ctx->username_nid;
	}

	ssl_io->verbose = set->verbose;
	ssl_io->verbose_invalid_cert = set->verbose_invalid_cert || set->verbose;
	ssl_io->require_valid_cert = set->require_valid_cert;
	return 0;
}
Ejemplo n.º 9
0
static int pkey_ec_ctrl_str(EVP_PKEY_CTX *ctx,
                            const char *type, const char *value)
{
    if (strcmp(type, "ec_paramgen_curve") == 0) {
        int nid;
        nid = EC_curve_nist2nid(value);
        if (nid == NID_undef)
            nid = OBJ_sn2nid(value);
        if (nid == NID_undef)
            nid = OBJ_ln2nid(value);
        if (nid == NID_undef) {
            ECerr(EC_F_PKEY_EC_CTRL_STR, EC_R_INVALID_CURVE);
            return 0;
        }
        return EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, nid);
#ifndef OPENSSL_NO_SM2
    } else if (!strcmp(type, "ec_scheme")) {
        int scheme;
        if (!strcmp(value, "secg"))
            scheme = NID_secg_scheme;
        else if (!strcmp(value, "sm2"))
            scheme = NID_sm_scheme;
        else
            return -2;
        return EVP_PKEY_CTX_set_ec_scheme(ctx, scheme);
    } else if (!strcmp(type, "signer_id")) {
        return EVP_PKEY_CTX_set_signer_id(ctx, value);
    } else if (!strcmp(type, "ec_encrypt_param")) {
        int encrypt_param;
        if (!(encrypt_param = OBJ_txt2nid(value))) {
            ECerr(EC_F_PKEY_EC_CTRL_STR, EC_R_INVALID_EC_ENCRYPT_PARAM);
            return 0;
        }
        return EVP_PKEY_CTX_set_ec_encrypt_param(ctx, encrypt_param);
#endif
    } else if (strcmp(type, "ec_param_enc") == 0) {
        int param_enc;
        if (strcmp(value, "explicit") == 0)
            param_enc = 0;
        else if (strcmp(value, "named_curve") == 0)
            param_enc = OPENSSL_EC_NAMED_CURVE;
        else
            return -2;
        return EVP_PKEY_CTX_set_ec_param_enc(ctx, param_enc);
    } else if (strcmp(type, "ecdh_kdf_md") == 0) {
        const EVP_MD *md;
        if ((md = EVP_get_digestbyname(value)) == NULL) {
            ECerr(EC_F_PKEY_EC_CTRL_STR, EC_R_INVALID_DIGEST);
            return 0;
        }
        return EVP_PKEY_CTX_set_ecdh_kdf_md(ctx, md);
    } else if (strcmp(type, "ecdh_cofactor_mode") == 0) {
        int co_mode;
        co_mode = atoi(value);
        return EVP_PKEY_CTX_set_ecdh_cofactor_mode(ctx, co_mode);
    }

    return -2;
}
Ejemplo n.º 10
0
/*
 * call-seq:
 *    PKCS12.create(pass, name, key, cert [, ca, [, key_pbe [, cert_pbe [, key_iter [, mac_iter [, keytype]]]]]])
 *
 * === Parameters
 * * +pass+ - string
 * * +name+ - A string describing the key.
 * * +key+ - Any PKey.
 * * +cert+ - A X509::Certificate.
 * * * The public_key portion of the certificate must contain a valid public key.
 * * * The not_before and not_after fields must be filled in.
 * * +ca+ - An optional array of X509::Certificate's.
 * * +key_pbe+ - string
 * * +cert_pbe+ - string
 * * +key_iter+ - integer
 * * +mac_iter+ - integer
 * * +keytype+ - An integer representing an MSIE specific extension.
 *
 * Any optional arguments may be supplied as nil to preserve the OpenSSL defaults.
 *
 * See the OpenSSL documentation for PKCS12_create().
 */
static VALUE
ossl_pkcs12_s_create(int argc, VALUE *argv, VALUE self)
{
    VALUE pass, name, pkey, cert, ca, key_nid, cert_nid, key_iter, mac_iter, keytype;
    VALUE obj;
    char *passphrase, *friendlyname;
    EVP_PKEY *key;
    X509 *x509;
    STACK_OF(X509) *x509s;
    int nkey = 0, ncert = 0, kiter = 0, miter = 0, ktype = 0;
    PKCS12 *p12;

    rb_scan_args(argc, argv, "46", &pass, &name, &pkey, &cert, &ca, &key_nid, &cert_nid, &key_iter, &mac_iter, &keytype);
    passphrase = NIL_P(pass) ? NULL : StringValuePtr(pass);
    friendlyname = NIL_P(name) ? NULL : StringValuePtr(name);
    key = GetPKeyPtr(pkey);
    x509 = GetX509CertPtr(cert);
    x509s = NIL_P(ca) ? NULL : ossl_x509_ary2sk(ca);
/* TODO: make a VALUE to nid function */
    if (!NIL_P(key_nid)) {
        if ((nkey = OBJ_txt2nid(StringValuePtr(key_nid))) == NID_undef)
            rb_raise(rb_eArgError, "Unknown PBE algorithm %s", StringValuePtr(key_nid));
    }
    if (!NIL_P(cert_nid)) {
        if ((ncert = OBJ_txt2nid(StringValuePtr(cert_nid))) == NID_undef)
            rb_raise(rb_eArgError, "Unknown PBE algorithm %s", StringValuePtr(cert_nid));
    }
    if (!NIL_P(key_iter))
        kiter = NUM2INT(key_iter);
    if (!NIL_P(mac_iter))
        miter = NUM2INT(mac_iter);
    if (!NIL_P(keytype))
        ktype = NUM2INT(keytype);

    p12 = PKCS12_create(passphrase, friendlyname, key, x509, x509s,
                        nkey, ncert, kiter, miter, ktype);
    sk_X509_pop_free(x509s, X509_free);
    if(!p12) ossl_raise(ePKCS12Error, NULL);
    WrapPKCS12(cPKCS12, obj, p12);

    ossl_pkcs12_set_key(obj, pkey);
    ossl_pkcs12_set_cert(obj, cert);
    ossl_pkcs12_set_ca_certs(obj, ca);

    return obj;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[]) 
{
  struct vomsdata *vd = VOMS_Init(NULL, NULL);
  int error = 0;
  BIO *in = NULL;
  char *of = argv[1];
  X509 *x = NULL;
  int nid = -1;
  int index = -1;
  X509_EXTENSION *ext = NULL;

  if (vd) {
    in = BIO_new(BIO_s_file());
    if (in) {
      if (BIO_read_filename(in, of) > 0) {
        x = PEM_read_bio_X509(in, NULL, 0, NULL);
        if(!x) {
          printf("cannot read proxy:%s\n",of);
          exit(1);
        }

        nid = OBJ_txt2nid("acseq");
        index = X509_get_ext_by_NID(x, nid, -1);

        if (index >= 0) {
          ext = X509_get_ext(x, index);
    
          if (ext) {
            if (VOMS_RetrieveEXT(ext,  vd, &error)) {
              struct voms *voms = VOMS_DefaultData(vd, &error);
              
              if (voms) {
                char **fqans = voms->fqan;
                
                while (*fqans) {
                  printf("fqan: %s\n", *fqans++);
                }

                exit(0);
              }
              else {
                printf("no voms data found.");
                exit(1);
              }
            }
            else {
              printf("Error1 is: %s\n", VOMS_ErrorMessage(vd, error, NULL, 0));
              exit(1);
            }
          }
        }
        else
          printf("No extension found");
      }
    }
  }
  exit(1);
}
RTDECL(PCRTCRDIGESTDESC) RTCrDigestFindByObjIdString(const char *pszObjId, void **ppvOpaque)
{
    if (ppvOpaque)
        *ppvOpaque = NULL;

    /*
     * Primary OIDs.
     */
    uint32_t i = RT_ELEMENTS(g_apDigestOps);
    while (i-- > 0)
        if (strcmp(g_apDigestOps[i]->pszObjId, pszObjId) == 0)
            return g_apDigestOps[i];

    /*
     * Alias OIDs.
     */
    i = RT_ELEMENTS(g_apDigestOps);
    while (i-- > 0)
    {
        const char * const *ppszAliases = g_apDigestOps[i]->papszObjIdAliases;
        if (ppszAliases)
            for (; *ppszAliases; ppszAliases++)
                if (strcmp(*ppszAliases, pszObjId) == 0)
                    return g_apDigestOps[i];
    }

#ifdef IPRT_WITH_OPENSSL
    /*
     * Try EVP and see if it knows the algorithm.
     */
    if (ppvOpaque)
    {
        rtCrOpenSslInit();
        int iAlgoNid = OBJ_txt2nid(pszObjId);
        if (iAlgoNid != NID_undef)
        {
            const char *pszAlogSn = OBJ_nid2sn(iAlgoNid);
            const EVP_MD *pEvpMdType = EVP_get_digestbyname(pszAlogSn);
            if (pEvpMdType)
            {
                /*
                 * Return the OpenSSL provider descriptor and the EVP_MD address.
                 */
# if OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(LIBRESSL_VERSION_NUMBER)
                Assert(EVP_MD_block_size(pEvpMdType));
# else
                Assert(pEvpMdType->md_size);
# endif
                *ppvOpaque = (void *)pEvpMdType;
                return &g_rtCrDigestOpenSslDesc;
            }
        }
    }
#endif
    return NULL;
}
Ejemplo n.º 13
0
int
ressl_config_set_ecdhcurve(struct ressl_config *config, const char *name)
{
	int nid = NID_undef;

	if (name != NULL && (nid = OBJ_txt2nid(name)) == NID_undef)
		return (-1);

	config->ecdhcurve = nid;
	return (0);
}
Ejemplo n.º 14
0
static char *__apn_cert_entry_value_string_by_nib(X509_NAME *name, const char * const nid_str) {
    int nid = OBJ_txt2nid(nid_str);
    int index = X509_NAME_get_index_by_NID(name, nid, -1);
    if(index != -1) {
        X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, index);
        const unsigned char *entry_value = ASN1_STRING_data(X509_NAME_ENTRY_get_data(entry));
        if(entry_value) {
            return apn_strndup((const char *)entry_value, strlen((const char *)entry_value));
        }
    }
    return NULL;
}
Ejemplo n.º 15
0
/**
 * Constructor.
 * @param p the secure server port.
 * @param b the backlog, that is the maximum number of outstanding connection requests.
 */
GSISocketServer::GSISocketServer(int p, void *l, int b, bool m) :
  own_subject(""), own_ca(""), peer_subject(""), 
  peer_ca(""), peer_serial(""), own_key(NULL), own_cert(NULL), 
  peer_cert(NULL), own_stack(NULL), peer_stack(NULL), 
  ssl(NULL), ctx(NULL), conn(NULL), pvd(NULL), cacertdir(NULL),
  upkey(NULL), ucert(NULL), error(""),
  port(p), opened(false), sck(-1), backlog(b), newsock(-1), timeout(30),
  newopened(false), mustclose(m), logh(l)
{
  if (OBJ_txt2nid("UID") == NID_undef)
    OBJ_create("0.9.2342.19200300.100.1.1","USERID","userId");
}
Ejemplo n.º 16
0
static
bool extract_x509_extension(X509 *cert, char *fieldname, char *out, int size)
{
  bool retval = false;
  X509_EXTENSION *pExt;
  char *buf = 0;
  int length = 0;
  GENERAL_NAMES *extensions;
  int nid = OBJ_txt2nid(fieldname);

  extensions = (GENERAL_NAMES *)X509_get_ext_d2i(cert, nid, NULL, NULL);
  if ( extensions )
    {
      int numalts;
      int i;
      /* get amount of alternatives,
       * RFC2459 claims there MUST be at least
       * one, but we don't depend on it...
       */

      numalts = sk_GENERAL_NAME_num(extensions);

      /* loop through all alternatives */
      for (i=0; i<numalts; i++)
        {
          /* get a handle to alternative name number i */
          const GENERAL_NAME *name = sk_GENERAL_NAME_value (extensions, i );

          switch (name->type)
            {
              case GEN_EMAIL:
                ASN1_STRING_to_UTF8((unsigned char**)&buf, name->d.ia5);
                if ( strlen (buf) != name->d.ia5->length )
                  {
                    msg (D_TLS_ERRORS, "ASN1 ERROR: string contained terminating zero");
                    OPENSSL_free (buf);
                  } else {
                    strncpynt(out, buf, size);
                    OPENSSL_free(buf);
                    retval = true;
                  }
                break;
              default:
                msg (D_TLS_ERRORS, "ASN1 ERROR: can not handle field type %i",
                     name->type);
                break;
            }
          }
        sk_GENERAL_NAME_free (extensions);
    }
  return retval;
}
Ejemplo n.º 17
0
PCRTCRPKIXSIGNATUREDESC RTCrPkixSignatureFindByObjIdString(const char *pszObjId, void **ppvOpaque)
{
    if (ppvOpaque)
        *ppvOpaque = NULL;

    /*
     * Primary OIDs.
     */
    uint32_t i = RT_ELEMENTS(g_apPkixSignatureDescriptors);
    while (i-- > 0)
        if (strcmp(g_apPkixSignatureDescriptors[i]->pszObjId, pszObjId) == 0)
            return g_apPkixSignatureDescriptors[i];

    /*
     * Alias OIDs.
     */
    i = RT_ELEMENTS(g_apPkixSignatureDescriptors);
    while (i-- > 0)
    {
        const char * const *ppszAliases = g_apPkixSignatureDescriptors[i]->papszObjIdAliases;
        if (ppszAliases)
            for (; *ppszAliases; ppszAliases++)
                if (strcmp(*ppszAliases, pszObjId) == 0)
                    return g_apPkixSignatureDescriptors[i];
    }

#if 0//def IPRT_WITH_OPENSSL
    /*
     * Try EVP and see if it knows the algorithm.
     */
    if (ppvOpaque)
    {
        rtCrOpenSslInit();
        int iAlgoNid = OBJ_txt2nid(pszObjId);
        if (iAlgoNid != NID_undef)
        {
            const char *pszAlogSn = OBJ_nid2sn(iAlgoNid);
            const EVP_MD *pEvpMdType = EVP_get_digestbyname(pszAlogSn);
            if (pEvpMdType)
            {
                /*
                 * Return the OpenSSL provider descriptor and the EVP_MD address.
                 */
                Assert(pEvpMdType->md_size);
                *ppvOpaque = (void *)pEvpMdType;
                return &g_rtCrPkixSignatureOpenSslDesc;
            }
        }
    }
#endif
    return NULL;
}
Ejemplo n.º 18
0
/**
 * @ingroup proxypolicy
 *
 * Allocates and initializes a new PROXYPOLICY structure.
 *
 * @return pointer to the new PROXYPOLICY
 */
PROXYPOLICY * PROXYPOLICY_new()
{
    ASN1_CTX                            c;
    PROXYPOLICY *                       ret;

    ret = NULL;

    M_ASN1_New_Malloc(ret, PROXYPOLICY);
    ret->policy_language = OBJ_nid2obj(OBJ_txt2nid(IMPERSONATION_PROXY_OID));
    ret->policy = NULL;
    return (ret);
    M_ASN1_New_Error(ASN1_F_PROXYPOLICY_NEW);
}
Ejemplo n.º 19
0
void genCommonName(X509* cert,
                   std::string& subject,
                   std::string& common_name,
                   std::string& issuer) {
  if (cert == nullptr) {
    return;
  }

  {
    X509_NAME* issuerName = X509_get_issuer_name(cert);
    if (issuerName != nullptr) {
      // Generate the string representation of the issuer.
      char* issuerBytes = X509_NAME_oneline(issuerName, nullptr, 0);
      if (issuerBytes != nullptr) {
        issuer = std::string(issuerBytes);
        OPENSSL_free(issuerBytes);
      }
    }
  }

  X509_NAME* subjectName = X509_get_subject_name(cert);
  if (subjectName == nullptr) {
    return;
  }

  {
    // Generate the string representation of the subject.
    char* subjectBytes = X509_NAME_oneline(subjectName, nullptr, 0);
    if (subjectBytes != nullptr) {
      subject = std::string(subjectBytes);
      OPENSSL_free(subjectBytes);
    }
  }

  int nid = OBJ_txt2nid("CN");

  int index = X509_NAME_get_index_by_NID(subjectName, nid, -1);
  if (index == -1) {
    return;
  }

  X509_NAME_ENTRY* commonNameEntry = X509_NAME_get_entry(subjectName, index);
  if (commonNameEntry == nullptr) {
    return;
  }

  ASN1_STRING* commonNameData = X509_NAME_ENTRY_get_data(commonNameEntry);

  unsigned char* data = ASN1_STRING_data(commonNameData);
  common_name = std::string(reinterpret_cast<char*>(data));
}
Ejemplo n.º 20
0
static char *extract_cn(X509_NAME *subj)
{
	int nid;
	int index;
	ASN1_STRING *d;
	X509_NAME_ENTRY *e;

	nid=OBJ_txt2nid("CN");
	if((index=X509_NAME_get_index_by_NID(subj, nid, -1))<0
	  || !(e=X509_NAME_get_entry(subj, index))
	  || !(d=X509_NAME_ENTRY_get_data(e)))
		return NULL;
	return (char *)ASN1_STRING_data(d);
}
Ejemplo n.º 21
0
int
tls_config_set_ecdhecurve(struct tls_config *config, const char *name)
{
    int nid;

    if (name == NULL || strcasecmp(name, "none") == 0)
        nid = NID_undef;
    else if (strcasecmp(name, "auto") == 0)
        nid = -1;
    else if ((nid = OBJ_txt2nid(name)) == NID_undef)
        return (-1);

    config->ecdhecurve = nid;

    return (0);
}
Ejemplo n.º 22
0
/** Return a newly allocated X509 name with commonName <b>cname</b>. */
static X509_NAME *
tor_x509_name_new(const char *cname)
{
  int nid;
  X509_NAME *name;
  if (!(name = X509_NAME_new()))
    return NULL;
  if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
                                   (unsigned char*)cname, -1, -1, 0)))
    goto error;
  return name;
 error:
  X509_NAME_free(name);
  return NULL;
}
Ejemplo n.º 23
0
static void parse_otherName_value(apr_pool_t *p, ASN1_TYPE *value,
                                  const char *onf, apr_array_header_t **entries)
{
    const char *str;
    int nid = onf ? OBJ_txt2nid(onf) : NID_undef;

    if (!value || (nid == NID_undef) || !*entries)
       return;

    /* 
     * Currently supported otherName forms (values for "onf"):
     * "msUPN" (1.3.6.1.4.1.311.20.2.3): Microsoft User Principal Name
     * "id-on-dnsSRV" (1.3.6.1.5.5.7.8.7): SRVName, as specified in RFC 4985
     */
    if ((nid == NID_ms_upn) && (value->type == V_ASN1_UTF8STRING) &&
        (str = asn1_string_to_utf8(p, value->value.utf8string))) {
        APR_ARRAY_PUSH(*entries, const char *) = str;
    } else if (strEQ(onf, "id-on-dnsSRV") &&
Ejemplo n.º 24
0
static X509 *
getcert(void)
{
	/* Dummy code to make a quick-and-dirty valid certificate with
	   OpenSSL.  Don't copy this code into your own program! It does a
	   number of things in a stupid and insecure way. */
	X509 *x509 = NULL;
	X509_NAME *name = NULL;
	EVP_PKEY *key = getkey();
	int nid;
	time_t now = time(NULL);

	tt_assert(key);

	x509 = X509_new();
	tt_assert(x509);
	tt_assert(0 != X509_set_version(x509, 2));
	tt_assert(0 != ASN1_INTEGER_set(X509_get_serialNumber(x509),
		(long)now));

	name = X509_NAME_new();
	tt_assert(name);
	nid = OBJ_txt2nid("commonName");
	tt_assert(NID_undef != nid);
	tt_assert(0 != X509_NAME_add_entry_by_NID(
		    name, nid, MBSTRING_ASC, (unsigned char*)"example.com",
		    -1, -1, 0));

	X509_set_subject_name(x509, name);
	X509_set_issuer_name(x509, name);

	X509_time_adj(X509_get_notBefore(x509), 0, &now);
	now += 3600;
	X509_time_adj(X509_get_notAfter(x509), 0, &now);
	X509_set_pubkey(x509, key);
	tt_assert(0 != X509_sign(x509, key, EVP_sha1()));

	return x509;
end:
	X509_free(x509);
	return NULL;
}
Ejemplo n.º 25
0
static int pkey_gost_ec_ctrl_str_512(EVP_PKEY_CTX *ctx,
                                     const char *type, const char *value)
{
    int param_nid = NID_undef;

    if (strcmp(type, param_ctrl_string))
        return -2;

    if (!value)
        return 0;

    if (strlen(value) == 1) {
        switch (toupper((unsigned char)value[0])) {
        case 'A':
            param_nid = NID_id_tc26_gost_3410_2012_512_paramSetA;
            break;

        case 'B':
            param_nid = NID_id_tc26_gost_3410_2012_512_paramSetB;
            break;

        default:
            return 0;
        }
    } else {
        R3410_ec_params *p = R3410_2012_512_paramset;
        param_nid = OBJ_txt2nid(value);
        if (param_nid == NID_undef)
            return 0;

        while (p->nid != NID_undef && p->nid != param_nid)
            p++;

        if (p->nid == NID_undef) {
            GOSTerr(GOST_F_PKEY_GOST_EC_CTRL_STR_512,
                    GOST_R_INVALID_PARAMSET);
            return 0;
        }
    }

    return pkey_gost_ctrl(ctx, EVP_PKEY_CTRL_GOST_PARAMSET, param_nid, NULL);
}
Ejemplo n.º 26
0
void
x509_track_add (const struct x509_track **ll_head, const char *name, int msglevel, struct gc_arena *gc)
{
  struct x509_track *xt;
  ALLOC_OBJ_CLEAR_GC (xt, struct x509_track, gc);
  if (*name == '+')
    {
      xt->flags |= XT_FULL_CHAIN;
      ++name;
    }
  xt->name = name;
  xt->nid = OBJ_txt2nid(name);
  if (xt->nid != NID_undef)
    {
      xt->next = *ll_head;
      *ll_head = xt;
    }
  else
    msg(msglevel, "x509_track: no such attribute '%s'", name);
}
Ejemplo n.º 27
0
/*
 * Extract a field from an X509 subject name.
 *
 * Example:
 *
 * /C=US/ST=CO/L=Denver/O=ORG/CN=First-CN/CN=Test-CA/[email protected]
 *
 * The common name is 'Test-CA'
 *
 * Return true on success, false on error (insufficient buffer size in 'out'
 * to contain result is grounds for error).
 */
static result_t
extract_x509_field_ssl (X509_NAME *x509, const char *field_name, char *out,
    int size)
{
  int lastpos = -1;
  int tmp = -1;
  X509_NAME_ENTRY *x509ne = 0;
  ASN1_STRING *asn1 = 0;
  unsigned char *buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
  int nid = OBJ_txt2nid((char *)field_name);

  ASSERT (size > 0);
  *out = '\0';
  do {
    lastpos = tmp;
    tmp = X509_NAME_get_index_by_NID(x509, nid, lastpos);
  } while (tmp > -1);

  /* Nothing found */
  if (lastpos == -1)
    return FAILURE;

  x509ne = X509_NAME_get_entry(x509, lastpos);
  if (!x509ne)
    return FAILURE;

  asn1 = X509_NAME_ENTRY_get_data(x509ne);
  if (!asn1)
    return FAILURE;
  tmp = ASN1_STRING_to_UTF8(&buf, asn1);
  if (tmp <= 0)
    return FAILURE;

  strncpynt(out, (char *)buf, size);

  {
    const result_t ret = (strlen ((char *)buf) < size) ? SUCCESS: FAILURE;
    OPENSSL_free (buf);
    return ret;
  }
}
Ejemplo n.º 28
0
/*
 * Set attribute
 *
 * Arguments: self  - The X509Name object
 *            name  - The attribute name
 *            value - The value to set
 */
static int
crypto_X509Name_setattr(crypto_X509NameObj *self, char *name, PyObject *value)
{
    int nid;
    int result;
    char *buffer;

    if ((nid = OBJ_txt2nid(name)) == NID_undef)
    {
        PyErr_SetString(PyExc_AttributeError, "No such attribute");
        return -1;
    }

    /* Something of a hack to get nice unicode behaviour */
    if (!PyArg_Parse(value, "es:setattr", "utf-8", &buffer))
        return -1;

    result = set_name_by_nid(self->x509_name, nid, buffer);
    PyMem_Free(buffer);
    return result;
}
Ejemplo n.º 29
0
/** Return a newly allocated X509 name with commonName <b>cname</b>. */
static X509_NAME *
tor_x509_name_new(const char *cname)
{
  int nid;
  X509_NAME *name;
  /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
  if (!(name = X509_NAME_new()))
    return NULL;
  if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
  if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
                                   (unsigned char*)cname, -1, -1, 0)))
    goto error;
  /* LCOV_EXCL_BR_STOP */
  return name;

  /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
 error:
  X509_NAME_free(name);
  return NULL;
  /* LCOV_EXCL_STOP */
}
Ejemplo n.º 30
0
/*
 * Returns specified field of specified X509_NAME structure
 *
 * Common part of ssl_client_dn and ssl_issuer_dn functions.
 *
 * Parameter: X509_NAME *name - either subject or issuer of certificate
 * Parameter: text fieldName  - field name string like 'CN' or commonName
 *			  to be looked up in the OpenSSL ASN1 OID database
 *
 * Returns result of ASN1_STRING_to_text applied to appropriate
 * part of name
 */
datum_t
X509_NAME_field_to_text(X509_NAME *name, text *fieldName)
{
	char	   *string_fieldname;
	int			nid,
				index;
	ASN1_STRING *data;

	string_fieldname = text_to_cstring(fieldName);
	nid = OBJ_txt2nid(string_fieldname);
	if (nid == NID_undef)
		ereport(ERROR,
				(errcode(E_INVALID_PARAMETER_VALUE),
				 errmsg("invalid X.509 field name: \"%s\"",
						string_fieldname)));
	pfree(string_fieldname);
	index = X509_NAME_get_index_by_NID(name, nid, -1);
	if (index < 0)
		return (datum_t) 0;
	data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, index));
	return ASN1_STRING_to_text(data);
}