Repository: certbot/certbot

Issue:
Only conditionally use openssl command line
In [cryptography 2.4](https://github.com/pyca/cryptography/blob/master/CHANGELOG.rst#24---2018-11-11) added support for making OCSP queries which I requested at https://github.com/pyca/cryptography/pull/4261#issuecomment-410908923.

We currently [shell out to openssl](https://github.com/certbot/certbot/blob/master/certbot/ocsp.py#L52) for this. Doing this makes things like Windows support and our new packaging harder because we depend on the openssl command line which must be installed in an OS specific way.

I think we should change this code to only conditionally shell out to `openssl` when the necessary features in `cryptography` aren't available. In the future, we can hopefully remove the code that shells out all together, but I think we need it while we are relying on packaging from Linux distros.

cc @adferrand 


Discussion:
@bmw you can assign me this. Is it acceptable to move pinned version of cryptography from 2.2 to 2.4? 
Thanks Adrien!

It's totally fine to update the pinned cryptography version. I'd use their latest bug fix version in the 2.4 series which as of writing this is 2.4.2.

In general, we can pin whatever versions we want in `certbot-auto`. The only concern is one of our dependencies dropping support for an environment we still want to support ourselves which cryptography hasn't done here.

Resolving patch:
diff --git a/certbot/crypto_util.py b/certbot/crypto_util.py
--- a/certbot/crypto_util.py
+++ b/certbot/crypto_util.py
@@ -19,7 +19,7 @@
 from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
 from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
 # https://github.com/python/typeshed/tree/master/third_party/2/cryptography
-from cryptography import x509 # type: ignore
+from cryptography import x509  # type: ignore
 from OpenSSL import crypto
 from OpenSSL import SSL  # type: ignore
 
@@ -226,7 +226,7 @@ def verify_renewable_cert(renewable_cert):
 
 
 def verify_renewable_cert_sig(renewable_cert):
-    """ Verifies the signature of a `.storage.RenewableCert` object.
+    """Verifies the signature of a `.storage.RenewableCert` object.
 
     :param `.storage.RenewableCert` renewable_cert: cert to verify
 
@@ -239,22 +239,8 @@ def verify_renewable_cert_sig(renewable_cert):
             cert = x509.load_pem_x509_certificate(cert_file.read(), default_backend())
         pk = chain.public_key()
         with warnings.catch_warnings():
-            warnings.simplefilter("ignore")
-            if isinstance(pk, RSAPublicKey):
-                # https://github.com/python/typeshed/blob/master/third_party/2/cryptography/hazmat/primitives/asymmetric/rsa.pyi
-                verifier = pk.verifier(  # type: ignore
-                    cert.signature, PKCS1v15(), cert.signature_hash_algorithm
-                )
-                verifier.update(cert.tbs_certificate_bytes)
-                verifier.verify()
-            elif isinstance(pk, EllipticCurvePublicKey):
-                verifier = pk.verifier(
-                    cert.signature, ECDSA(cert.signature_hash_algorithm)
-                )
-                verifier.update(cert.tbs_certificate_bytes)
-                verifier.verify()
-            else:
-                raise errors.Error("Unsupported public key type")
+            verify_signed_payload(pk, cert.signature, cert.tbs_certificate_bytes,
+                                  cert.signature_hash_algorithm)
     except (IOError, ValueError, InvalidSignature) as e:
         error_str = "verifying the signature of the cert located at {0} has failed. \
                 Details: {1}".format(renewable_cert.cert, e)
@@ -262,6 +248,37 @@ def verify_renewable_cert_sig(renewable_cert):
         raise errors.Error(error_str)
 
 
+def verify_signed_payload(public_key, signature, payload, signature_hash_algorithm):
+    """Check the signature of a payload.
+
+    :param RSAPublicKey/EllipticCurvePublicKey public_key: the public_key to check signature
+    :param bytes signature: the signature bytes
+    :param bytes payload: the payload bytes
+    :param cryptography.hazmat.primitives.hashes.HashAlgorithm
+           signature_hash_algorithm: algorithm used to hash the payload
+
+    :raises InvalidSignature: If signature verification fails.
+    :raises errors.Error: If public key type is not supported
+    """
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore")
+        if isinstance(public_key, RSAPublicKey):
+            # https://github.com/python/typeshed/blob/master/third_party/2/cryptography/hazmat/primitives/asymmetric/rsa.pyi
+            verifier = public_key.verifier(  # type: ignore
+                signature, PKCS1v15(), signature_hash_algorithm
+            )
+            verifier.update(payload)
+            verifier.verify()
+        elif isinstance(public_key, EllipticCurvePublicKey):
+            verifier = public_key.verifier(
+                signature, ECDSA(signature_hash_algorithm)
+            )
+            verifier.update(payload)
+            verifier.verify()
+        else:
+            raise errors.Error("Unsupported public key type")
+
+
 def verify_cert_matches_priv_key(cert_path, key_path):
     """ Verifies that the private key and cert match.
 
diff --git a/certbot/ocsp.py b/certbot/ocsp.py
--- a/certbot/ocsp.py
+++ b/certbot/ocsp.py
@@ -1,53 +1,79 @@
 """Tools for checking certificate revocation."""
 import logging
 import re
-
+from datetime import datetime, timedelta
 from subprocess import Popen, PIPE
 
+try:
+    # Only cryptography>=2.5 has ocsp module
+    # and signature_hash_algorithm attribute in OCSPResponse class
+    from cryptography.x509 import ocsp  # pylint: disable=import-error
+    getattr(ocsp.OCSPResponse, 'signature_hash_algorithm')
+except (ImportError, AttributeError):  # pragma: no cover
+    ocsp = None  # type: ignore
+from cryptography import x509
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives import hashes  # type: ignore
+from cryptography.exceptions import UnsupportedAlgorithm, InvalidSignature
+import requests
+
+from acme.magic_typing import Optional, Tuple  # pylint: disable=unused-import, no-name-in-module
+from certbot import crypto_util
 from certbot import errors
 from certbot import util
 
 logger = logging.getLogger(__name__)
 
+
 class RevocationChecker(object):
-    "This class figures out OCSP checking on this system, and performs it."
+    """This class figures out OCSP checking on this system, and performs it."""
 
-    def __init__(self):
+    def __init__(self, enforce_openssl_binary_usage=False):
         self.broken = False
-
-        if not util.exe_exists("openssl"):
-            logger.info("openssl not installed, can't check revocation")
-            self.broken = True
-            return
-
-       # New versions of openssl want -header var=val, old ones want -header var val
-        test_host_format = Popen(["openssl", "ocsp", "-header", "var", "val"],
-                                 stdout=PIPE, stderr=PIPE, universal_newlines=True)
-        _out, err = test_host_format.communicate()
-        if "Missing =" in err:
-            self.host_args = lambda host: ["Host=" + host]
-        else:
-            self.host_args = lambda host: ["Host", host]
-
+        self.use_openssl_binary = enforce_openssl_binary_usage or not ocsp
+
+        if self.use_openssl_binary:
+            if not util.exe_exists("openssl"):
+                logger.info("openssl not installed, can't check revocation")
+                self.broken = True
+                return
+
+            # New versions of openssl want -header var=val, old ones want -header var val
+            test_host_format = Popen(["openssl", "ocsp", "-header", "var", "val"],
+                                     stdout=PIPE, stderr=PIPE, universal_newlines=True)
+            _out, err = test_host_format.communicate()
+            if "Missing =" in err:
+                self.host_args = lambda host: ["Host=" + host]
+            else:
+                self.host_args = lambda host: ["Host", host]
 
     def ocsp_revoked(self, cert_path, chain_path):
+        # type: (str, str) -> bool
         """Get revoked status for a particular cert version.
 
         .. todo:: Make this a non-blocking call
 
         :param str cert_path: Path to certificate
         :param str chain_path: Path to intermediate cert
-        :rtype bool or None:
         :returns: True if revoked; False if valid or the check failed
+        :rtype: bool
 
         """
         if self.broken:
             return False
 
-
-        url, host = self.determine_ocsp_server(cert_path)
-        if not host:
+        url, host = _determine_ocsp_server(cert_path)
+        if not host or not url:
             return False
+
+        if self.use_openssl_binary:
+            return self._check_ocsp_openssl_bin(cert_path, chain_path, host, url)
+        else:
+            return _check_ocsp_cryptography(cert_path, chain_path, url)
+
+    def _check_ocsp_openssl_bin(self, cert_path, chain_path, host, url):
+        # type: (str, str, str, str) -> bool
         # jdkasten thanks "Bulletproof SSL and TLS - Ivan Ristic" for documenting this!
         cmd = ["openssl", "ocsp",
                "-no_nonce",
@@ -65,33 +91,117 @@ def ocsp_revoked(self, cert_path, chain_path):
         except errors.SubprocessError:
             logger.info("OCSP check failed for %s (are we offline?)", cert_path)
             return False
-
         return _translate_ocsp_query(cert_path, output, err)
 
 
-    def determine_ocsp_server(self, cert_path):
-        """Extract the OCSP server host from a certificate.
+def _determine_ocsp_server(cert_path):
+    # type: (str) -> Tuple[Optional[str], Optional[str]]
+    """Extract the OCSP server host from a certificate.
 
-        :param str cert_path: Path to the cert we're checking OCSP for
-        :rtype tuple:
-        :returns: (OCSP server URL or None, OCSP server host or None)
+    :param str cert_path: Path to the cert we're checking OCSP for
+    :rtype tuple:
+    :returns: (OCSP server URL or None, OCSP server host or None)
 
-        """
-        try:
-            url, _err = util.run_script(
-                ["openssl", "x509", "-in", cert_path, "-noout", "-ocsp_uri"],
-                log=logger.debug)
-        except errors.SubprocessError:
-            logger.info("Cannot extract OCSP URI from %s", cert_path)
-            return None, None
+    """
+    with open(cert_path, 'rb') as file_handler:
+        cert = x509.load_pem_x509_certificate(file_handler.read(), default_backend())
+    try:
+        extension = cert.extensions.get_extension_for_class(x509.AuthorityInformationAccess)
+        ocsp_oid = x509.AuthorityInformationAccessOID.OCSP
+        descriptions = [description for description in extension.value
+                        if description.access_method == ocsp_oid]
+
+        url = descriptions[0].access_location.value
+    except (x509.ExtensionNotFound, IndexError):
+        logger.info("Cannot extract OCSP URI from %s", cert_path)
+        return None, None
+
+    url = url.rstrip()
+    host = url.partition("://")[2].rstrip("/")
+
+    if host:
+        return url, host
+    else:
+        logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path)
+        return None, None
+
+
+def _check_ocsp_cryptography(cert_path, chain_path, url):
+    # type: (str, str, str) -> bool
+    # Retrieve OCSP response
+    with open(chain_path, 'rb') as file_handler:
+        issuer = x509.load_pem_x509_certificate(file_handler.read(), default_backend())
+    with open(cert_path, 'rb') as file_handler:
+        cert = x509.load_pem_x509_certificate(file_handler.read(), default_backend())
+    builder = ocsp.OCSPRequestBuilder()
+    builder = builder.add_certificate(cert, issuer, hashes.SHA1())
+    request = builder.build()
+    request_binary = request.public_bytes(serialization.Encoding.DER)
+    response = requests.post(url, data=request_binary,
+                             headers={'Content-Type': 'application/ocsp-request'})
+    if response.status_code != 200:
+        logger.info("OCSP check failed for %s (are we offline?)", cert_path)
+        return False
+    response_ocsp = ocsp.load_der_ocsp_response(response.content)
+
+    # Check OCSP response validity
+    if response_ocsp.response_status != ocsp.OCSPResponseStatus.SUCCESSFUL:
+        logger.error("Invalid OCSP response status for %s: %s",
+                     cert_path, response_ocsp.response_status)
+        return False
+
+    # Check OCSP signature
+    try:
+        _check_ocsp_response(response_ocsp, request, issuer)
+    except UnsupportedAlgorithm as e:
+        logger.error(str(e))
+    except errors.Error as e:
+        logger.error(str(e))
+    except InvalidSignature:
+        logger.error('Invalid signature on OCSP response for %s', cert_path)
+    except AssertionError as error:
+        logger.error('Invalid OCSP response for %s: %s.', cert_path, str(error))
+    else:
+        # Check OCSP certificate status
+        logger.debug("OCSP certificate status for %s is: %s",
+                     cert_path, response_ocsp.certificate_status)
+        return response_ocsp.certificate_status == ocsp.OCSPCertStatus.REVOKED
+
+    return False
+
+
+def _check_ocsp_response(response_ocsp, request_ocsp, issuer_cert):
+    """Verify that the OCSP is valid for serveral criterias"""
+    # Assert OCSP response corresponds to the certificate we are talking about
+    if response_ocsp.serial_number != request_ocsp.serial_number:
+        raise AssertionError('the certificate in response does not correspond '
+                             'to the certificate in request')
+
+    # Assert signature is valid
+    _check_ocsp_response_signature(response_ocsp, issuer_cert)
+
+    # Assert issuer in response is the expected one
+    if (not isinstance(response_ocsp.hash_algorithm, type(request_ocsp.hash_algorithm))
+            or response_ocsp.issuer_key_hash != request_ocsp.issuer_key_hash
+            or response_ocsp.issuer_name_hash != request_ocsp.issuer_name_hash):
+        raise AssertionError('the issuer does not correspond to issuer of the certificate.')
+
+    # Assert nextUpdate is in the future, and that thisUpdate is not too old
+    if response_ocsp.next_update:
+        if response_ocsp.next_update < datetime.now() - timedelta(minutes=5):
+            raise AssertionError('next update is in the past.')
+        interval = response_ocsp.next_update - response_ocsp.this_update
+        if datetime.now() - response_ocsp.this_update > interval + timedelta(minutes=5):
+            raise AssertionError('this update is too old.')
+
+
+def _check_ocsp_response_signature(response_ocsp, issuer_cert):
+    """Verify an OCSP response signature against certificate issuer"""
+    # Following line may raise UnsupportedAlgorithm
+    chosen_hash = response_ocsp.signature_hash_algorithm
+    crypto_util.verify_signed_payload(issuer_cert.public_key(), response_ocsp.signature,
+                                      response_ocsp.tbs_response_bytes, chosen_hash)
 
-        url = url.rstrip()
-        host = url.partition("://")[2].rstrip("/")
-        if host:
-            return url, host
-        else:
-            logger.info("Cannot process OCSP host from URL (%s) in cert at %s", url, cert_path)
-            return None, None
 
 def _translate_ocsp_query(cert_path, ocsp_output, ocsp_errors):
     """Parse openssl's weird output to work out what it means."""
@@ -102,7 +212,7 @@ def _translate_ocsp_query(cert_path, ocsp_output, ocsp_errors):
 
     warning = good.group(1) if good else None
 
-    if (not "Response verify OK" in ocsp_errors) or (good and warning) or unknown:
+    if ("Response verify OK" not in ocsp_errors) or (good and warning) or unknown:
         logger.info("Revocation status for %s is unknown", cert_path)
         logger.debug("Uncertain output:\n%s\nstderr:\n%s", ocsp_output, ocsp_errors)
         return False
@@ -115,6 +225,5 @@ def _translate_ocsp_query(cert_path, ocsp_output, ocsp_errors):
         return True
     else:
         logger.warning("Unable to properly parse OCSP output: %s\nstderr:%s",
-                    ocsp_output, ocsp_errors)
+                       ocsp_output, ocsp_errors)
         return False
-
diff --git a/certbot/util.py b/certbot/util.py
--- a/certbot/util.py
+++ b/certbot/util.py
@@ -62,7 +62,7 @@ def run_script(params, log=logger.error):
     """Run the script with the given params.
 
     :param list params: List of parameters to pass to Popen
-    :param logging.Logger log: Logger to use for errors
+    :param callable log: Logger method to use for errors
 
     """
     try:


Test patch:
diff --git a/certbot/tests/ocsp_test.py b/certbot/tests/ocsp_test.py
--- a/certbot/tests/ocsp_test.py
+++ b/certbot/tests/ocsp_test.py
@@ -1,18 +1,33 @@
 """Tests for ocsp.py"""
 # pylint: disable=protected-access
-
 import unittest
+from datetime import datetime, timedelta
 
+from cryptography.hazmat.backends import default_backend
+from cryptography.hazmat.primitives import hashes  # type: ignore
+from cryptography.exceptions import UnsupportedAlgorithm, InvalidSignature
+from cryptography import x509
+try:
+    # Only cryptography>=2.5 has ocsp module
+    # and signature_hash_algorithm attribute in OCSPResponse class
+    from cryptography.x509 import ocsp as ocsp_lib  # pylint: disable=import-error
+    getattr(ocsp_lib.OCSPResponse, 'signature_hash_algorithm')
+except (ImportError, AttributeError):  # pragma: no cover
+    ocsp_lib = None  # type: ignore
 import mock
 
 from certbot import errors
+from certbot.tests import util as test_util
 
 out = """Missing = in header key=value
 ocsp: Use -help for summary.
 """
 
-class OCSPTest(unittest.TestCase):
 
+class OCSPTestOpenSSL(unittest.TestCase):
+    """
+    OCSP revokation tests using OpenSSL binary.
+    """
 
     def setUp(self):
         from certbot import ocsp
@@ -22,7 +37,7 @@ def setUp(self):
                 mock_communicate.communicate.return_value = (None, out)
                 mock_popen.return_value = mock_communicate
                 mock_exists.return_value = True
-                self.checker = ocsp.RevocationChecker()
+                self.checker = ocsp.RevocationChecker(enforce_openssl_binary_usage=True)
 
     def tearDown(self):
         pass
@@ -37,23 +52,23 @@ def test_init(self, mock_exists, mock_popen, mock_log):
         mock_exists.return_value = True
 
         from certbot import ocsp
-        checker = ocsp.RevocationChecker()
+        checker = ocsp.RevocationChecker(enforce_openssl_binary_usage=True)
         self.assertEqual(mock_popen.call_count, 1)
         self.assertEqual(checker.host_args("x"), ["Host=x"])
 
         mock_communicate.communicate.return_value = (None, out.partition("\n")[2])
-        checker = ocsp.RevocationChecker()
+        checker = ocsp.RevocationChecker(enforce_openssl_binary_usage=True)
         self.assertEqual(checker.host_args("x"), ["Host", "x"])
         self.assertEqual(checker.broken, False)
 
         mock_exists.return_value = False
         mock_popen.call_count = 0
-        checker = ocsp.RevocationChecker()
+        checker = ocsp.RevocationChecker(enforce_openssl_binary_usage=True)
         self.assertEqual(mock_popen.call_count, 0)
         self.assertEqual(mock_log.call_count, 1)
         self.assertEqual(checker.broken, True)
 
-    @mock.patch('certbot.ocsp.RevocationChecker.determine_ocsp_server')
+    @mock.patch('certbot.ocsp._determine_ocsp_server')
     @mock.patch('certbot.util.run_script')
     def test_ocsp_revoked(self, mock_run, mock_determine):
         self.checker.broken = True
@@ -71,21 +86,12 @@ def test_ocsp_revoked(self, mock_run, mock_determine):
         self.assertEqual(self.checker.ocsp_revoked("x", "y"), False)
         self.assertEqual(mock_run.call_count, 2)
 
+    def test_determine_ocsp_server(self):
+        cert_path = test_util.vector_path('google_certificate.pem')
 
-    @mock.patch('certbot.ocsp.logger.info')
-    @mock.patch('certbot.util.run_script')
-    def test_determine_ocsp_server(self, mock_run, mock_info):
-        uri = "http://ocsp.stg-int-x1.letsencrypt.org/"
-        host = "ocsp.stg-int-x1.letsencrypt.org"
-        mock_run.return_value = uri, ""
-        self.assertEqual(self.checker.determine_ocsp_server("beep"), (uri, host))
-        mock_run.return_value = "ftp:/" + host + "/", ""
-        self.assertEqual(self.checker.determine_ocsp_server("beep"), (None, None))
-        self.assertEqual(mock_info.call_count, 1)
-
-        c = "confusion"
-        mock_run.side_effect = errors.SubprocessError(c)
-        self.assertEqual(self.checker.determine_ocsp_server("beep"), (None, None))
+        from certbot import ocsp
+        result = ocsp._determine_ocsp_server(cert_path)
+        self.assertEqual(('http://ocsp.digicert.com', 'ocsp.digicert.com'), result)
 
     @mock.patch('certbot.ocsp.logger')
     @mock.patch('certbot.util.run_script')
@@ -112,6 +118,129 @@ def test_translate_ocsp(self, mock_run, mock_log):
         self.assertEqual(mock_log.info.call_count, 1)
 
 
+@unittest.skipIf(not ocsp_lib,
+                 reason='This class tests functionalities available only on cryptography>=2.5.0')
+class OSCPTestCryptography(unittest.TestCase):
+    """
+    OCSP revokation tests using Cryptography >= 2.4.0
+    """
+
+    def setUp(self):
+        from certbot import ocsp
+        self.checker = ocsp.RevocationChecker()
+        self.cert_path = test_util.vector_path('google_certificate.pem')
+        self.chain_path = test_util.vector_path('google_issuer_certificate.pem')
+
+    @mock.patch('certbot.ocsp._determine_ocsp_server')
+    @mock.patch('certbot.ocsp._check_ocsp_cryptography')
+    def test_ensure_cryptography_toggled(self, mock_revoke, mock_determine):
+        mock_determine.return_value = ('http://example.com', 'example.com')
+        self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        mock_revoke.assert_called_once_with(self.cert_path, self.chain_path, 'http://example.com')
+
+    @mock.patch('certbot.ocsp.requests.post')
+    @mock.patch('certbot.ocsp.ocsp.load_der_ocsp_response')
+    def test_revoke(self, mock_ocsp_response, mock_post):
+        with mock.patch('certbot.ocsp.crypto_util.verify_signed_payload'):
+            mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+                ocsp_lib.OCSPCertStatus.REVOKED, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+            mock_post.return_value = mock.Mock(status_code=200)
+            revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertTrue(revoked)
+
+    @mock.patch('certbot.ocsp.crypto_util.verify_signed_payload')
+    @mock.patch('certbot.ocsp.requests.post')
+    @mock.patch('certbot.ocsp.ocsp.load_der_ocsp_response')
+    def test_revoke_resiliency(self, mock_ocsp_response, mock_post, mock_check):
+        # Server return an invalid HTTP response
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.UNKNOWN, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=400)
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # OCSP response in invalid
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.UNKNOWN, ocsp_lib.OCSPResponseStatus.UNAUTHORIZED)
+        mock_post.return_value = mock.Mock(status_code=200)
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # OCSP response is valid, but certificate status is unknown
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.UNKNOWN, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=200)
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # The OCSP response says that the certificate is revoked, but certificate
+        # does not contain the OCSP extension.
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.UNKNOWN, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=200)
+        with mock.patch('cryptography.x509.Extensions.get_extension_for_class',
+                        side_effect=x509.ExtensionNotFound(
+                            'Not found', x509.AuthorityInformationAccessOID.OCSP)):
+            revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # Valid response, OCSP extension is present,
+        # but OCSP response uses an unsupported signature.
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.REVOKED, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=200)
+        mock_check.side_effect = UnsupportedAlgorithm('foo')
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # And now, the signature itself is invalid.
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.REVOKED, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=200)
+        mock_check.side_effect = InvalidSignature('foo')
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+        # Finally, assertion error on OCSP response validity
+        mock_ocsp_response.return_value = _construct_mock_ocsp_response(
+            ocsp_lib.OCSPCertStatus.REVOKED, ocsp_lib.OCSPResponseStatus.SUCCESSFUL)
+        mock_post.return_value = mock.Mock(status_code=200)
+        mock_check.side_effect = AssertionError('foo')
+        revoked = self.checker.ocsp_revoked(self.cert_path, self.chain_path)
+
+        self.assertFalse(revoked)
+
+
+def _construct_mock_ocsp_response(certificate_status, response_status):
+    cert = x509.load_pem_x509_certificate(
+        test_util.load_vector('google_certificate.pem'), default_backend())
+    issuer = x509.load_pem_x509_certificate(
+        test_util.load_vector('google_issuer_certificate.pem'), default_backend())
+    builder = ocsp_lib.OCSPRequestBuilder()
+    builder = builder.add_certificate(cert, issuer, hashes.SHA1())
+    request = builder.build()
+
+    return mock.Mock(
+        response_status=response_status,
+        certificate_status=certificate_status,
+        serial_number=request.serial_number,
+        issuer_key_hash=request.issuer_key_hash,
+        issuer_name_hash=request.issuer_name_hash,
+        hash_algorithm=hashes.SHA1(),
+        next_update=datetime.now() + timedelta(days=1),
+        this_update=datetime.now() - timedelta(days=1),
+        signature_algorithm_oid=x509.oid.SignatureAlgorithmOID.RSA_WITH_SHA1,
+    )
+
+
 # pylint: disable=line-too-long
 openssl_confused = ("", """
 /etc/letsencrypt/live/example.org/cert.pem: good
@@ -165,5 +294,6 @@ def test_translate_ocsp(self, mock_run, mock_log):
 """,
 """Response verify OK""")
 
+
 if __name__ == '__main__':
     unittest.main()  # pragma: no cover
diff --git a/certbot/tests/testdata/google_certificate.pem b/certbot/tests/testdata/google_certificate.pem
new file mode 100644
--- /dev/null
+++ b/certbot/tests/testdata/google_certificate.pem
@@ -0,0 +1,41 @@
+-----BEGIN CERTIFICATE-----
+MIIHQjCCBiqgAwIBAgIQCgYwQn9bvO1pVzllk7ZFHzANBgkqhkiG9w0BAQsFADB1
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMTQwMgYDVQQDEytEaWdpQ2VydCBTSEEyIEV4dGVuZGVk
+IFZhbGlkYXRpb24gU2VydmVyIENBMB4XDTE4MDUwODAwMDAwMFoXDTIwMDYwMzEy
+MDAwMFowgccxHTAbBgNVBA8MFFByaXZhdGUgT3JnYW5pemF0aW9uMRMwEQYLKwYB
+BAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQITCERlbGF3YXJlMRAwDgYDVQQF
+Ewc1MTU3NTUwMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQG
+A1UEBxMNU2FuIEZyYW5jaXNjbzEVMBMGA1UEChMMR2l0SHViLCBJbmMuMRMwEQYD
+VQQDEwpnaXRodWIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+xjyq8jyXDDrBTyitcnB90865tWBzpHSbindG/XqYQkzFMBlXmqkzC+FdTRBYyneZ
+w5Pz+XWQ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EAAAAWNBYm0KAAAEAwBHMEUCIQDRZp38cTWsWH2GdBpe/uPT
+Wnsu/m4BEC2+dIcvSykZYgIgCP5gGv6yzaazxBK2NwGdmmyuEFNSg2pARbMJlUFg
+U5UAdgBWFAaaL9fC7NP14b1Esj7HRna5vJkRXMDvlJhV1onQ3QAAAWNBYm0tAAAE
+AwBHMEUCIQCi7omUvYLm0b2LobtEeRAYnlIo7n6JxbYdrtYdmPUWJQIgVgw1AZ51
+vK9ENinBg22FPxb82TvNDO05T17hxXRC2IYAdgC72d+8H4pxtZOUI5eqkntHOFeV
+CqtS6BqQlmQ2jh7RhQAAAWNBYm3fAAAEAwBHMEUCIQChzdTKUU2N+XcqcK0OJYrN
+8EYynloVxho4yPk6Dq3EPgIgdNH5u8rC3UcslQV4B9o0a0w204omDREGKTVuEpxG
+eOQwDQYJKoZIhvcNAQELBQADggEBAHAPWpanWOW/ip2oJ5grAH8mqQfaunuCVE+v
+ac+88lkDK/LVdFgl2B6kIHZiYClzKtfczG93hWvKbST4NRNHP9LiaQqdNC17e5vN
+HnXVUGw+yxyjMLGqkgepOnZ2Rb14kcTOGp4i5AuJuuaMwXmCo7jUwPwfLe1NUlVB
+Kqg6LK0Hcq4K0sZnxE8HFxiZ92WpV2AVWjRMEc/2z2shNoDvxvFUYyY1Oe67xINk
+myQKc+ygSBZzyLnXSFVWmHr3u5dcaaQGGAR42v6Ydr4iL38Hd4dOiBma+FXsXBIq
+WUjbST4VXmdaol7uzFMojA4zkxQDZAvF5XgJlAFadfySna/teik=
+-----END CERTIFICATE-----
diff --git a/certbot/tests/testdata/google_issuer_certificate.pem b/certbot/tests/testdata/google_issuer_certificate.pem
new file mode 100644
--- /dev/null
+++ b/certbot/tests/testdata/google_issuer_certificate.pem
@@ -0,0 +1,26 @@
+-----BEGIN CERTIFICATE-----
+MIIEXDCCA0SgAwIBAgINAeOpMBz8cgY4P5pTHTANBgkqhkiG9w0BAQsFADBMMSAw
+HgYDVQQLExdHbG9iYWxTaWduI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