|
| 1 | +import base64 |
| 2 | +import ssl |
| 3 | +from urllib.parse import urljoin, urlparse |
| 4 | + |
| 5 | +import cryptography.hazmat.primitives.hashes |
| 6 | +import requests |
| 7 | +from cryptography import hazmat, x509 |
| 8 | +from cryptography.hazmat import backends |
| 9 | +from cryptography.x509 import ocsp |
| 10 | + |
| 11 | +from redis.exceptions import AuthorizationError, ConnectionError |
| 12 | + |
| 13 | + |
| 14 | +class OCSPVerifier: |
| 15 | + """A class to verify ssl sockets for RFC6960/RFC6961. |
| 16 | +
|
| 17 | + @see https://datatracker.ietf.org/doc/html/rfc6960 |
| 18 | + @see https://datatracker.ietf.org/doc/html/rfc6961 |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, sock, host, port, ca_certs=None): |
| 22 | + self.SOCK = sock |
| 23 | + self.HOST = host |
| 24 | + self.PORT = port |
| 25 | + self.CA_CERTS = ca_certs |
| 26 | + |
| 27 | + def _bin2ascii(self, der): |
| 28 | + """Convert SSL certificates in a binary (DER) format to ASCII PEM.""" |
| 29 | + |
| 30 | + pem = ssl.DER_cert_to_PEM_cert(der) |
| 31 | + cert = x509.load_pem_x509_certificate(pem.encode(), backends.default_backend()) |
| 32 | + return cert |
| 33 | + |
| 34 | + def components_from_socket(self): |
| 35 | + """This function returns the certificate, primary issuer, and primary ocsp server |
| 36 | + in the chain for a socket already wrapped with ssl. |
| 37 | + """ |
| 38 | + |
| 39 | + # convert the binary certifcate to text |
| 40 | + der = self.SOCK.getpeercert(True) |
| 41 | + if der is False: |
| 42 | + raise ConnectionError("no certificate found for ssl peer") |
| 43 | + cert = self._bin2ascii(der) |
| 44 | + return self._certificate_components(cert) |
| 45 | + |
| 46 | + def _certificate_components(self, cert): |
| 47 | + """Given an SSL certificate, retract the useful components for |
| 48 | + validating the certificate status with an OCSP server. |
| 49 | +
|
| 50 | + Args: |
| 51 | + cert ([bytes]): A PEM encoded ssl certificate |
| 52 | + """ |
| 53 | + |
| 54 | + try: |
| 55 | + aia = cert.extensions.get_extension_for_oid( |
| 56 | + x509.oid.ExtensionOID.AUTHORITY_INFORMATION_ACCESS |
| 57 | + ).value |
| 58 | + except cryptography.x509.extensions.ExtensionNotFound: |
| 59 | + raise ConnectionError("No AIA information present in ssl certificate") |
| 60 | + |
| 61 | + # fetch certificate issuers |
| 62 | + issuers = [ |
| 63 | + i |
| 64 | + for i in aia |
| 65 | + if i.access_method == x509.oid.AuthorityInformationAccessOID.CA_ISSUERS |
| 66 | + ] |
| 67 | + try: |
| 68 | + issuer = issuers[0].access_location.value |
| 69 | + except IndexError: |
| 70 | + raise ConnectionError("no issuers in certificate") |
| 71 | + |
| 72 | + # now, the series of ocsp server entries |
| 73 | + ocsps = [ |
| 74 | + i |
| 75 | + for i in aia |
| 76 | + if i.access_method == x509.oid.AuthorityInformationAccessOID.OCSP |
| 77 | + ] |
| 78 | + |
| 79 | + try: |
| 80 | + ocsp = ocsps[0].access_location.value |
| 81 | + except IndexError: |
| 82 | + raise ConnectionError("no ocsp servers in certificate") |
| 83 | + |
| 84 | + return cert, issuer, ocsp |
| 85 | + |
| 86 | + def components_from_direct_connection(self): |
| 87 | + """Return the certificate, primary issuer, and primary ocsp server |
| 88 | + from the host defined by the socket. This is useful in cases where |
| 89 | + different certificates are occasionally presented. |
| 90 | + """ |
| 91 | + |
| 92 | + pem = ssl.get_server_certificate((self.HOST, self.PORT), ca_certs=self.CA_CERTS) |
| 93 | + cert = x509.load_pem_x509_certificate(pem.encode(), backends.default_backend()) |
| 94 | + return self._certificate_components(cert) |
| 95 | + |
| 96 | + def build_certificate_url(self, server, cert, issuer_cert): |
| 97 | + """Return the complete url to the ocsp""" |
| 98 | + orb = ocsp.OCSPRequestBuilder() |
| 99 | + |
| 100 | + # add_certificate returns an initialized OCSPRequestBuilder |
| 101 | + orb = orb.add_certificate( |
| 102 | + cert, issuer_cert, cryptography.hazmat.primitives.hashes.SHA256() |
| 103 | + ) |
| 104 | + request = orb.build() |
| 105 | + |
| 106 | + path = base64.b64encode( |
| 107 | + request.public_bytes(hazmat.primitives.serialization.Encoding.DER) |
| 108 | + ) |
| 109 | + url = urljoin(server, path.decode("ascii")) |
| 110 | + return url |
| 111 | + |
| 112 | + def check_certificate(self, server, cert, issuer_url): |
| 113 | + """Checks the validitity of an ocsp server for an issuer""" |
| 114 | + |
| 115 | + r = requests.get(issuer_url) |
| 116 | + if not r.ok: |
| 117 | + raise ConnectionError("failed to fetch issuer certificate") |
| 118 | + der = r.content |
| 119 | + issuer_cert = self._bin2ascii(der) |
| 120 | + |
| 121 | + ocsp_url = self.build_certificate_url(server, cert, issuer_cert) |
| 122 | + |
| 123 | + # HTTP 1.1 mandates the addition of the Host header in ocsp responses |
| 124 | + header = { |
| 125 | + "Host": urlparse(ocsp_url).netloc, |
| 126 | + "Content-Type": "application/ocsp-request", |
| 127 | + } |
| 128 | + r = requests.get(ocsp_url, headers=header) |
| 129 | + if not r.ok: |
| 130 | + raise ConnectionError("failed to fetch ocsp certificate") |
| 131 | + |
| 132 | + ocsp_response = ocsp.load_der_ocsp_response(r.content) |
| 133 | + if ocsp_response.response_status == ocsp.OCSPResponseStatus.UNAUTHORIZED: |
| 134 | + raise AuthorizationError( |
| 135 | + "you are not authorized to view this ocsp certificate" |
| 136 | + ) |
| 137 | + if ocsp_response.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL: |
| 138 | + if ocsp_response.certificate_status == ocsp.OCSPCertStatus.REVOKED: |
| 139 | + return False |
| 140 | + else: |
| 141 | + return True |
| 142 | + else: |
| 143 | + return False |
| 144 | + |
| 145 | + def is_valid(self): |
| 146 | + """Returns the validity of the certificate wrapping our socket. |
| 147 | + This first retrieves for validate the certificate, issuer_url, |
| 148 | + and ocsp_server for certificate validate. Then retrieves the |
| 149 | + issuer certificate from the issuer_url, and finally checks |
| 150 | + the valididy of OCSP revocation status. |
| 151 | + """ |
| 152 | + |
| 153 | + # validate the certificate |
| 154 | + try: |
| 155 | + cert, issuer_url, ocsp_server = self.components_from_socket() |
| 156 | + return self.check_certificate(ocsp_server, cert, issuer_url) |
| 157 | + except AuthorizationError: |
| 158 | + cert, issuer_url, ocsp_server = self.components_from_direct_connection() |
| 159 | + return self.check_certificate(ocsp_server, cert, issuer_url) |
0 commit comments