def test_verify_with_add_crls(self): ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem") valid_cert = X509.load_cert('tests/crl_data/certs/valid_cert.pem') revoked_cert = X509.load_cert('tests/crl_data/certs/revoked_cert.pem') crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem') # Verify that a good cert is verified OK store = X509.X509_Store() store.add_x509(ca) store.set_flags(X509.m2.X509_V_FLAG_CRL_CHECK | X509.m2.X509_V_FLAG_CRL_CHECK_ALL) crl_stack = X509.CRL_Stack() crl_stack.push(crl) store_ctx = X509.X509_Store_Context() store_ctx.init(store, valid_cert) store_ctx.add_crls(crl_stack) self.assertTrue(store_ctx.verify_cert()) # Verify that a revoked cert is not verified store = X509.X509_Store() store.add_x509(ca) store.set_flags(X509.m2.X509_V_FLAG_CRL_CHECK | X509.m2.X509_V_FLAG_CRL_CHECK_ALL) crl_stack = X509.CRL_Stack() crl_stack.push(crl) store_ctx = X509.X509_Store_Context() store_ctx.init(store, revoked_cert) store_ctx.add_crls(crl_stack) self.assertFalse(store_ctx.verify_cert())
def test_verify(self): ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem") crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem') self.assertTrue(crl.verify(ca.get_pubkey())) wrong_ca = X509.load_cert('tests/ca.pem') self.assertFalse(crl.verify(wrong_ca.get_pubkey()))
def test_malformed_data(self): with self.assertRaises(X509.X509Error): X509.load_cert_string('Hello') with self.assertRaises(X509.X509Error): X509.load_cert_der_string('Hello') with self.assertRaises(X509.X509Error): X509.new_stack_from_der('Hello') with self.assertRaises(X509.X509Error): X509.load_cert('tests/alltests.py') with self.assertRaises(X509.X509Error): X509.load_request('tests/alltests.py') with self.assertRaises(X509.X509Error): X509.load_request_string('Hello') with self.assertRaises(X509.X509Error): X509.load_request_der_string('Hello') with self.assertRaises(X509.X509Error): X509.load_crl('tests/alltests.py')
def main(self, files): values = {} i = 0 for f in files: fd = open(f["meta"]) data = fd.read() fd.close() off = 0 offset = struct.unpack_from("<L", data, off)[0] off += struct.calcsize("<L") offset += off struct.unpack_from("<2L", data, off) off += struct.calcsize("<2L") length = struct.unpack_from("<L", data, off)[0] off += struct.calcsize("<L") tstamp = struct.unpack_from("<Q", data, off)[0] off += struct.calcsize("<Q") url = data[offset:offset + length].decode("UTF-16LE")[:-1] if tstamp > 0: tstamp /= 10000000 tstamp -= 11644473600 ## dealing with CRL ASN.1 file now try: fd = open(f["content"]) content = base64.b64encode(fd.read()) fd.close() t = ['-----BEGIN X509 CRL-----'] while len(content) > 64: t.append(content[:64]) content = content[64:] t.append(content) t.append('-----END X509 CRL-----') t.append('') fd = tempfile.NamedTemporaryFile(delete=False) fd.write("\n".join(t)) fd.close() crl = X509.load_crl(fd.name) t = map(lambda x: x.strip(), crl.as_text().splitlines()) serial = t[t.index('X509v3 CRL Number:') + 1] os.unlink(fd.name) except: serial = None crl = None i += 1 values["url%d" % i] = {'timestamp': tstamp, 'url': url} # if crl is not None: # values["url%d" % i]['crl'] = crl.as_text() if serial is not None: values["url%d" % i]['serial'] = serial return {self.__class__.__name__: values}
def main(self, files): values = {} i = 0 for f in files: fd = open(f["meta"]) data = fd.read() fd.close() off = 0 offset = struct.unpack_from("<L", data, off)[0] off += struct.calcsize("<L") offset += off struct.unpack_from("<2L", data, off) off += struct.calcsize("<2L") length = struct.unpack_from("<L", data, off)[0] off += struct.calcsize("<L") tstamp = struct.unpack_from("<Q", data, off)[0] off += struct.calcsize("<Q") url = data[offset:offset+length].decode("UTF-16LE")[:-1] if tstamp > 0: tstamp /= 10000000 tstamp -= 11644473600 ## dealing with CRL ASN.1 file now try: fd = open(f["content"]) content = base64.b64encode(fd.read()) fd.close() t = [ '-----BEGIN X509 CRL-----'] while len(content) > 64: t.append(content[:64]) content = content[64:] t.append(content) t.append('-----END X509 CRL-----') t.append('') fd = tempfile.NamedTemporaryFile(delete=False) fd.write("\n".join(t)) fd.close() crl = X509.load_crl(fd.name) t = map(lambda x: x.strip(), crl.as_text().splitlines()) serial = t[t.index('X509v3 CRL Number:') + 1] os.unlink(fd.name) except: serial = None crl = None i += 1 values["url%d" % i] = { 'timestamp': tstamp, 'url': url } # if crl is not None: # values["url%d" % i]['crl'] = crl.as_text() if serial is not None: values["url%d" % i]['serial'] = serial return { self.__class__.__name__: values }
def test_get_issuer(self): ca = X509.load_cert("tests/crl_data/certs/revoking_ca.pem") crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem') ca_issuer = ca.get_issuer() crl_issuer = crl.get_issuer() self.assertEqual(ca_issuer.as_hash(), crl_issuer.as_hash()) wrong_ca = X509.load_cert('tests/ca.pem') wrong_ca_issuer = wrong_ca.get_issuer() self.assertNotEqual(wrong_ca_issuer.as_hash(), crl_issuer.as_hash())
def get_crl_stack(self, issuer_hash, crl_dir=None): """ @param issuer_hash: Hash value of the issuing certificate @type issuer_hash: unsigned long @param crl_dir: Path to search for CRLs, default is None which defaults to configuration file parameter @type crl_dir: str @return CRL_Stack of any CRLs issued by the issuer_hash @rtype: CRL_Stack: M2Crypto.X509.CRL_Stack """ crl_stack = X509.CRL_Stack() if not crl_dir: crl_dir = self._crl_directory() if os.path.exists(crl_dir): search_path = "%s/%x.r*" % (crl_dir, issuer_hash) crl_paths = glob(search_path) for c in crl_paths: try: crl = X509.load_crl(c) crl_stack.push(crl) except: LOG.exception("Unable to load CRL file: %s" % (c)) return crl_stack
def load_ca_crl(self,filename): crltext = str(X509.load_crl(filename).as_text()) lines = crltext.split('\n') if 'Certificate Revocation List (CRL):' != lines[0]: return False section = 0 regex_issuer = re.compile(' Issuer: ') regex_crl_created = re.compile(' Last Update: ') regex_crl_expires = re.compile(' Next Update: ') regex_serial = re.compile(' Serial Number: ') #regex_revoke_date = re.compile(' Revocation Date:') regex_section_revoked = re.compile('Revoked Certificates:') regex_section_revoked2 = re.compile('No Revoked Certificates.') regex_section_signature = re.compile(' Signature Algorithm: ') Issuer = None crl_update_created = None crl_update_expires = None revokationlist = set([]) for line in lines: if section == 0: match_issuer = regex_issuer.match(line) if match_issuer: Issuer = line[match_issuer.end():].strip() continue match_crl_created = regex_crl_created.match(line) if match_crl_created: crl_update_created = parse_crl_date(line[match_crl_created.end():].strip()) continue match_crl_expires = regex_crl_expires.match(line) if match_crl_expires: crl_update_expires = parse_crl_date(line[match_crl_expires.end():].strip()) continue if regex_section_revoked.match(line) or regex_section_revoked2.match(line): section = 1 continue #print line if section == 1: match_serial = regex_serial.match(line) if match_serial: serial_num_string = int(line[match_serial.end():].strip(),16) revokationlist.add(serial_num_string) #match_revokedate = regex_revoke_date.match(line) #if match_revokedate: # testerdate = parse_crl_date(line[match_revokedate.end():].strip()) # if testerdate == None: # print 'sdfsdf%s' % (line[match_revokedate.end():].strip()) # print testerdate.strftime("%b %d %H:%M:%S %Y GMT") if regex_section_signature.match(line): section = 2 continue #print line if section == 2: continue if None == Issuer: self.logger.warning("CRL Issuer not found:%s" % (filename)) return False if not Issuer in self.ca.keys(): self.logger.debug("Namespace for Issuer '%s' does not exist:%s" % (Issuer,filename)) return False self.ca[Issuer].crl = revokationlist self.ca[Issuer].crl_created = crl_update_created self.ca[Issuer].crl_expires = crl_update_expires if None == crl_update_created: self.logger.warning("CRL creation date not found:%s:%s" % (filename,Issuer)) return False if None == crl_update_expires: self.logger.warning("CRL expiry date not found:%s:%s" % (filename,Issuer)) return False now = datetime.datetime.now() if now <= crl_update_created: self.logger.debug("CRL created in the future :%s:%s" % (filename,Issuer)) return False if now >= crl_update_expires: self.logger.info("at %s the CRL expired:%s:%s" % (crl_update_expires,filename,Issuer)) return False return True
def load_ca_crl(self, filename): crltext = str(X509.load_crl(filename).as_text()) lines = crltext.split('\n') if 'Certificate Revocation List (CRL):' != lines[0]: return False section = 0 regex_issuer = re.compile(' Issuer: ') regex_crl_created = re.compile(' Last Update: ') regex_crl_expires = re.compile(' Next Update: ') regex_serial = re.compile(' Serial Number: ') #regex_revoke_date = re.compile(' Revocation Date:') regex_section_revoked = re.compile('Revoked Certificates:') regex_section_revoked2 = re.compile('No Revoked Certificates.') regex_section_signature = re.compile(' Signature Algorithm: ') Issuer = None crl_update_created = None crl_update_expires = None revokationlist = set([]) for line in lines: if section == 0: match_issuer = regex_issuer.match(line) if match_issuer: Issuer = line[match_issuer.end():].strip() continue match_crl_created = regex_crl_created.match(line) if match_crl_created: crl_update_created = parse_crl_date( line[match_crl_created.end():].strip()) continue match_crl_expires = regex_crl_expires.match(line) if match_crl_expires: crl_update_expires = parse_crl_date( line[match_crl_expires.end():].strip()) continue if regex_section_revoked.match( line) or regex_section_revoked2.match(line): section = 1 continue #print line if section == 1: match_serial = regex_serial.match(line) if match_serial: serial_num_string = int(line[match_serial.end():].strip(), 16) revokationlist.add(serial_num_string) #match_revokedate = regex_revoke_date.match(line) #if match_revokedate: # testerdate = parse_crl_date(line[match_revokedate.end():].strip()) # if testerdate == None: # print 'sdfsdf%s' % (line[match_revokedate.end():].strip()) # print testerdate.strftime("%b %d %H:%M:%S %Y GMT") if regex_section_signature.match(line): section = 2 continue #print line if section == 2: continue if None == Issuer: self.logger.warning("CRL Issuer not found:%s" % (filename)) return False if not Issuer in self.ca.keys(): self.logger.debug("Namespace for Issuer '%s' does not exist:%s" % (Issuer, filename)) return False self.ca[Issuer].crl = revokationlist self.ca[Issuer].crl_created = crl_update_created self.ca[Issuer].crl_expires = crl_update_expires if None == crl_update_created: self.logger.warning("CRL creation date not found:%s:%s" % (filename, Issuer)) return False if None == crl_update_expires: self.logger.warning("CRL expiry date not found:%s:%s" % (filename, Issuer)) return False now = datetime.datetime.utcnow() if now <= crl_update_created: self.logger.debug("CRL created in the future :%s:%s" % (filename, Issuer)) return False if now >= crl_update_expires: self.logger.info("at %s the CRL expired:%s:%s" % (crl_update_expires, filename, Issuer)) return False return True
def test_get_next_update(self): expected_nextUpdate = "Jan 18 16:55:58 2015 GMT" crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem') self.assertEquals(str(crl.get_nextUpdate()), expected_nextUpdate)
def test_load_crl(self): crl = X509.load_crl('tests/crl_data/certs/revoking_crl.pem') self.assertIsNotNone(crl) self.assertIsInstance(crl, X509.CRL)
sk = X509.X509_Stack() # Load the data, verify it. p7, data = SMIME.smime_load_pkcs7('bill') stack = p7.get0_signers(sk) looping = True while looping: one = stack.pop() if one == None: break print one.get_subject() print one.get_serial_number() print one.get_issuer() crl = X509.load_crl('/etc/grid-security/certificates/dd4b34ea.r0') print crl.as_text() #print crl.crl.own() s = SMIME.SMIME() x509c = X509.load_cert('/etc/grid-security/certificates/dd4b34ea.0') sk = X509.X509_Stack() sk.push(x509c) s.set_x509_stack(sk) # Load the signer's CA cert. In this case, because the signer's # cert is self-signed, it is the signer's cert itself. st = X509.X509_Store() st.load_info('/etc/grid-security/certificates/dd4b34ea.0')
if self.check: if self.ca: logger.debug("Load certificate authority (%s) file" % self.ca) ok = context.load_verify_locations(self.encodeFilename(self.ca)) if not ok: raise SSLConfigError( tr("Unable to open the certificate authority: %s") % self.ca) else: logger.info("Warning: No certificate authority") if self.crl: logger.debug("Load certificate revokation list (%s) file" % self.crl) try: crl = X509.load_crl(self.crl) except Exception, err: raise SSLConfigError( tr("Unable to open the certificate revokation list: %s") % exceptionAsUnicode(err)) cert_store = context.get_cert_store() try: cert_store.add_crl(crl) cert_store.set_flags(m2.X509_V_FLAG_CRL_CHECK) except AttributeError: logger.error("Your m2crypto version doesn't support CRL") else: logger.info("Warning: No certificate revokation list") logger.info("Check SSL peer certificate using M2Crypto") mode = SSL.verify_peer
# Instantiate an SMIME object. sk = X509.X509_Stack() # Load the data, verify it. p7, data = SMIME.smime_load_pkcs7('bill') stack = p7.get0_signers(sk) looping = True while looping: one = stack.pop() if one == None: break print one.get_subject() print one.get_serial_number() print one.get_issuer() crl = X509.load_crl('/etc/grid-security/certificates/dd4b34ea.r0') print crl.as_text() #print crl.crl.own() s = SMIME.SMIME() x509c = X509.load_cert('/etc/grid-security/certificates/dd4b34ea.0') sk = X509.X509_Stack() sk.push(x509c) s.set_x509_stack(sk) # Load the signer's CA cert. In this case, because the signer's # cert is self-signed, it is the signer's cert itself. st = X509.X509_Store() st.load_info('/etc/grid-security/certificates/dd4b34ea.0')