Skip to content

Commit

Permalink
Allow Connection.get_certificate to return a cryptography certificate (
Browse files Browse the repository at this point in the history
  • Loading branch information
alex committed Aug 9, 2024
1 parent 265adc5 commit 38d8b04
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Deprecations:
Changes:
^^^^^^^^

* ``OpenSSL.SSL.Connection.get_certificate`` now takes an ``as_cryptography`` keyword-argument. When ``True`` is passed then a ``cryptography.x509.Certificate`` is returned, instead of an ``OpenSSL.crypto.X509``. In the future, passing ``False`` (the default) will be deprecated.


24.2.1 (2024-07-20)
-------------------
Expand Down
31 changes: 29 additions & 2 deletions src/OpenSSL/SSL.py
Original file line number Diff line number Diff line change
Expand Up @@ -2696,16 +2696,43 @@ def sock_shutdown(self, *args: Any, **kwargs: Any) -> None:
"""
return self._socket.shutdown(*args, **kwargs) # type: ignore[return-value, union-attr]

def get_certificate(self) -> X509 | None:
@typing.overload
def get_certificate(
self, *, as_cryptography: typing.Literal[True]
) -> x509.Certificate | None:
pass

@typing.overload
def get_certificate(
self, *, as_cryptography: typing.Literal[False] = False
) -> X509 | None:
pass

@typing.overload
def get_certificate(
self, *, as_cryptography: bool = False
) -> X509 | x509.Certificate | None:
pass

def get_certificate(
self, *, as_cryptography: bool = False
) -> X509 | x509.Certificate | None:
"""
Retrieve the local certificate (if any)
:param bool as_cryptography: Controls whether a
``cryptography.x509.Certificate`` or an ``OpenSSL.crypto.X509``
object should be returned.
:return: The local certificate
"""
cert = _lib.SSL_get_certificate(self._ssl)
if cert != _ffi.NULL:
_lib.X509_up_ref(cert)
return X509._from_raw_x509_ptr(cert)
pycert = X509._from_raw_x509_ptr(cert)
if as_cryptography:
return pycert.to_cryptography()
return pycert
return None

def get_peer_certificate(self) -> X509 | None:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2556,6 +2556,13 @@ def test_get_certificate(self):
assert cert is not None
assert "Server Certificate" == cert.get_subject().CN

cryptography_cert = client.get_certificate(as_cryptography=True)
assert cryptography_cert is not None
assert (
cryptography_cert.subject.rfc4514_string()
== "CN=Server Certificate"
)

def test_get_certificate_none(self):
"""
`Connection.get_certificate` returns the local certificate.
Expand Down

0 comments on commit 38d8b04

Please sign in to comment.