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???
__str__()[source]

Show dump_str_info.

__repr__()[source]

Use str() for repr().

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:
  • host (str) – hostname to connect to.
  • port (str, optional) – port to connect to on host. Defaults to: 443.
Returns:

(CertStore)

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:
  • host (str) – hostname to connect to.
  • port (str, optional) – port to connect to on host. Defaults to: 443.
Returns:

(CertStore)

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 the requests.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 or bytes or OpenSSL.crypto.X509 or: X509.Certificate or requests.Response):
Object to create CertStore.
Returns:(CertStore)
classmethod from_path(path)[source]

Make instance of this cls from a file containing a PEM.

Parameters:path (str or pathlib.Path) – Path to file containing PEM.
Returns:(CertStore)
pem

Return the PEM version of the original x509 cert object.

Returns:(str)
x509

Return the original x509 cert object.

Returns:(OpenSSL.crypto.X509)
der

Return the DER bytes version of the original x509 cert object.

Returns:(bytes)
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 or pathlib.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:
  • 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
  • kwargs – passed thru to requests.get()
Returns:

True / False if cert was valid. Exception that was thrown if cert not valid, or None if successful.

Return type:

(tuple of (bool, Exception))

issuer

Get issuer parts.

Returns:(dict)
issuer_str

Get issuer parts as string.

Returns:(str)
subject

Get subject parts.

Returns:(dict)
subject_str

Get subject parts as string.

Returns:(str)
subject_alt_names

Get subject alternate names.

Returns:(list of str)
subject_alt_names_str

Get subject alternate names as CSV string.

Returns:(str)
fingerprint_sha1

SHA1 Fingerprint.

Returns:(str)
fingerprint_sha256

SHA256 Fingerprint.

Returns:(str)
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)
public_key_str

Public key as in hex format spaced and wrapped.

Returns:(str)
public_key_parameters

Public key parameters, only for ‘ec’ certs.

Returns:(str)
public_key_algorithm

Algorithm of public key (‘ec’, ‘rsa’, ‘dsa’).

Returns:(str)
public_key_size

Size of public key in bits.

Returns:(int)
public_key_exponent

Public key exponent, only for ‘rsa’ certs.

Returns:(int)
signature

Signature in hex format.

Returns:(str)
signature_str

Signature in hex format spaced and wrapped.

Returns:(str)
signature_algorithm

Algorithm used to sign the public key certificate.

Returns:(str)
x509_version

Version of x509 this certificate is using.

Returns:(str)
serial_number

Certificate serial number.

Returns:int if algorithm is ‘ec’, or hex str.
Return type:(str or int)
serial_number_str

Certificate serial number.

Returns:int if algorithm is ‘ec’, or spaced and wrapped hex str.
Return type:(str or int)
is_expired

Determine if this certificate is expired.

Returns:(bool)
is_self_signed

Determine if this certificate is self_sign.

Returns:(‘yes’, ‘maybe’, or ‘no’)
Return type:(str)
is_self_issued

Determine if this certificate is self issued.

Returns:(bool)
not_valid_before

Certificate valid start date as datetime object.

Returns:(datetime.datetime)
not_valid_before_str

Certificate valid start date as str.

Returns:(str)
not_valid_after

Certificate valid end date as datetime object.

Returns:(datetime.datetime)
not_valid_after_str

Certificate valid end date as str.

Returns:(str)
extensions

Certificate extensions as dict.

Notes

Parsing the extensions was not easy. I sort of gave up at one point. Resorted to using str(extension) as OpenSSL returns it.

Returns:(dict)
extensions_str

Certificate extensions as str with index, name, and value.

Returns:(str)
dump

Dump dictionary with all attributes of self.

Returns:(dict)
dump_json_friendly

Dump dict with all attributes of self that are JSON friendly.

Returns:(dict)
dump_json

Dump JSON string with all attributes of self that are JSON friendly.

Returns:(str)
dump_str

Dump a human friendly str of the all the important bits.

Returns:(str)
dump_str_info

Dump a human friendly str of the important cert info bits.

Returns:(str)
dump_str_exts

Dump a human friendly str of the extensions.

Returns:(str)
dump_str_key

Dump a human friendly str of the public_key important bits.

Returns:(str)
_extension_str(ext)[source]

Format the string of an extension using str(extension).

Returns:(str)
_extensions

List mapping of extension name to extension object.

Returns:(list of list)
_public_key_native

Access self.asn1.public_key.

Returns:(dict)
_cert_native

Access to self.asn1.

Returns:(dict)
_is_ec

Determine if this certificates public key algorithm is Elliptic Curve (‘ec’).

Returns:(bool)
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.

__str__()[source]

Show most useful information of all certs in cert chain.

__repr__()[source]

Use str() for repr().

__getitem__(i)[source]

Passthru to self._certs[n].

__len__()[source]

Passthru to len(self._certs).

append(value)[source]

Passthru to self._certs.append with automatic conversion for PEM or X509.

Parameters:value (str or OpenSSL.crypto.X509 or CertStore) –
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:
  • host (str) – hostname to connect to.
  • port (str, optional) – port to connect to on host. Defaults to: 443.
Returns:

(CertChainStore)

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:
  • host (str) – hostname to connect to.
  • port (str, optional) – port to connect to on host. Defaults to: 443.
  • timeout (str, optional) – Timeout for connect/response. Defaults to: 5.
Returns:

(CertChainStore)

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 the requests.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 or pathlib.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 of x509.Certificate)
der

Return the DER bytes version of the each CertStore in self.

Returns:(list of bytes)
asn1

Return the asn1crypto X509 version of the each CertStore in self.

Returns:(list of x509.Certificate)
to_path(path, overwrite=False, mkparent=True, protect=True)[source]

Write self.pem to disk.

Parameters:path (str or pathlib.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 of dict)
dump_json

Dump JSON string with all attributes of each cert in self that are JSON friendly.

Returns:(str)
dump

Dump dictionary with all attributes of each cert in self.

Returns:(list of dict)
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)
dump_str_key

Dump a human friendly str of the public_key important bits for each cert in self.

Returns:(str)
dump_str_exts

Dump a human friendly str of the extensions 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]

Bases: urllib3.connection.VerifiedHTTPSConnection

connect()[source]

Connect to the host and port specified in __init__.

_set_cert_attrs()[source]

Add cert info from the socket connection to a HTTPSConnection object.

Adds the following attributes:

  • peer_cert: x509 certificate of the server
  • peer_cert_chain: x509 certificate chain of the server
  • peer_cert_dict: dictionary containing commonName and subjectAltName
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:

_abc_impl = <_abc_data object>

2.3.1.3. Exception Classes

exception cert_human.CertHumanError[source]

Bases: Exception

Exception wrapper.

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:
  • 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
  • kwargs – passed thru to requests.get()
Returns:

(requests.Response)

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:
  • host (str) – hostname to connect to.
  • port (str, optional) – port to connect to on host. Defaults to: 443.
Yields:

(OpenSSL.SSL.Connection)

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:

(tuple of (bool, Exception))

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 attributes urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls and urllib3.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 attributes urllib3.connectionpool.HTTPSConnectionPool.ConnectionCls and urllib3.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 bytes
Returns:(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 x509
Returns:(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 to x509.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 to x509.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 of OpenSSL.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 to x509.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 or int or bytes) – 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)

cert_human.indent(txt, n=4, s=' ')[source]

Text indenter.

Parameters:
  • txt (str) – The text to indent.
  • n (str, optional) – Number of s to indent txt. Defaults to: 4.
  • s (str, optional) – Char to use for indent. Defaults to: ” “.
Returns:

(str)

cert_human.write_file(path, text, overwrite=False, mkparent=True, protect=True)[source]

Write text to path.

Parameters:
  • path (str or pathlib.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:

(pathlib.Path)

cert_human.read_file(path)[source]

Read text from path.

Parameters:path (str or pathlib.Path) – Path to file to read.
Raises:(CertHumanError) – if path does not exist.
Returns:(str)
cert_human.find_certs(txt)[source]

Split text with multiple certificates into a list of certificates.

Parameters:txt (str) – the text to find certificates in.
Returns:(list of str)