Accessing CSR extension stack in M2Crypto
Question
I have a certificate signing request with an extension stack added. When building a certificate based on this request, I would like to be able to access that stack to use in creating the final certificate.
However, while M2Crypto.X509.X509
has a number of helpers for accessing extensions (get_ext
, get_ext_at
and the like), M2Crypto.X509.Request
appears to provide only a member for adding extensions, but no way to inspect the extensions already associated with a given object.
Am I missing something here?
Solution
You're right.
The current version of M2Crypto doesn't expose the necessary OpenSSL interface - X509_REQ_get_extensions
.
Just to give an idea of what's involved in terms of C:
X509_REQ *req = /* ... */;
STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(req);
int count = sk_X509_EXTENSION_num(exts);
int i;
for (i = 0; i < count; ++i) {
X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
/* Do something with ext */
}
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
Since M2Crypto uses SWIG to wrap the C code, it shouldn't be difficult to expose a new API if you have a good C background.
OTHER TIPS
To others finding this question via a similar Google search to what brought me here.
Faced with a similar problem, and no patch to this shortcoming of M2Crypto in sight, I went down the path of calling the OpenSSL utility and parsing the output, which looks similar-enough to YAML that we can fake it with a little cleanup.
def req_extensions(csrFilename):
cmd = ('openssl req -text -noout -in %s'
% csrFilename)
output = subprocess.check_output(cmd.split(),
stderr=subprocess.STDOUT)
output = re.sub(r': rsaEncryption', ':', output)
output = re.sub(r'[0-9a-f]{2}:', '', output)
return yaml.load(output)
Then...
csrExt = self.req_extensions('my.csr')
keyUsage = (
csrExt['Certificate Request']['Data']['Requested Extensions']
['X509v3 Key Usage'])
SAN = (
csrExt['Certificate Request']['Data']['Requested Extensions']
['X509v3 Subject Alternative Name'])
etc.