2.3. API Reference¶
2.3.1. Classes¶
2.3.1.1. Store Classes¶
-
class
cert_human.
CertStore
(x509)[source]¶ Bases:
object
Make SSL certs and their attributes generally more accessible.
Examples
>>> # x509 cert from any number of methods >>> cert = CertStore(OpenSSL.crypto.X509) >>> # not echoing any of these due to length >>> print(cert) # print the basic info for this cert >>> x = cert.issuer # get a dict of the issuer info. >>> print(cert.issuer_str) # print the issuer in str form. >>> x = cert.subject # get a dict of the subject info. >>> print(cert.subject_str) # print the subject in str form. >>> print(cert.dump_str_exts) # print the extensions in str form. >>> print(cert.pem) # print the PEM version. >>> print(cert.public_key_str) # print the public key. >>> print(cert.dump_str_key) # print a bunch of public key info. >>> print(cert.dump_str_info) # print what str(cert) prints. >>> x = cert.dump # get a dict of ALL attributes. >>> x = cert.dump_json_friendly # dict of JSON friendly attrs. >>> print(cert.dump_json) # JSON str of JSON friendly attrs. >>> # and so on
Notes
The whole point of this was to be able to provide the same kind of information that is seen when looking at an SSL cert in a browser. This can be used to prompt for validity before doing “something”. For instance:
- If no cert provided, get the cert and prompt user for validity before continuing.
- If no cert provided, get cert, prompt for validity, then write to disk for using in further connections.
- … to print it out and hang it on the wall???
-
classmethod
from_socket
(host, port=443)[source]¶ Make instance of this cls using socket module to get the cert.
Examples
>>> cert = CertStore.from_socket("cyborg") >>> print(cert)
Parameters: Returns:
-
classmethod
from_request
(host, port=443)[source]¶ Make instance of this cls using requests module to get the cert.
Examples
>>> cert = CertStore.from_request("cyborg") >>> print(cert)
Parameters: Returns:
-
classmethod
from_response
(response)[source]¶ Make instance of this cls using a requests.Response object.
Examples
>>> enable_urllib3_patch() >>> response = requests.get("https://cyborg", verify=False) >>> cert = CertStore.from_response(response) >>> print(cert)
Notes
This relies on the fact that
enable_urllib3_patch()
has been used to add the SSL attributes to therequests.Response
.raw object.Parameters: response ( requests.Response
) – response object to get raw.peer_cert.Returns: ( CertStore
)
-
classmethod
from_auto
(obj)[source]¶ Make instance of this cls from a number of types.
- :param obj (
str
orbytes
orOpenSSL.crypto.X509
or:X509.Certificate
orrequests.Response
): - Object to create CertStore.
Returns: ( CertStore
)- :param obj (
-
classmethod
from_path
(path)[source]¶ Make instance of this cls from a file containing a PEM.
Parameters: path ( str
orpathlib.Path
) – Path to file containing PEM.Returns: ( CertStore
)
-
x509
¶ Return the original x509 cert object.
Returns: ( OpenSSL.crypto.X509
)
-
asn1
¶ Return the ASN1 version of the original x509 cert object.
Returns: ( x509.Certificate
)
-
to_path
(path, overwrite=False, mkparent=True, protect=True)[source]¶ Write self.pem to disk.
Examples
>>> # get a cert using sockets: >>> cert = CertStore.from_socket("cyborg") >>> # or, get a cert using requests: >>> cert = CertStore.from_request("cyborg")
>>> # ideally, do some kind of validation with the user here >>> # i.e. use ``print(cert.dump_str)`` to show the same >>> # kind of information that a browser would show
>>> # then write to disk: >>> cert_path = cert.to_path("~/cyborg.pem")
>>> # use requests with the newly written cert >>> # no SSL warnings or SSL validation errors happen >>> # even though it's self signed: >>> response = requests.get("https://cyborg", verify=cert_path)
Parameters: path ( str
orpathlib.Path
) – Path to write self.pem.Returns: ( pathlib.Path
)
-
test
(host, port=443, **kwargs)[source]¶ Test that a cert is valid on a site.
Parameters: Returns: True / False if cert was valid. Exception that was thrown if cert not valid, or None if successful.
Return type:
-
public_key
¶ Public key in hex format.
Notes
EC certs don’t have a modulus, and thus public_key in asn1 obj is not a dict, just the cert itself.
Returns: ( str
)
-
serial_number
¶ Certificate serial number.
Returns: int if algorithm is ‘ec’, or hex str. Return type: ( str
orint
)
-
serial_number_str
¶ Certificate serial number.
Returns: int if algorithm is ‘ec’, or spaced and wrapped hex str. Return type: ( str
orint
)
-
is_self_signed
¶ Determine if this certificate is self_sign.
Returns: (‘yes’, ‘maybe’, or ‘no’) Return type: ( str
)
-
not_valid_before
¶ Certificate valid start date as datetime object.
Returns: ( datetime.datetime
)
-
not_valid_after
¶ Certificate valid end date as datetime object.
Returns: ( datetime.datetime
)
-
class
cert_human.
CertChainStore
(x509=None)[source]¶ Bases:
object
Make SSL cert chains and their attributes generally more accessible.
This is really just a list container for a cert chain, which is just a list of x509 certs.
-
append
(value)[source]¶ Passthru to self._certs.append with automatic conversion for PEM or X509.
Parameters: value ( str
orOpenSSL.crypto.X509
orCertStore
) –
-
classmethod
from_socket
(host, port=443)[source]¶ Make instance of this cls using socket module to get the cert chain.
Examples
>>> cert_chain = CertChainStore.from_socket("cyborg") >>> print(cert_chain)
Parameters: Returns:
-
classmethod
from_request
(host, port=443)[source]¶ Make instance of this cls using requests module to get the cert chain.
Examples
>>> cert_chain = CertChainStore.from_request("cyborg") >>> print(cert_chain)
Parameters: Returns:
-
classmethod
from_response
(response)[source]¶ Make instance of this cls using a requests.Response.raw object.
Examples
>>> enable_urllib3_patch() >>> response = requests.get("https://cyborg", verify=False) >>> cert_chain = CertChainStore.from_response(response) >>> print(cert_chain)
Notes
This relies on the fact that
enable_urllib3_patch()
has been used to add the SSL attributes to therequests.Response
.raw object.Parameters: response ( requests.Response
) – response object to get raw.peer_cert_chain from.Returns: ( CertChainStore
)
-
classmethod
from_pem
(pem)[source]¶ Make instance of this cls from a string containing multiple PEM certs.
Parameters: pem ( str
) – PEM string with multiple pems to convert to x509.Returns: ( CertChainStore
)
-
classmethod
from_path
(path)[source]¶ Make instance of this cls from a file containing PEMs.
Parameters: path ( str
orpathlib.Path
) – Path to file containing PEMs.Returns: ( CertChainStore
)
-
certs
¶ Expose self._certs list container.
-
pem
¶ Return all of the joined PEM strings for each cert in self.
Returns: all PEM strings joined. Return type: ( str
)
-
x509
¶ Return the X509 version of the each CertStore in self.
Returns: ( list
ofx509.Certificate
)
-
asn1
¶ Return the asn1crypto X509 version of the each CertStore in self.
Returns: ( list
ofx509.Certificate
)
-
to_path
(path, overwrite=False, mkparent=True, protect=True)[source]¶ Write self.pem to disk.
Parameters: path ( str
orpathlib.Path
) – Path to write self.pem to.Returns: ( pathlib.Path
)
-
dump_json_friendly
¶ Dump dict with all attributes of each cert in self that are JSON friendly.
Returns: ( list
ofdict
)
-
dump_json
¶ Dump JSON string with all attributes of each cert in self that are JSON friendly.
Returns: ( str
)
-
dump_str
¶ Dump a human friendly str of the all the important bits for each cert in self.
Returns: ( str
)
-
dump_str_info
¶ Dump a human friendly str of the important cert info bits for each cert in self.
Returns: ( str
)
-
2.3.1.2. WithCert Classes¶
-
class
cert_human.
HTTPSConnectionWithCertCls
(host, port=None, key_file=None, cert_file=None, key_password=None, strict=None, timeout=<object object>, ssl_context=None, server_hostname=None, **kw)[source]¶
-
class
cert_human.
ResponseWithCertCls
(*args, **kwargs)[source]¶ Bases:
urllib3.response.HTTPResponse
-
_set_cert_attrs
()[source]¶ Add cert info from a HTTPSConnection object to a HTTPSResponse object.
This allows accessing the attributes in a HTTPSConnectionWithCertCls from a requests.Response.raw object like so:
requests.Response
.raw.peer_certrequests.Response
.raw.peer_cert_chainrequests.Response
.raw.peer_cert_dict
-
_abc_impl
= <_abc_data object>¶
-
2.3.2. Functions¶
2.3.2.1. Get Cert Functions¶
-
cert_human.
get_response
(host, port=443, **kwargs)[source]¶ Get a requests.Response object with cert attributes.
Examples
Make a request to a site that has a valid cert:
>>> response = get_response(host="www.google.com") >>> print(response.raw.peer_cert.get_subject().get_components()) >>> print(response.raw.peer_cert_chain) >>> print(response.raw.peer_cert_dict)
Make a request to a site that has an invalid cert (self-signed):
>>> response = get_response(host="cyborg") >>> print(response.raw.peer_cert.get_subject().get_components())
Notes
This is to fetch a requests.Response object that has cert attributes.
- Uses a context manager to disable warnings about SSL cert validation.
- Uses a context manager to patch urllib3 to add SSL cert attributes
to the HTTPSResponse object, which is then accessible via the
requests.Response
.raw object. - Makes a request to a server using
requests.get()
Parameters: Returns:
-
cert_human.
ssl_socket
(host, port=443, *args, **kwargs)[source]¶ Context manager to create an SSL socket.
Examples
Use sockets and OpenSSL to make a request using this context manager:
>>> with ssl_socket(host="cyborg", port=443) as sock: ... cert = sock.get_peer_certificate() ... cert_chain = sock.get_peer_cert_chain() ... >>> print(cert.get_subject().get_components()) >>> print(cert_chain)
Parameters: Yields:
-
cert_human.
test_cert
(host, port=443, timeout=5, **kwargs)[source]¶ Test that a cert is valid on a site.
Parameters: - host (
str
) – hostname to connect to. can be any of: “scheme://host:port”, “scheme://host”, or “host”. - port (
str
, optional) – port to connect to on host. If no :PORT in host, this will be added to host. Defaults to: 443 - timeout (
str
, optional) – Timeout for connect/response. Defaults to: 5. - kwargs – passed thru to requests.get()
Returns: True / False if cert was valid. Exception that was thrown if cert not valid, or None if successfull.
Return type: - host (
2.3.2.2. WithCert Functions¶
-
cert_human.
enable_urllib3_patch
()[source]¶ Patch HTTPSConnectionPool to use the WithCert Connect/Response classes.
Examples
Make a request using
requests
and patch urllib3 until you want to unpatch it:>>> enable_urllib3_patch() >>> response1 = requests.get("https://www.google.com") >>> # self-signed, don't verify >>> response2 = requests.get("https://cyborg", verify=False) >>> print(response1.raw.peer_cert.get_subject().get_components()) >>> print(response2.raw.peer_cert.get_subject().get_components()) >>> # optionally disable the urllib3 patch once you no longer need >>> # to make requests with the cert attributes attached >>> disable_urllib3_patch()
Notes
Modifies
urllib3.connectionpool.HTTPSConnectionPool
attributesurllib3.connectionpool.HTTPSConnectionPool.ConnectionCls
andurllib3.connectionpool.HTTPSConnectionPool.ResponseCls
to the WithCert classes.
-
cert_human.
disable_urllib3_patch
()[source]¶ Unpatch HTTPSConnectionPool to use the default Connect/Response classes.
Notes
Modifies
urllib3.connectionpool.HTTPSConnectionPool
attributesurllib3.connectionpool.HTTPSConnectionPool.ConnectionCls
andurllib3.connectionpool.HTTPSConnectionPool.ResponseCls
back to original classes.
-
cert_human.
urllib3_patch
()[source]¶ Context manager to enable/disable cert patch.
Examples
Make a request using
requests
using this context manager to patch urllib3:>>> import requests >>> with urllib3_patch(): ... response = requests.get("https://www.google.com") ... >>> print(response.raw.peer_cert.get_subject().get_components())
-
cert_human.
using_urllib3_patch
()[source]¶ Check if urllib3 is patched with the WithCert classes.
Returns: ( bool
)
-
cert_human.
check_urllib3_patch
()[source]¶ Throw exception if urllib3 is not patched with the WithCert classes.
Raises: ( CertHumanError
) – if using_urllib3_patch() returns False.
2.3.2.3. Conversion Functions¶
-
cert_human.
asn1_to_der
(asn1)[source]¶ Convert from asn1crypto x509 to DER bytes.
Parameters: asn1 ( x509.Certificate
) – asn1crypto x509 to convert to DER bytesReturns: ( bytes
)
-
cert_human.
asn1_to_x509
(asn1)[source]¶ Convert from asn1crypto x509 to OpenSSL x509.
Parameters: asn1 ( x509.Certificate
) – asn1crypto x509 to convert to OpenSSL x509Returns: ( OpenSSL.crypto.X509
)
-
cert_human.
der_to_asn1
(der)[source]¶ Convert from DER bytes to asn1crypto x509.
Parameters: der ( bytes
) – DER bytes string to convert tox509.Certificate
.Returns: ( x509.Certificate
)
-
cert_human.
der_to_x509
(der)[source]¶ Convert from DER bytes to OpenSSL x509.
Parameters: der ( bytes
) – DER bytes string to convert tox509.Certificate
.Returns: ( OpenSSL.crypto.X509
)
-
cert_human.
pem_to_x509
(pem)[source]¶ Convert from PEM str to OpenSSL x509.
Parameters: pem ( str
) – PEM string to convert to x509 certificate object.Returns: ( OpenSSL.crypto.X509
)
-
cert_human.
pems_to_x509
(pem)[source]¶ Convert from PEM str with multiple certs to list of OpenSSL x509s.
Parameters: pem ( str
) – PEM string with multiple certs to convert to x509 certificate object.Returns: ( list
ofOpenSSL.crypto.X509
)
-
cert_human.
x509_to_asn1
(x509)[source]¶ Convert from OpenSSL x509 to asn1crypto x509.
Parameters: x509 ( OpenSSL.crypto.X509
) – x509 object to convert tox509.Certificate
.Returns: ( x509.Certificate
)
-
cert_human.
x509_to_der
(x509)[source]¶ Convert from OpenSSL x509 to DER bytes.
Parameters: x509 ( OpenSSL.crypto.X509
) – x509 certificate object to convert to DER.Returns: ( bytes
)
-
cert_human.
x509_to_pem
(x509)[source]¶ Convert from OpenSSL x509 to PEM str.
Parameters: x509 ( OpenSSL.crypto.X509
) – x509 certificate object to convert to PEM.Returns: ( str
)
2.3.2.4. Utility Functions¶
-
cert_human.
clsname
(obj)[source]¶ Get objects class name.
Parameters: obj ( object
) – The object or class to get the name of.Returns: ( str
)
-
cert_human.
hexify
(obj, space=False, every=2, zerofill=True)[source]¶ Convert bytes, int, or str to hex and optionally space it out.
Parameters: - obj (
str
orint
orbytes
) – The object to convert into hex. - zerofill (
bool
, optional) – Zero fill the string if len is not even. This gets around oddly sized hex strings. Defaults to: True. - space (
bool
, optional) – Space the output string using join. Defaults to: False. - join (
str
, optional) – Rejoining str. Defaults to: ” “. - every (
str
, optional) – The number of characters to split on. Defaults to: 2.
Returns: (
str
)- obj (
-
cert_human.
write_file
(path, text, overwrite=False, mkparent=True, protect=True)[source]¶ Write text to path.
Parameters: - path (
str
orpathlib.Path
) – The path to write text to. - text (
str
) – The text to write to path. - overwrite (
bool
, optional) – Overwite file if exists. Defaults to: False. - mkparent (
bool
, optional) – Create parent directory if not exist. Defaults to: True. - protect (
bool
, optional) – Set file 0600 and parent 0700. Defaults to: True.
Raises: (
CertHumanError
) – path exists and not overwrite, parent not exist and not mkparent.Returns: - path (
-
cert_human.
read_file
(path)[source]¶ Read text from path.
Parameters: path ( str
orpathlib.Path
) – Path to file to read.Raises: ( CertHumanError
) – if path does not exist.Returns: ( str
)