tls._common package

Submodules

tls._common._constructs module

class tls._common._constructs.BytesAdapter(subcon)

Bases: construct.core.Adapter

tls._common._constructs.EnumClass(type_field, type_enum)

Maps the members of an enum.Enum to a single kind of construct.Construct.

Parameters:
  • type_field (construct.Construct) – The construct that represents the enum’s members. The type of this should correspond to the enum members’ types; for instance, an enum with a maximum value of 65535 would use a construct.macros.UBInt16.
  • type_enum (enum.Enum) – The enum to encode and decode.
tls._common._constructs.EnumSwitch(type_field, type_enum, value_field, value_choices, default=NoDefault('No default value specified'))

Maps the members of an enum.Enum to arbitrary construct.Constructs(). It returns a tuple intended to be spliced into another construct.Construct()‘s definition:

>>> from tls._common._constructs import EnumSwitch
>>> import construct, enum
>>> class IntEnum(enum.Enum):
...     VALUE = 1
...
>>> construct.Struct(
...     "name",
...     construct.UBInt8("an_integer"),
...     *EnumSwitch(type_field=construct.UBInt8("type"),
...                 type_enum=IntEnum,
...                 value_field="value",
...                 value_choices={
...                     IntEnum.VALUE: construct.UBInt8("first"),
...      })
... )
...
Struct('name')
Parameters:
  • type_field (construct.Construct) – The construct that represents the enum’s members. The type of this should correspond to the enum members’ types, so an enum with a maximum value of 65535, for example, would use a construct.macros.UBInt16.
  • type_enum (enum.Enum) – The enum to encode and decode.
  • value_field (str) – The attribute name under which this value will be accessible.
  • value_choices (dict) – A dictionary that maps members of type_enum to subconstructs. This follows construct.core.Switch()‘s API, so _default_ will match any members without an explicit mapping.
  • default (construct.Construct) – A default field to use when no explicit match is found for the key in the provided mapping. This follows construct.core.Switch()‘s API, so if not supplied, an exception will be raised when the key is not found. construct.Pass can be used for do-nothing.
Returns:

A tuple of the form (EnumClass(), construct.core.Switch())

tls._common._constructs.Opaque(subcon)

An opaque sequence of bytes. Such a sequence consists of a 16 bit integer followed that many bytes. It behaves like TLSPrefixedArray except that it returns a single construct instance and not a sequence of them.

Parameters:subcon (construct.Construct) – The construct to wrap.
tls._common._constructs.PrefixedBytes(name, length_field=FormatField('length'))

Length-prefixed binary data. This is like a construct.macros.PascalString() that raises a constrcut.AdaptationError when encoding something other than bytes.

Parameters:
  • name (str) – The attribute name under which this value will be accessible.
  • length_field (a construct.core.FormatField) – (optional) The prefixed length field. Defaults to construct.macros.UBInt8().
class tls._common._constructs.SizeAtLeast(subcon, min_size)

Bases: construct.adapters.Validator

A construct.adapter.Validator that validates a sequence size is greater than or equal to some minimum.

>>> from construct import UBInt8
>>> from tls._common._constructs import SizeAtLeast, PrefixedBytes
>>> PrefixedBytes(None, SizeAtLeast(UBInt8("length"),
...                     min_size=2)).parse(b'a')
Traceback (most recent call last):
    ...
construct.core.ValidationError: ('invalid object', b'a')
Parameters:
  • subcon (construct.core.Construct) – the construct to validate.
  • min_size (int) – the (inclusive) minimum allowable size for the validated sequence.
class tls._common._constructs.SizeAtMost(subcon, max_size)

Bases: construct.adapters.Validator

A construct.adapter.Validator that validates a sequence size is less than or equal to some maximum.

>>> from tls._common._constructs import SizeAtMost, PrefixedBytes
>>> PrefixedBytes(None, SizeAtMost(UBInt8("length"),
...                     max_size=1)).parse(b'aa')
Traceback (most recent call last):
    ...
construct.core.ValidationError: ('invalid object', b'aa')
Parameters:
  • subcon (construct.core.Construct) – the construct to validate.
  • max_size (int) – the (inclusive) maximum allowable size for the validated sequence.
class tls._common._constructs.SizeWithin(subcon, min_size, max_size)

Bases: construct.adapters.Validator

A construct.adapter.Validator that validates a sequence’s size is within some bounds. The bounds are inclusive.

>>> from tls._common._constructs import SizeWithin, PrefixedBytes
>>> PrefixedBytes(None, SizeWithin(UBInt8("length"),
...                     min_size=2, max_size=2)).parse(b'a')
Traceback (most recent call last):
    ...
construct.core.ValidationError: ('invalid object', b'a')
Parameters:
  • subcon (construct.core.Construct) – the construct to validate.
  • min_size (int) – the (inclusive) minimum allowable size for the validated sequence.
  • max_size (int) – the (inclusive) maximum allowable size for the validated sequence.
class tls._common._constructs.TLSExprValidator(subcon, validator)

Bases: construct.adapters.Validator

Like construct.ExprValidator, but raises a tls.exceptions.TLSValidationException on validation failure.

This is necessary because any ConstructError signifies the end of subconstruct repetition to Range, which in turn breaks use with TLSPrefixedArray.

tls._common._constructs.TLSOneOf(subcon, valids)

Validates that the object is one of the listed values, both during parsing and building. Like construct.OneOf(), but raises a tls.exceptions.TLSValidationException instead of a ConstructError subclass on mismatch.

This is necessary because any ConstructError signifies the end of subconstruct repetition to Range, which in turn breaks use with TLSPrefixedArray.

tls._common._constructs.TLSPrefixedArray(name, subcon, length_validator=None, length_field_size=<function UBInt16>)

The TLS vector type. It specializes on another construct.Construct and then encodes or decodes an arbitrarily long list or array of those constructs, prepending or reading a leading 16 bit length.

Parameters:
  • name (str) – The name by which the array will be accessible on the returned construct.Container.
  • subcon (construct.Construct) – The construct this array contains.
  • length_validator (a callable that accepts the length construct of the array as its only argument and returns a construct.adapters.Validator) – (optional) A callable that validates the array’s length construct.
  • length_field_size (a construct.core.FormatField) – (optional) The prefixed length field for representing the array length. Defaults to construct.macros.UBInt16().
tls._common._constructs.UBInt24(name)

A 24-bit integer.

Parameters:name (str) – The attribute name under which this value will be accessible.

tls._common.enums module

class tls._common.enums.AlertDescription

Bases: enum.Enum

ACCESS_DENIED = 49
BAD_CERTIFICATE = 42
BAD_CERTIFICATE_HASH_VALUE = 114
BAD_CERTIFICATE_STATUS_RESPONSE = 113
BAD_RECORD_MAC = 20
CERTIFICATE_EXPIRED = 45
CERTIFICATE_REVOKED = 44
CERTIFICATE_UNKNOWN = 46
CERTIFICATE_UNOBTAINABLE = 111
CLOSE_NOTIFY = 0
DECODE_ERROR = 50
DECOMPRESSION_FAILURE = 30
DECRYPTION_FAILED_RESERVED = 21
DECRYPT_ERROR = 51
EXPORT_RESTRICTION_RESERVED = 60
HANDSHAKE_FAILURE = 40
ILLEGAL_PARAMETER = 47
INSUFFICIENT_SECURITY = 71
INTERNAL_ERROR = 80
NO_CERTIFICATE_RESERVED = 41
NO_RENEGOTIATION = 100
PROTOCOL_VERSION = 70
RECORD_OVERFLOW = 22
UNEXPECTED_MESSAGE = 10
UNKNOWN_CA = 48
UNRECOGNIZED_NAME = 112
UNSUPPORTED_CERTIFICATE = 43
UNSUPPORTED_EXTENSION = 110
USER_CANCELED = 90
class tls._common.enums.AlertLevel

Bases: enum.Enum

FATAL = 2
WARNING = 1
class tls._common.enums.CertChainType

Bases: enum.Enum

INDIVIDUAL_CERTS = 0
PKIPATH = 1
class tls._common.enums.CertificateStatusType

Bases: enum.Enum

OCSP = 1
class tls._common.enums.ClientCertificateType

Bases: enum.Enum

DSS_EPHEMERAL_DH_RESERVED = 6
DSS_FIXED_DH = 4
DSS_SIGN = 2
FORTEZZA_DMS_RESERVED = 20
RSA_EPHEMERAL_DH_RESERVED = 5
RSA_FIXED_DH = 3
RSA_SIGN = 1
class tls._common.enums.CompressionMethod

Bases: enum.Enum

NULL = 0
class tls._common.enums.ContentType

Bases: enum.Enum

ALERT = 21
APPLICATION_DATA = 23
CHANGE_CIPHER_SPEC = 20
HANDSHAKE = 22
class tls._common.enums.ExtensionType

Bases: enum.Enum

TLS extensions as assigned in http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml.

APPLICATION_LAYER_PROTOCOL_NEGOTIATION = 16
CACHED_INFO = 25
CERT_TYPE = 9
CLIENT_AUTHZ = 7
CLIENT_CERTIFICATE_TYPE = 19
CLIENT_CERTIFICATE_URL = 2
EC_POINT_FORMATS = 11
ENCRYPT_THEN_MAC = 22
EXTENDED_MASTER_SECRET = 23
HEARTBEAT = 15
MAX_FRAGMENT_LENGTH = 1
PADDING = 21
RENEGOTIATION_INFO = 65281
SERVER_AUTHZ = 8
SERVER_CERTIFICATE_TYPE = 20
SERVER_NAME = 0
SIGNATURE_ALGORITHMS = 13
SIGNED_CERTIFICATE_TIMESTAMP = 18
SRP = 12
STATUS_REQUEST = 5
STATUS_REQUEST_V2 = 17
SUPPORTED_GROUPS = 10
TRUNCATED_HMAC = 4
TRUSTED_CA_KEYS = 3
USER_MAPPING = 6
USE_SRTP = 14
class tls._common.enums.HandshakeType

Bases: enum.Enum

CERTIFICATE = 11
CERTIFICATE_REQUEST = 13
CERTIFICATE_STATUS = 22
CERTIFICATE_URL = 21
CERTIFICATE_VERIFY = 15
CLIENT_HELLO = 1
CLIENT_KEY_EXCHANGE = 16
FINISHED = 20
HELLO_REQUEST = 0
SERVER_HELLO = 2
SERVER_HELLO_DONE = 14
SERVER_KEY_EXCHANGE = 12
class tls._common.enums.HashAlgorithm

Bases: enum.Enum

MD5 = 1
NONE = 0
SHA1 = 2
SHA224 = 3
SHA256 = 4
SHA384 = 5
SHA512 = 6
class tls._common.enums.MaxFragmentLength

Bases: enum.Enum

TWO_TO_THE_10TH = 2
TWO_TO_THE_11TH = 3
TWO_TO_THE_12TH = 4
TWO_TO_THE_9TH = 1
class tls._common.enums.NameType

Bases: enum.Enum

HOST_NAME = 0
class tls._common.enums.SignatureAlgorithm

Bases: enum.Enum

ANONYMOUS = 0
DSA = 2
ECDSA = 3
RSA = 1
class tls._common.enums.TrustedAuthorityIdentifierType

Bases: enum.Enum

CERT_SHA1_HASH = 3
KEY_SHA1_HASH = 1
PRE_AGREED = 0
X509_NAME = 2

tls._common.prf module

This file implements the TLS Pseudo-Random Function as specified by Section 5 of RFC 5246 (https://tools.ietf.org/html/rfc5246#section-5). The section states:

The TLS record layer uses a keyed Message Authentication Code (MAC) to
protect message integrity.  The cipher suites defined in this document use
a construction known as HMAC, described in [HMAC], which is based on a hash
function.  Other cipher suites MAY define their own MAC constructions, if
needed.

In addition, a construction is required to do expansion of secrets into
blocks of data for the purposes of key generation or validation.  This
pseudorandom function (PRF) takes as input a secret, a seed, and an
identifying label and produces an output of arbitrary length.

In this section, we define one PRF, based on HMAC.  This PRF with the
SHA-256 hash function is used for all cipher suites defined in this
document and in TLS documents published prior to this document when TLS 1.2
is negotiated.  New cipher suites MUST explicitly specify a PRF and, in
general, SHOULD use the TLS PRF with SHA-256 or a stronger standard hash
function.

First, we define a data expansion function, P_hash(secret, data), that uses
a single hash function to expand a secret and seed into an arbitrary
quantity of output:

    P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
    HMAC_hash(secret, A(2) + seed) + HMAC_hash(secret, A(3) + seed) + ...

where + indicates concatenation.

A() is defined as:

    A(0) = seed A(i) = HMAC_hash(secret, A(i-1))

P_hash can be iterated as many times as necessary to produce the required
quantity of data.  For example, if P_SHA256 is being used to create 80
bytes of data, it will have to be iterated three times (through A(3)),
creating 96 bytes of output data; the last 16 bytes of the final iteration
will then be discarded, leaving 80 bytes of output data.

TLS's PRF is created by applying P_hash to the secret as:

    PRF(secret, label, seed) = P_<hash>(secret, label + seed)

The label is an ASCII string.  It should be included in the exact form it
is given without a length byte or trailing null character.  For example,
the label "slithy toves" would be processed by hashing the following bytes:

    73 6C 69 74 68 79 20 74 6F 76 65 73
tls._common.prf.prf(secret, label, seed, hash_algorithm, output_length)

A construction to expand secrets into blocks of data for the purposes of key generation or validation.

This pseudo-random function (PRF) takes as input a secret, a seed, an identifying label and a hash algorithm and produces an output of length specified in output_length.

Parameters:
  • secret (bytes) – Secret key as bytes. The key should be randomly generated bytes and is recommended to be equal in length to the digest_size of the hash function chosen. You must keep the key secret.
  • label (bytes) – An ASCII string.
  • seed – The seed as bytes.
  • hash_algorithm (a cryptography.hazmat.primitives.hashes.HashAlgorithm provider.) – The hash algorithm to use with HMAC.
  • output_length (int) – The number of bytes to expand the seed into.

Module contents