On Sun, Apr 06, 2008 at 01:24:28AM +0200, Till Elsner wrote:

> is there any simple way to get the common name out of an certificate
> loaded to an X509 object via PEM_read_X509?


It is easy to get *a* common name, usually there is only one. More
interesting questions arise should the certificate's subject DN contain
multiple CommonName elements. Also, X509v3 TLS server certificates can
(and should, but often don't) contain subjectAlternativeName entries with
that include at least the subject CN and perhaps additional (typically
DNS) names.

To parse subjectAlternativeName entries:

X509 *cert;
STACK_OF(GENERAL_NAME) * gens;
const GENERAL_NAME *gn;
int num;
int len;
char *dnsname;

gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0);
num = sk_GENERAL_NAME_num(gens);

for (i = 0; i < num; ++i) {
gn = sk_GENERAL_NAME_value(gens, i);
...
if (gn->type != GEN_DNS)
/* fatal error */
if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING)
/* malformed cert */

dnsname = (char *) ASN1_STRING_data(gn->d.ia5);
len = ASN1_STRING_length(gn->d.ia5);

#define TRIM0(s, l) do { while ((l) > 0 && (s)[(l)-1] == 0) --(l); } while (0)
TRIM0(dnsname, len);

if (len != strlen(dnsname))
/* malformed cert */
}

To parse the (first or should it be last) CommonName in the subject DN:

X509_NAME *subject;
int pos;
X509_NAME_ENTRY *entry;
ASN1_STRING *entry_str;
int len;
unsigned char *utf;

subject = X509_get_subject_name(cert);
pos = X509_NAME_get_index_by_NID(subject, NID_commonName, -1);

if (pos < 0)
/* No Common Name */

if (X509_NAME_get_index_by_NID(name, nid, pos) >= 0)
/* Multiple common names, OK? or not? */

if ((entry = X509_NAME_get_entry(name, pos)) == 0)
/* fatal error */

if ((entry_str = X509_NAME_ENTRY_get_data(entry)) == 0)
/* fatal error */

/* Canonicalize to UTF-8 and validate */
len = ASN1_STRING_to_UTF8(&utf, entry_str)

TRIM0(utf, len);
if (len != strlen((char *) utf))
/* malformed cert */

--
Viktor.
__________________________________________________ ____________________
OpenSSL Project http://www.openssl.org
User Support Mailing List openssl-users@openssl.org
Automated List Manager majordomo@openssl.org