def add_extension(self, new_ext): """Add a new extension or replace existing one.""" if not isinstance(new_ext, extension.X509Extension): raise errors.X509Error("ext is not an anchor X509Extension") attributes = self.get_attributes() ext_attrs = [a for a in attributes if a['attrType'] == OID_extensionRequest] if not ext_attrs: new_attr_index = len(attributes) attributes[new_attr_index] = None ext_attr = attributes[new_attr_index] ext_attr['attrType'] = OID_extensionRequest ext_attr['attrValues'] = None exts = rfc5280.Extensions() else: ext_attr = ext_attrs[0] exts = decoder.decode(ext_attr['attrValues'][0].asOctets(), asn1Spec=rfc5280.Extensions())[0] # the end is the default position new_ext_index = len(exts) # unless there's an existing extension with the same OID for i, ext_i in enumerate(exts): if ext_i['extnID'] == new_ext.get_oid(): new_ext_index = i break exts[new_ext_index] = new_ext._ext ext_attr['attrValues'][0] = encoder.encode(exts)
def get_extensions(self, ext_type=None): """Get the list of all X509 V3 Extensions on this CSR :return: a list of X509Extension objects """ ext_attrs = [a for a in self.get_attributes() if a['attrType'] == OID_extensionRequest] if len(ext_attrs) == 0: return [] else: exts_der = ext_attrs[0]['attrValues'][0].asOctets() exts = decoder.decode(exts_der, asn1Spec=rfc5280.Extensions())[0] return [extension.construct_extension(e) for e in exts if ext_type is None or e['extnID'] == ext_type._oid]
def test_with_duplicates(self): csr = signing_request.X509Csr() ext = extension.X509ExtensionSubjectAltName() ext.add_dns_id('example.com') exts = rfc5280.Extensions() exts[0] = ext._ext exts[1] = ext._ext # Anchor doesn't allow this normally, so tests need to cheat attrs = csr.get_attributes() attrs[0] = None attrs[0]['attrType'] = signing_request.OID_extensionRequest attrs[0]['attrValues'] = None attrs[0]['attrValues'][0] = encoder.encode(exts) with self.assertRaises(errors.ValidationError): standards._no_extension_duplicates(csr)