iamcool76
iamcool76

Reputation: 53

Parsing a DN from certificate in pem format (correct order)

I have seen a few posts related to parsing DN from a certificate in PEM format. I am writing a UNIX script that will read the pem files in a given path and spits out their corresponding Distinguished Name (DN) in the correct order. Created a simple script but the command that parses the pem file within the script is..

openssl x509 -in <file name.pem> -noout -subject

My confusion is when I run the above command, it spits the DN in this order starting with /C=US/ST=...but I know for a fact that the certificate DN starts with "CN=" which is exact reverse of what the command is spitting out. I am having a hard time trusting which command to run that gives me the exact order because I use that order to authenticate the user and if I onboard with the wrong order, requests will not be authorized and it defeats the purpose.

Upvotes: 5

Views: 7811

Answers (1)

jmd
jmd

Reputation: 1051

The order of the component of the DN is a matter of convention.
The physical order inside the binary DER encoding is the one OpenSSL shows you here.
OTOH the reverted order you expected is the one that a majority of tools use and that was normalized in RFC 2253.

This "/C=US/ST=..." format is the old OpenSSL one and now obsolete. If that's the one you get by default with OpenSSL, then you're using a very old version and should probably replace it with a more recent one.

In order to control how OpenSSL will display the subject, you need to use the -nameopt option. The value you can use are :
-nameopt rfc2253 : the order you wish, and the name will be "CN=xxx,OU=xxx,ST=xxx,C=FR" (no space, reverse order).
-nameopt oneline : the name will be "C = FR, ST = xxx , OU = xxx , CN = xxx".
-nameopt compat : the name will be "/C=US/ST=xxx/OU=xxx/CN=xxx" (without the space).

One more thing, if you compare the string of the DN to authenticate a client, the only way to get a reasonably reliable result is to use the exact same tool to generate it initially and when you verify it. As soon as a DN contains a less usual element, there's too many variations between tools to reliably get the same string representation of the DN if not using the exact same tool at the same version.

Upvotes: 8

Related Questions