class TBSCertificateRevocationList(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('signature', AlgorithmIdentifier()), namedtype.NamedType('issuer', Name()), namedtype.NamedType('lastUpdate', useful.UTCTime()), namedtype.NamedType('nextUpdate', useful.UTCTime()), namedtype.OptionalNamedType('revokedCertificates', univ.SequenceOf(componentType=CRLEntry())))
def testSchemaPickling(self): old_asn1 = useful.UTCTime() serialised = pickle.dumps(old_asn1) assert serialised new_asn1 = pickle.loads(serialised) assert type(new_asn1) == useful.UTCTime assert old_asn1.isSameTypeWith(new_asn1)
class Time(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime())) def __str__(self): return str(self.getComponent())
def testFractionOfSecond(self): try: assert encoder.encode(useful.UTCTime('150501120112.10Z')) except PyAsn1Error: pass else: assert 0, 'Decimal point tolerated'
def __init__(self, not_before, not_after): """@todo: to be defined """ val = univ.Sequence() for i, x in enumerate((not_before, not_after)): val.setComponentByPosition( i, useful.UTCTime(x.strftime('%y%m%d%H%M%SZ'))) super(CertValidity, self).__init__('1.2.643.2.4.1.1.1.1.2', val)
def testLocalTimezone(self): try: assert encoder.encode(useful.UTCTime('150501120112+0200')) except PyAsn1Error: pass else: assert 0, 'Local timezone tolerated'
class MPContent(univ.Sequence): """ MPContent class inherits pyasn1.type.univ.Sequence class and encapsulates MPContent structure in it You can take a look for the information about the structure in our docs: https://github.com/arachnid42/mflod/blob/master/mflod/crypto/README.md #0-content-block-asn1-structure @developer: vsmysle You need to set these parameters: timestamp: string representing current time in YYMMDDhhmmssZ format content: string representing message of the user Example: mp_content = MPContent() mp_content['timestamp'] = datetime.datetime.utcnow().strftime("%Y%m%d%H%M%SZ") mp_content['content'] = 'Hello, world!' """ componentType = namedtype.NamedTypes( namedtype.NamedType('timestamp', useful.UTCTime()), namedtype.NamedType('content', univ.OctetString()) )
class CertTrustList(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('catalogList', CatalogList()), namedtype.NamedType('someStr0', univ.OctetString()), namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('catalogListMemberId', CatalogListMemberId()), namedtype.NamedType('members', CatalogMembers()), namedtype.OptionalNamedType('attributes', CatalogAttributes()))
def testMissingTimezone(self): try: assert encoder.encode(useful.UTCTime('150501120112')) == ints2octs( (23, 13, 49, 53, 48, 53, 48, 49, 49, 50, 48, 49, 49, 50, 90)) except PyAsn1Error: pass else: assert 0, 'Missing timezone tolerated'
class CTL(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('dummy1', univ.Any()), namedtype.NamedType('UnknownInt', univ.Integer()), namedtype.NamedType('GenDate', useful.UTCTime()), namedtype.NamedType('dummy4', univ.Any()), namedtype.NamedType('InnerCTL', univ.SequenceOf(CTLEntry())), )
def _build_tbs(csr, days, network): cri = csr.getComponentByName('certificationRequestInfo') subject = cri.getComponentByName('subject') subjectPublicKeyInfo = cri.getComponentByName('subjectPublicKeyInfo') dt_now = datetime.datetime.utcnow() later = datetime.timedelta(days=days) dt_now_str = dt_now.strftime("%y%m%d%H%M%S") + "Z" later_str = (dt_now + later).strftime("%y%m%d%H%M%S") + "Z" notbefore = useful.UTCTime(dt_now_str) notafter = useful.UTCTime(later_str) validity = rfc2459.Validity() validity.setComponentByName('notBefore', notbefore) validity.setComponentByName('notAfter', notafter) tbs = rfc2459.TBSCertificate() tbs.setComponentByName( 'version', rfc2459.Version('v3').subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))) rndfile = Random.new() serial = encoding.to_long(256, encoding.byte_to_int, rndfile.read(32))[0] tbs.setComponentByName( 'serialNumber', rfc2459.CertificateSerialNumber(univ.Integer(serial))) tbs.setComponentByName('signature', csr.getComponentByName('signatureAlgorithm')) tbs.setComponentByName('issuer', subject) tbs.setComponentByName('validity', validity) tbs.setComponentByName('subject', subject) tbs.setComponentByName('subjectPublicKeyInfo', subjectPublicKeyInfo) extensionstoadd = "" attributes = cri.getComponentByName('attributes') for attribute in attributes: if (attribute.getComponentByName('type') == utility.OID_PKCShash9ExtensionRequest): value = attribute[1] ## careful with decoder, it returns an implicit type in a tuple extensionstoadd = decoder.decode(value[0])[0] spk = subjectPublicKeyInfo.getComponentByName('subjectPublicKey') ## self siiiigned extensions = _build_extensionsForTbs(extensionstoadd, akipubkeybitstring=spk, skipubkeybitstring=spk) if extensions: tbs.setComponentByName('extensions', extensions) return tbs
class Time(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime())) def to_python_time(self): if 'utcTime' in self: return self['utcTime'].asDateTime else: return self['generalTime'].asDateTime
def test_conversion_utc(self): utctime = useful.UTCTime('120614235959Z') t = Time() t['utcTime'] = utctime self.assertEqual( time_to_python(t), datetime.datetime(2012, 6, 14, 23, 59, 59, tzinfo=datetime.timezone.utc))
def check_signing_time(attr_value): """ Verify signing time attribute """ logging.info('Attribute Signing Time') try: signed_time, _ = decoder.decode(attr_value, asn1Spec=useful.UTCTime()) logging.info('\tAttribute Value:\t' + str(signed_time.asDateTime)) logging.info('\tGenTime Value:\t\t' + str(GenTime.asDateTime)) assert signed_time.asDateTime == GenTime.asDateTime except Exception as e: logging.error('Check Attribute Signing Time: Failure,', exc_info=True) raise e logging.info('Check Attribute Signing Time: Success\n') return True
class Time(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime())) def ToPythonEpochTime(self): """Takes a ASN.1 Time choice, and returns seconds since epoch in UTC.""" utc_time = self.getComponentByName('utcTime') general_time = self.getComponentByName('generalTime') if utc_time and general_time: raise error.PyAsn1Error('Both elements of a choice are present.') if general_time: format_str = '%Y%m%d%H%M%SZ' time_str = str(general_time) else: format_str = '%y%m%d%H%M%SZ' time_str = str(utc_time) time_tpl = time.strptime(time_str, format_str) return calendar.timegm(time_tpl)
class Time(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime())) def ToPythonEpochTime(self): """Takes a ASN.1 Time choice, and returns seconds since epoch in UTC.""" # For some reason, if you don't pass default=None, instantiate=False, then it seems # that the parent ASN.1 object gets destroyed utc_time = self.getComponentByName('utcTime', default=None, instantiate=False) general_time = self.getComponentByName('generalTime', default=None, instantiate=False) if utc_time and general_time: raise error.PyAsn1Error('Both elements of a choice are present.') if general_time: format_str = '%Y%m%d%H%M%SZ' time_str = str(general_time) else: format_str = '%y%m%d%H%M%SZ' time_str = str(utc_time) time_tpl = time.strptime(time_str, format_str) return calendar.timegm(time_tpl)
def process(): "Process new certificate requests" for request in Request.query.filter(Request.generation_date == None).all(): # noqa if app.config['SHOW_SIGNED_REQUESTS']: numsigned = Request.query.filter(Request.email == request.email, Request.generation_date != None).count() prompt = "Do you want to generate a certificate for {}, {}?\n\talready signed to this address: {}" print(prompt.format(request.id, request.email, numsigned)) else: prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type 'y' to approve, 'n' to reject or 'any key' to skip") confirm = input('>') if confirm in ['Y', 'y']: print('generating key') new_key = create_key() print('generating certificate') new_cert_sn = Request.getMaxCertSn() + 1 request.cert_sn = new_cert_sn new_cert = create_cert(request.id, request.email, request.cert_sn, new_key) key_store(request.id, new_key) cert_store(request.id, new_cert) #print (crypto.dump_certificate(crypto.FILETYPE_TEXT, new_cert)) request.generation_date = datetime.date.today() expireAsn1 = new_cert.get_notAfter().decode("ASCII") # see the Note on http://pyasn1.sourceforge.net/docs/type/useful/utctime.html#pyasn1.type.useful.UTCTime # for this we only use the 2-digit year expireAsn1 = str(expireAsn1)[2:] expiry = useful.UTCTime(expireAsn1) request.cert_expire_date = expiry.asDateTime db.session.commit() mail_certificate(request.id, request.email) print() elif confirm in ['N', 'n']: print('rejecting request') db.session.delete(request) db.session.commit() mail_request_rejected(request.id, request.email) else: print('skipping generation \n')
class CRLEntry(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('userCertificate', SerialNumber()), namedtype.NamedType('revocationDate', useful.UTCTime()))
def testConvert(self): utctime = useful.UTCTime('120614235959Z') t = Time() t.setComponentByName('utcTime', utctime) t_str = time.asctime(time.gmtime(t.ToPythonEpochTime())) self.assertEquals(t_str, 'Thu Jun 14 23:59:59 2012')
def testMissingTimezone(self): assert encoder.encode(useful.UTCTime('150501120112')) == ints2octs( (23, 13, 49, 53, 48, 53, 48, 49, 49, 50, 48, 49, 49, 50, 90)), 'Missing timezone not added'
def testValuePickling(self): old_asn1 = useful.UTCTime("170711000102") serialised = pickle.dumps(old_asn1) assert serialised new_asn1 = pickle.loads(serialised) assert new_asn1 == old_asn1
def testWithMinutes(self): assert encoder.encode(useful.UTCTime('9908011201Z')) == ints2octs( (23, 11, 57, 57, 48, 56, 48, 49, 49, 50, 48, 49, 90))
def testWithSeconds(self): assert encoder.encode(useful.UTCTime('990801120112Z')) == ints2octs( (23, 13, 57, 57, 48, 56, 48, 49, 49, 50, 48, 49, 49, 50, 90))
class TimeChoice(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('genTime', useful.GeneralizedTime()))
pass class AlgorithmIdentifier(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('algorithm', univ.ObjectIdentifier()), namedtype.OptionalNamedType('parameters', univ.Any()) ) class Time(univ.Choice): pass Time.componentType = namedtype.NamedTypes( namedtype.NamedType('utcTime', useful.UTCTime()), namedtype.NamedType('generalTime', useful.GeneralizedTime()) ) class AttributeValue(univ.Any): pass certificateAttributesMap = {} class AttributeTypeAndValue(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('type', AttributeType()), namedtype.NamedType(
def testToDateTime4(self): assert datetime.datetime(2017, 7, 11, 0, 1) == useful.UTCTime('1707110001').asDateTime
def testToDateTime3(self): assert datetime.datetime(2017, 7, 11, 0, 1, 2, tzinfo=UTC2) == useful.UTCTime('170711000102+0200').asDateTime
class Time(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType("utcTime", useful.UTCTime()), namedtype.NamedType("generalTime", useful.GeneralizedTime()))
class UTCTimeDecoder(OctetStringDecoder): protoComponent = useful.UTCTime()
class CrlIdentifier(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('crlissuer', Name()), namedtype.NamedType('crlIssuedTime', useful.UTCTime()), namedtype.OptionalNamedType('crlNumber', univ.Integer()))