Search code examples
pythonx509certificateasn.1pyasn1

Error while creating an X509 certificate with extensions in PyASN1


I'm trying to create a X509v3 certificate and encode it in DER and save it into a file. I'm using PyASN1 0.1.7 and Python 2.7.6 on Ubuntu 14.04.

The code can be summarized as this:

tbs = rfc2459.TBSCertificate()
tbs.setComponentByName('XYZ', xyz)  # other non-problematic certificate fields
....
subjaltname = rfc2459.SubjectAltName()
subjaltname.setComponentByPosition(0, fc2459.GeneralName().setComponentByName('dNSName', 'domain.com'))
extension = rfc2459.Extension()
extension.setComponentByName('extnID', rfc2459.id_ce_subjectAltName)
extension.setComponentByName('critical', univ.Boolean(False))
extension.setComponentByName('extnValue', univ.OctetString(der_encoder.encode(subjaltname)))
extensions = rfc2459.Extensions()
extensions.setComponentByPosition(0, extension)
tbs.setComponentByName('extensions', extensions.subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3)))
cert = rfc2459.Certificate()
cert.setComponentByName('tbsCertificate', tbs)

When I try to encode cert object with DER encoder, I get this error:

pyasn1.type.error.ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(), ValueSizeConstraint(1, 64)) failed at: "ValueSizeConstraint(1, 64) failed at: "Extensions()""

Any suggestions on the problematic part of code would be appreciated.

P.S. if anyone has a working sample code on how to create a X509v3 certificate with extensions using PyASN1, I'd love to see it.


Solution

  • My guess is that when you make a subtype of Extensions object here:

    tbs.setComponentByName('extensions',extensions.subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3)))
    

    it loses its initial value. You could either try adding cloneValueFlag=True to .subtype() to force it doing a deep copy, or better do subtyping prior to initialization:

    extensions = rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))
    extensions.setComponentByPosition(0, extension)
    tbs.setComponentByName('extensions', extensions)
    

    Also enabling pyasn1 debugging may be helpful for troubleshooting.