Python OpenSSL.crypto.load_crl() Examples

The following are 22 code examples of OpenSSL.crypto.load_crl(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenSSL.crypto , or try the search function .
Example #1
Source File: localca.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_crl_next_update(filename):
    """
    Read the CRL file and return the next update as datetime
    :param filename:
    :return:
    """
    dt = None
    f = open(filename)
    crl_buff = f.read()
    f.close()
    crl_obj = crypto.load_crl(crypto.FILETYPE_PEM, crl_buff)
    # Get "Next Update" of CRL
    # Unfortunately pyOpenSSL does not support this. so we dump the
    # CRL and parse the text :-/
    # We do not want to add dependency to pyasn1
    crl_text = to_unicode(crypto.dump_crl(crypto.FILETYPE_TEXT, crl_obj))
    for line in crl_text.split("\n"):
        if "Next Update: " in line:
            key, value = line.split(":", 1)
            date = value.strip()
            dt = datetime.datetime.strptime(date, "%b %d %X %Y %Z")
            break
    return dt 
Example #2
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_load_crl(self):
        """
        Load a known CRL and inspect its revocations.  Both
        PEM and DER formats are loaded.
        """
        crl = load_crl(FILETYPE_PEM, crlData)
        revs = crl.get_revoked()
        self.assertEqual(len(revs), 2)
        self.assertEqual(revs[0].get_serial(), b('03AB'))
        self.assertEqual(revs[0].get_reason(), None)
        self.assertEqual(revs[1].get_serial(), b('0100'))
        self.assertEqual(revs[1].get_reason(), b('Superseded'))

        der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
        crl = load_crl(FILETYPE_ASN1, der)
        revs = crl.get_revoked()
        self.assertEqual(len(revs), 2)
        self.assertEqual(revs[0].get_serial(), b('03AB'))
        self.assertEqual(revs[0].get_reason(), None)
        self.assertEqual(revs[1].get_serial(), b('0100'))
        self.assertEqual(revs[1].get_reason(), b('Superseded')) 
Example #3
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 6 votes vote down vote up
def test_load_crl(self):
        """
        Load a known CRL and inspect its revocations.  Both EM and DER formats
        are loaded.
        """
        crl = load_crl(FILETYPE_PEM, crlData)
        revs = crl.get_revoked()
        assert len(revs) == 2
        assert revs[0].get_serial() == b'03AB'
        assert revs[0].get_reason() is None
        assert revs[1].get_serial() == b'0100'
        assert revs[1].get_reason() == b'Superseded'

        der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
        crl = load_crl(FILETYPE_ASN1, der)
        revs = crl.get_revoked()
        assert len(revs) == 2
        assert revs[0].get_serial() == b'03AB'
        assert revs[0].get_reason() is None
        assert revs[1].get_serial() == b'0100'
        assert revs[1].get_reason() == b'Superseded' 
Example #4
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_convert_to_cryptography_key(self):
        crl = load_crl(FILETYPE_PEM, crlData)
        crypto_crl = crl.to_cryptography()
        assert isinstance(crypto_crl, x509.CertificateRevocationList) 
Example #5
Source File: ssl_context.py    From aerospike-admin with Apache License 2.0 5 votes vote down vote up
def _parse_crl_cert(self, crl_dir_path):
        if not crl_dir_path:
            raise ValueError("No capath provided to CRL check.")
        try:
            files = [join(crl_dir_path, f) for f in listdir(
                crl_dir_path) if isfile(join(crl_dir_path, f))]
        except Exception:
            raise ValueError("Wrong or empty capath provided to CRL check.")

        crl_checklist = []
        for f in files:
            fs = None
            try:
                fs = open(f, "r").read()
                crl = crypto.load_crl(crypto.FILETYPE_PEM, fs)
                revoked = crl.get_revoked()
                if not revoked:
                    continue
                for r in revoked:
                    try:
                        r_serial = int(r.get_serial(), 16)
                        crl_checklist.append(r_serial)
                    except Exception:
                        pass
            except Exception:
                # Directory can have other files also
                pass
        if crl_checklist:
            return crl_checklist
        else:
            raise ValueError("No valid CRL found at capath") 
Example #6
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_dump_crl(self):
        """
        The dumped CRL matches the original input.
        """
        crl = load_crl(FILETYPE_PEM, crlData)
        buf = dump_crl(FILETYPE_PEM, crl)
        assert buf == crlData 
Example #7
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_load_crl_bad_data(self):
        """
        Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
        raises a `OpenSSL.crypto.Error`.
        """
        with pytest.raises(Error):
            load_crl(FILETYPE_PEM, b"hello, world") 
Example #8
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_load_crl_bad_filetype(self):
        """
        Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
        `ValueError`.
        """
        with pytest.raises(ValueError):
            load_crl(100, crlData) 
Example #9
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
        crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
        revoked = crl.get_revoked()
        revoked[1].set_reason(None)
        reason = revoked[1].get_reason()
        assert reason is None 
Example #10
Source File: test_crypto.py    From pyopenssl with Apache License 2.0 5 votes vote down vote up
def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
        """
        The get_reason method on the Revoked class checks to see if the
        extension is NID_crl_reason and should skip it otherwise. This test
        loads a CRL with extensions it should ignore.
        """
        crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
        revoked = crl.get_revoked()
        reason = revoked[1].get_reason()
        assert reason == b'Unspecified' 
Example #11
Source File: test_models.py    From openwisp-controller with GNU General Public License v3.0 5 votes vote down vote up
def test_crl_view(self):
        ca = self._create_ca()
        response = self.client.get(reverse('admin:crl', args=[ca.pk]))
        self.assertEqual(response.status_code, 200)
        crl = crypto.load_crl(crypto.FILETYPE_PEM, response.content)
        revoked_list = crl.get_revoked()
        self.assertIsNone(revoked_list) 
Example #12
Source File: openssl.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_crl(self):
        crl_path = self._get_crl_path()
        try:
            with open(crl_path) as crl:
                self.crl = crypto.load_crl(
                    crypto.FILETYPE_PEM,
                    crl.read()
                )
        except IOError as err:
            self.logger.warning(str(err))
            self.crl = None 
Example #13
Source File: openssl.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_crl(self):
        crl_path = self._get_crl_path()
        try:
            with open(crl_path) as crl:
                self.crl = crypto.load_crl(
                    crypto.FILETYPE_PEM,
                    crl.read()
                )
        except IOError as err:
            self.logger.warning(str(err))
            self.crl = None 
Example #14
Source File: openssl.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _load_crl(self):
        crl_path = self._get_crl_path()
        try:
            with open(crl_path) as crl:
                self.crl = crypto.load_crl(
                    crypto.FILETYPE_PEM,
                    crl.read()
                )
        except IOError as err:
            self.logger.warning(str(err))
            self.crl = None 
Example #15
Source File: test_ca.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_crl_view(self):
        ca, cert = self._prepare_revoked()
        response = self.client.get(reverse('admin:crl', args=[ca.pk]))
        self.assertEqual(response.status_code, 200)
        crl = crypto.load_crl(crypto.FILETYPE_PEM, response.content)
        revoked_list = crl.get_revoked()
        self.assertIsNotNone(revoked_list)
        self.assertEqual(len(revoked_list), 1)
        self.assertEqual(int(revoked_list[0].get_serial()), cert.serial_number) 
Example #16
Source File: test_ca.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_crl(self):
        ca, cert = self._prepare_revoked()
        crl = crypto.load_crl(crypto.FILETYPE_PEM, ca.crl)
        revoked_list = crl.get_revoked()
        self.assertIsNotNone(revoked_list)
        self.assertEqual(len(revoked_list), 1)
        self.assertEqual(int(revoked_list[0].get_serial()), cert.serial_number) 
Example #17
Source File: test_ca.py    From django-x509 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _prepare_revoked(self):
        ca = self._create_ca()
        crl = crypto.load_crl(crypto.FILETYPE_PEM, ca.crl)
        self.assertIsNone(crl.get_revoked())
        cert = self._create_cert(ca=ca)
        cert.revoke()
        return (ca, cert) 
Example #18
Source File: test_crypto.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_load_crl_bad_data(self):
        """
        Calling :py:obj:`OpenSSL.crypto.load_crl` with file data which can't
        be loaded raises a :py:obj:`OpenSSL.crypto.Error`.
        """
        self.assertRaises(Error, load_crl, FILETYPE_PEM, b"hello, world") 
Example #19
Source File: test_crypto.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_load_crl_bad_filetype(self):
        """
        Calling :py:obj:`OpenSSL.crypto.load_crl` with an unknown file type
        raises a :py:obj:`ValueError`.
        """
        self.assertRaises(ValueError, load_crl, 100, crlData) 
Example #20
Source File: test_crypto.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_load_crl_wrong_args(self):
        """
        Calling :py:obj:`OpenSSL.crypto.load_crl` with other than two
        arguments results in a :py:obj:`TypeError` being raised.
        """
        self.assertRaises(TypeError, load_crl)
        self.assertRaises(TypeError, load_crl, FILETYPE_PEM)
        self.assertRaises(TypeError, load_crl, FILETYPE_PEM, crlData, None) 
Example #21
Source File: fake_sas.py    From Spectrum-Access-System with Apache License 2.0 4 votes vote down vote up
def RunFakeServer(cbsd_sas_version, sas_sas_version, is_ecc, crl_index):
  FakeSasHandler.SetVersion(cbsd_sas_version, sas_sas_version)
  if is_ecc:
    assert ssl.HAS_ECDH
  server = HTTPServer(('localhost', PORT), FakeSasHandler)

  ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  ssl_context.options |= ssl.CERT_REQUIRED

  # If CRLs were provided, then enable revocation checking.
  if crl_index is not None:
    ssl_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN

    try:
      crl_files = ParseCrlIndex(crl_index)
    except IOError as e:
      print "Failed to parse CRL index file %r: %s" % (crl_index, e)

    # https://tools.ietf.org/html/rfc5280#section-4.2.1.13 specifies that
    # CRLs MUST be DER-encoded, but SSLContext expects the name of a PEM-encoded
    # file, so we must convert it first.
    for f in crl_files:
      try:
        with file(f) as handle:
          der = handle.read()
          try:
            crl = crypto.load_crl(crypto.FILETYPE_ASN1, der)
          except crypto.Error as e:
            print "Failed to parse CRL file %r as DER format: %s" % (f, e)
            return
          with tempfile.NamedTemporaryFile() as tmp:
            tmp.write(crypto.dump_crl(crypto.FILETYPE_PEM, crl))
            tmp.flush()
            ssl_context.load_verify_locations(cafile=tmp.name)
        print "Loaded CRL file: %r" % f
      except IOError as e:
        print "Failed to load CRL file %r: %s" % (f, e)
        return

  ssl_context.load_verify_locations(cafile=CA_CERT)
  ssl_context.load_cert_chain(
      certfile=ECC_CERT_FILE if is_ecc else CERT_FILE,
      keyfile=ECC_KEY_FILE if is_ecc else KEY_FILE)
  ssl_context.set_ciphers(':'.join(ECC_CIPHERS if is_ecc else CIPHERS))
  ssl_context.verify_mode = ssl.CERT_REQUIRED
  server.socket = ssl_context.wrap_socket(server.socket, server_side=True)
  print 'Will start server at localhost:%d, use <Ctrl-C> to stop.' % PORT
  server.serve_forever() 
Example #22
Source File: test_lib_caconnector.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_02_sign_cert(self):
        cacon = LocalCAConnector("localCA", {"cacert": "...",
                                             "cakey": "..."})
        # set the parameters:
        cwd = os.getcwd()
        cacon.set_config({"cakey": CAKEY, "cacert": CACERT,
                          "openssl.cnf": OPENSSLCNF,
                          "WorkingDir": cwd + "/" + WORKINGDIR})

        cert = cacon.sign_request(REQUEST,
                                  {"CSRDir": "",
                                   "CertificateDir": "",
                                   "WorkingDir": cwd + "/" + WORKINGDIR})
        serial = cert.get_serial_number()

        self.assertEqual("{0!r}".format(cert.get_issuer()),
                         "<X509Name object "
                         "'/C=DE/ST=Hessen/O=privacyidea/CN=CA001'>")
        self.assertEqual("{0!r}".format(cert.get_subject()),
                         "<X509Name object "
                         "'/C=DE/ST=Hessen/O=privacyidea/CN=requester"
                         ".localdomain'>")

        # Revoke certificate
        r = cacon.revoke_cert(cert)
        serial_hex = int_to_hex(serial)
        self.assertEqual(r, serial_hex)

        # Create the CRL
        r = cacon.create_crl()
        self.assertEqual(r, "crl.pem")
        # Check if the serial number is contained in the CRL!
        filename = os.path.join(cwd, WORKINGDIR, "crl.pem")
        f = open(filename)
        buff = f.read()
        f.close()
        crl = crypto.load_crl(crypto.FILETYPE_PEM, buff)
        revoked_certs = crl.get_revoked()
        found_revoked_cert = False
        for revoked_cert in revoked_certs:
            s = to_unicode(revoked_cert.get_serial())
            if s == serial_hex:
                found_revoked_cert = True
                break
        self.assertTrue(found_revoked_cert)

        # Create the CRL and check the overlap period. But no need to create
        # a new CRL.
        r = cacon.create_crl(check_validity=True)
        self.assertEqual(r, None)

        # Now we overlap at any cost!
        cacon.set_config({"cakey": CAKEY, "cacert": CACERT,
                          "openssl.cnf": OPENSSLCNF,
                          "WorkingDir": cwd + "/" + WORKINGDIR,
                          ATTR.CRL_OVERLAP_PERIOD: 1000})
        r = cacon.create_crl(check_validity=True)
        self.assertEqual(r, "crl.pem")