Blame Lib/ssl.py

rpm-build 2bd099
# Wrapper module for _ssl, providing some additional facilities
rpm-build 2bd099
# implemented in Python.  Written by Bill Janssen.
rpm-build 2bd099
rpm-build 2bd099
"""This module provides some more Pythonic support for SSL.
rpm-build 2bd099
rpm-build 2bd099
Object types:
rpm-build 2bd099
rpm-build 2bd099
  SSLSocket -- subtype of socket.socket which does SSL over the socket
rpm-build 2bd099
rpm-build 2bd099
Exceptions:
rpm-build 2bd099
rpm-build 2bd099
  SSLError -- exception raised for I/O errors
rpm-build 2bd099
rpm-build 2bd099
Functions:
rpm-build 2bd099
rpm-build 2bd099
  cert_time_to_seconds -- convert time string used for certificate
rpm-build 2bd099
                          notBefore and notAfter functions to integer
rpm-build 2bd099
                          seconds past the Epoch (the time values
rpm-build 2bd099
                          returned from time.time())
rpm-build 2bd099
rpm-build 2bd099
  fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
rpm-build 2bd099
                          by the server running on HOST at port PORT.  No
rpm-build 2bd099
                          validation of the certificate is performed.
rpm-build 2bd099
rpm-build 2bd099
Integer constants:
rpm-build 2bd099
rpm-build 2bd099
SSL_ERROR_ZERO_RETURN
rpm-build 2bd099
SSL_ERROR_WANT_READ
rpm-build 2bd099
SSL_ERROR_WANT_WRITE
rpm-build 2bd099
SSL_ERROR_WANT_X509_LOOKUP
rpm-build 2bd099
SSL_ERROR_SYSCALL
rpm-build 2bd099
SSL_ERROR_SSL
rpm-build 2bd099
SSL_ERROR_WANT_CONNECT
rpm-build 2bd099
rpm-build 2bd099
SSL_ERROR_EOF
rpm-build 2bd099
SSL_ERROR_INVALID_ERROR_CODE
rpm-build 2bd099
rpm-build 2bd099
The following group define certificate requirements that one side is
rpm-build 2bd099
allowing/requiring from the other side:
rpm-build 2bd099
rpm-build 2bd099
CERT_NONE - no certificates from the other side are required (or will
rpm-build 2bd099
            be looked at if provided)
rpm-build 2bd099
CERT_OPTIONAL - certificates are not required, but if provided will be
rpm-build 2bd099
                validated, and if validation fails, the connection will
rpm-build 2bd099
                also fail
rpm-build 2bd099
CERT_REQUIRED - certificates are required, and will be validated, and
rpm-build 2bd099
                if validation fails, the connection will also fail
rpm-build 2bd099
rpm-build 2bd099
The following constants identify various SSL protocol variants:
rpm-build 2bd099
rpm-build 2bd099
PROTOCOL_SSLv2
rpm-build 2bd099
PROTOCOL_SSLv3
rpm-build 2bd099
PROTOCOL_SSLv23
rpm-build 2bd099
PROTOCOL_TLS
rpm-build 2bd099
PROTOCOL_TLS_CLIENT
rpm-build 2bd099
PROTOCOL_TLS_SERVER
rpm-build 2bd099
PROTOCOL_TLSv1
rpm-build 2bd099
PROTOCOL_TLSv1_1
rpm-build 2bd099
PROTOCOL_TLSv1_2
rpm-build 2bd099
rpm-build 2bd099
The following constants identify various SSL alert message descriptions as per
rpm-build 2bd099
http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
rpm-build 2bd099
rpm-build 2bd099
ALERT_DESCRIPTION_CLOSE_NOTIFY
rpm-build 2bd099
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
rpm-build 2bd099
ALERT_DESCRIPTION_BAD_RECORD_MAC
rpm-build 2bd099
ALERT_DESCRIPTION_RECORD_OVERFLOW
rpm-build 2bd099
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
rpm-build 2bd099
ALERT_DESCRIPTION_HANDSHAKE_FAILURE
rpm-build 2bd099
ALERT_DESCRIPTION_BAD_CERTIFICATE
rpm-build 2bd099
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
rpm-build 2bd099
ALERT_DESCRIPTION_CERTIFICATE_REVOKED
rpm-build 2bd099
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
rpm-build 2bd099
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
rpm-build 2bd099
ALERT_DESCRIPTION_ILLEGAL_PARAMETER
rpm-build 2bd099
ALERT_DESCRIPTION_UNKNOWN_CA
rpm-build 2bd099
ALERT_DESCRIPTION_ACCESS_DENIED
rpm-build 2bd099
ALERT_DESCRIPTION_DECODE_ERROR
rpm-build 2bd099
ALERT_DESCRIPTION_DECRYPT_ERROR
rpm-build 2bd099
ALERT_DESCRIPTION_PROTOCOL_VERSION
rpm-build 2bd099
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
rpm-build 2bd099
ALERT_DESCRIPTION_INTERNAL_ERROR
rpm-build 2bd099
ALERT_DESCRIPTION_USER_CANCELLED
rpm-build 2bd099
ALERT_DESCRIPTION_NO_RENEGOTIATION
rpm-build 2bd099
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
rpm-build 2bd099
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
rpm-build 2bd099
ALERT_DESCRIPTION_UNRECOGNIZED_NAME
rpm-build 2bd099
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
rpm-build 2bd099
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
rpm-build 2bd099
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
rpm-build 2bd099
"""
rpm-build 2bd099
rpm-build 2bd099
import ipaddress
rpm-build 2bd099
import textwrap
rpm-build 2bd099
import re
rpm-build 2bd099
import sys
rpm-build 2bd099
import os
rpm-build 2bd099
from collections import namedtuple
rpm-build 2bd099
from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
rpm-build 2bd099
rpm-build 2bd099
import _ssl             # if we can't import it, let the error propagate
rpm-build 2bd099
rpm-build 2bd099
from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
rpm-build 2bd099
from _ssl import _SSLContext, MemoryBIO, SSLSession
rpm-build 2bd099
from _ssl import (
rpm-build 2bd099
    SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
rpm-build 2bd099
    SSLSyscallError, SSLEOFError,
rpm-build 2bd099
    )
rpm-build 2bd099
from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
rpm-build 2bd099
from _ssl import RAND_status, RAND_add, RAND_bytes, RAND_pseudo_bytes
rpm-build 2bd099
try:
rpm-build 2bd099
    from _ssl import RAND_egd
rpm-build 2bd099
except ImportError:
rpm-build 2bd099
    # LibreSSL does not provide RAND_egd
rpm-build 2bd099
    pass
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
rpm-build 2bd099
from _ssl import _OPENSSL_API_VERSION
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
_IntEnum._convert(
rpm-build 2bd099
    '_SSLMethod', __name__,
rpm-build 2bd099
    lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
_IntFlag._convert(
rpm-build 2bd099
    'Options', __name__,
rpm-build 2bd099
    lambda name: name.startswith('OP_'),
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
_IntEnum._convert(
rpm-build 2bd099
    'AlertDescription', __name__,
rpm-build 2bd099
    lambda name: name.startswith('ALERT_DESCRIPTION_'),
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
_IntEnum._convert(
rpm-build 2bd099
    'SSLErrorNumber', __name__,
rpm-build 2bd099
    lambda name: name.startswith('SSL_ERROR_'),
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
_IntFlag._convert(
rpm-build 2bd099
    'VerifyFlags', __name__,
rpm-build 2bd099
    lambda name: name.startswith('VERIFY_'),
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
_IntEnum._convert(
rpm-build 2bd099
    'VerifyMode', __name__,
rpm-build 2bd099
    lambda name: name.startswith('CERT_'),
rpm-build 2bd099
    source=_ssl)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
rpm-build 2bd099
_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
rpm-build 2bd099
rpm-build 2bd099
_SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
if sys.platform == "win32":
rpm-build 2bd099
    from _ssl import enum_certificates, enum_crls
rpm-build 2bd099
rpm-build 2bd099
from socket import socket, AF_INET, SOCK_STREAM, create_connection
rpm-build 2bd099
from socket import SOL_SOCKET, SO_TYPE
rpm-build 2bd099
import base64        # for DER-to-PEM translation
rpm-build 2bd099
import errno
rpm-build 2bd099
import warnings
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
socket_error = OSError  # keep that public name in module namespace
rpm-build 2bd099
rpm-build 2bd099
if _ssl.HAS_TLS_UNIQUE:
rpm-build 2bd099
    CHANNEL_BINDING_TYPES = ['tls-unique']
rpm-build 2bd099
else:
rpm-build 2bd099
    CHANNEL_BINDING_TYPES = []
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
# Disable weak or insecure ciphers by default
rpm-build 2bd099
# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
rpm-build 2bd099
# Enable a better set of ciphers by default
rpm-build 2bd099
# This list has been explicitly chosen to:
rpm-build 2bd099
#   * TLS 1.3 ChaCha20 and AES-GCM cipher suites
rpm-build 2bd099
#   * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
rpm-build 2bd099
#   * Prefer ECDHE over DHE for better performance
rpm-build 2bd099
#   * Prefer AEAD over CBC for better performance and security
rpm-build 2bd099
#   * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
rpm-build 2bd099
#     (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
rpm-build 2bd099
#   * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
rpm-build 2bd099
#     performance and security
rpm-build 2bd099
#   * Then Use HIGH cipher suites as a fallback
rpm-build 2bd099
#   * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
rpm-build 2bd099
#     for security reasons
rpm-build 2bd099
_DEFAULT_CIPHERS = (
rpm-build 2bd099
    'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
rpm-build 2bd099
    'TLS13-AES-128-GCM-SHA256:'
rpm-build 2bd099
    'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
rpm-build 2bd099
    'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
rpm-build 2bd099
    '!aNULL:!eNULL:!MD5:!3DES'
rpm-build 2bd099
    )
rpm-build 2bd099
rpm-build 2bd099
# Restricted and more secure ciphers for the server side
rpm-build 2bd099
# This list has been explicitly chosen to:
rpm-build 2bd099
#   * TLS 1.3 ChaCha20 and AES-GCM cipher suites
rpm-build 2bd099
#   * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
rpm-build 2bd099
#   * Prefer ECDHE over DHE for better performance
rpm-build 2bd099
#   * Prefer AEAD over CBC for better performance and security
rpm-build 2bd099
#   * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
rpm-build 2bd099
#   * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
rpm-build 2bd099
#     performance and security
rpm-build 2bd099
#   * Then Use HIGH cipher suites as a fallback
rpm-build 2bd099
#   * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
rpm-build 2bd099
#     3DES for security reasons
rpm-build 2bd099
_RESTRICTED_SERVER_CIPHERS = (
rpm-build 2bd099
    'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
rpm-build 2bd099
    'TLS13-AES-128-GCM-SHA256:'
rpm-build 2bd099
    'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
rpm-build 2bd099
    'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
rpm-build 2bd099
    '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
rpm-build 2bd099
)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class CertificateError(ValueError):
rpm-build 2bd099
    pass
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def _dnsname_match(dn, hostname, max_wildcards=1):
rpm-build 2bd099
    """Matching according to RFC 6125, section 6.4.3
rpm-build 2bd099
rpm-build 2bd099
    http://tools.ietf.org/html/rfc6125#section-6.4.3
rpm-build 2bd099
    """
rpm-build 2bd099
    pats = []
rpm-build 2bd099
    if not dn:
rpm-build 2bd099
        return False
rpm-build 2bd099
rpm-build 2bd099
    leftmost, *remainder = dn.split(r'.')
rpm-build 2bd099
rpm-build 2bd099
    wildcards = leftmost.count('*')
rpm-build 2bd099
    if wildcards > max_wildcards:
rpm-build 2bd099
        # Issue #17980: avoid denials of service by refusing more
rpm-build 2bd099
        # than one wildcard per fragment.  A survey of established
rpm-build 2bd099
        # policy among SSL implementations showed it to be a
rpm-build 2bd099
        # reasonable choice.
rpm-build 2bd099
        raise CertificateError(
rpm-build 2bd099
            "too many wildcards in certificate DNS name: " + repr(dn))
rpm-build 2bd099
rpm-build 2bd099
    # speed up common case w/o wildcards
rpm-build 2bd099
    if not wildcards:
rpm-build 2bd099
        return dn.lower() == hostname.lower()
rpm-build 2bd099
rpm-build 2bd099
    # RFC 6125, section 6.4.3, subitem 1.
rpm-build 2bd099
    # The client SHOULD NOT attempt to match a presented identifier in which
rpm-build 2bd099
    # the wildcard character comprises a label other than the left-most label.
rpm-build 2bd099
    if leftmost == '*':
rpm-build 2bd099
        # When '*' is a fragment by itself, it matches a non-empty dotless
rpm-build 2bd099
        # fragment.
rpm-build 2bd099
        pats.append('[^.]+')
rpm-build 2bd099
    elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
rpm-build 2bd099
        # RFC 6125, section 6.4.3, subitem 3.
rpm-build 2bd099
        # The client SHOULD NOT attempt to match a presented identifier
rpm-build 2bd099
        # where the wildcard character is embedded within an A-label or
rpm-build 2bd099
        # U-label of an internationalized domain name.
rpm-build 2bd099
        pats.append(re.escape(leftmost))
rpm-build 2bd099
    else:
rpm-build 2bd099
        # Otherwise, '*' matches any dotless string, e.g. www*
rpm-build 2bd099
        pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
rpm-build 2bd099
rpm-build 2bd099
    # add the remaining fragments, ignore any wildcards
rpm-build 2bd099
    for frag in remainder:
rpm-build 2bd099
        pats.append(re.escape(frag))
rpm-build 2bd099
rpm-build 2bd099
    pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
rpm-build 2bd099
    return pat.match(hostname)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def _ipaddress_match(ipname, host_ip):
rpm-build 2bd099
    """Exact matching of IP addresses.
rpm-build 2bd099
rpm-build 2bd099
    RFC 6125 explicitly doesn't define an algorithm for this
rpm-build 2bd099
    (section 1.7.2 - "Out of Scope").
rpm-build 2bd099
    """
rpm-build 2bd099
    # OpenSSL may add a trailing newline to a subjectAltName's IP address
rpm-build 2bd099
    ip = ipaddress.ip_address(ipname.rstrip())
rpm-build 2bd099
    return ip == host_ip
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def match_hostname(cert, hostname):
rpm-build 2bd099
    """Verify that *cert* (in decoded format as returned by
rpm-build 2bd099
    SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125
rpm-build 2bd099
    rules are followed, but IP addresses are not accepted for *hostname*.
rpm-build 2bd099
rpm-build 2bd099
    CertificateError is raised on failure. On success, the function
rpm-build 2bd099
    returns nothing.
rpm-build 2bd099
    """
rpm-build 2bd099
    if not cert:
rpm-build 2bd099
        raise ValueError("empty or no certificate, match_hostname needs a "
rpm-build 2bd099
                         "SSL socket or SSL context with either "
rpm-build 2bd099
                         "CERT_OPTIONAL or CERT_REQUIRED")
rpm-build 2bd099
    try:
rpm-build 2bd099
        host_ip = ipaddress.ip_address(hostname)
rpm-build 2bd099
    except ValueError:
rpm-build 2bd099
        # Not an IP address (common case)
rpm-build 2bd099
        host_ip = None
rpm-build 2bd099
    dnsnames = []
rpm-build 2bd099
    san = cert.get('subjectAltName', ())
rpm-build 2bd099
    for key, value in san:
rpm-build 2bd099
        if key == 'DNS':
rpm-build 2bd099
            if host_ip is None and _dnsname_match(value, hostname):
rpm-build 2bd099
                return
rpm-build 2bd099
            dnsnames.append(value)
rpm-build 2bd099
        elif key == 'IP Address':
rpm-build 2bd099
            if host_ip is not None and _ipaddress_match(value, host_ip):
rpm-build 2bd099
                return
rpm-build 2bd099
            dnsnames.append(value)
rpm-build 2bd099
    if not dnsnames:
rpm-build 2bd099
        # The subject is only checked when there is no dNSName entry
rpm-build 2bd099
        # in subjectAltName
rpm-build 2bd099
        for sub in cert.get('subject', ()):
rpm-build 2bd099
            for key, value in sub:
rpm-build 2bd099
                # XXX according to RFC 2818, the most specific Common Name
rpm-build 2bd099
                # must be used.
rpm-build 2bd099
                if key == 'commonName':
rpm-build 2bd099
                    if _dnsname_match(value, hostname):
rpm-build 2bd099
                        return
rpm-build 2bd099
                    dnsnames.append(value)
rpm-build 2bd099
    if len(dnsnames) > 1:
rpm-build 2bd099
        raise CertificateError("hostname %r "
rpm-build 2bd099
            "doesn't match either of %s"
rpm-build 2bd099
            % (hostname, ', '.join(map(repr, dnsnames))))
rpm-build 2bd099
    elif len(dnsnames) == 1:
rpm-build 2bd099
        raise CertificateError("hostname %r "
rpm-build 2bd099
            "doesn't match %r"
rpm-build 2bd099
            % (hostname, dnsnames[0]))
rpm-build 2bd099
    else:
rpm-build 2bd099
        raise CertificateError("no appropriate commonName or "
rpm-build 2bd099
            "subjectAltName fields were found")
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
rpm-build 2bd099
    "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
rpm-build 2bd099
    "openssl_capath")
rpm-build 2bd099
rpm-build 2bd099
def get_default_verify_paths():
rpm-build 2bd099
    """Return paths to default cafile and capath.
rpm-build 2bd099
    """
rpm-build 2bd099
    parts = _ssl.get_default_verify_paths()
rpm-build 2bd099
rpm-build 2bd099
    # environment vars shadow paths
rpm-build 2bd099
    cafile = os.environ.get(parts[0], parts[1])
rpm-build 2bd099
    capath = os.environ.get(parts[2], parts[3])
rpm-build 2bd099
rpm-build 2bd099
    return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
rpm-build 2bd099
                              capath if os.path.isdir(capath) else None,
rpm-build 2bd099
                              *parts)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
rpm-build 2bd099
    """ASN.1 object identifier lookup
rpm-build 2bd099
    """
rpm-build 2bd099
    __slots__ = ()
rpm-build 2bd099
rpm-build 2bd099
    def __new__(cls, oid):
rpm-build 2bd099
        return super().__new__(cls, *_txt2obj(oid, name=False))
rpm-build 2bd099
rpm-build 2bd099
    @classmethod
rpm-build 2bd099
    def fromnid(cls, nid):
rpm-build 2bd099
        """Create _ASN1Object from OpenSSL numeric ID
rpm-build 2bd099
        """
rpm-build 2bd099
        return super().__new__(cls, *_nid2obj(nid))
rpm-build 2bd099
rpm-build 2bd099
    @classmethod
rpm-build 2bd099
    def fromname(cls, name):
rpm-build 2bd099
        """Create _ASN1Object from short name, long name or OID
rpm-build 2bd099
        """
rpm-build 2bd099
        return super().__new__(cls, *_txt2obj(name, name=True))
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class Purpose(_ASN1Object, _Enum):
rpm-build 2bd099
    """SSLContext purpose flags with X509v3 Extended Key Usage objects
rpm-build 2bd099
    """
rpm-build 2bd099
    SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
rpm-build 2bd099
    CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class SSLContext(_SSLContext):
rpm-build 2bd099
    """An SSLContext holds various SSL-related configuration options and
rpm-build 2bd099
    data, such as certificates and possibly a private key."""
rpm-build 2bd099
rpm-build 2bd099
    __slots__ = ('protocol', '__weakref__')
rpm-build 2bd099
    _windows_cert_stores = ("CA", "ROOT")
rpm-build 2bd099
rpm-build 2bd099
    def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
rpm-build 2bd099
        self = _SSLContext.__new__(cls, protocol)
rpm-build 2bd099
        if protocol != _SSLv2_IF_EXISTS:
rpm-build 2bd099
            self.set_ciphers(_DEFAULT_CIPHERS)
rpm-build 2bd099
        return self
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, protocol=PROTOCOL_TLS):
rpm-build 2bd099
        self.protocol = protocol
rpm-build 2bd099
rpm-build 2bd099
    def wrap_socket(self, sock, server_side=False,
rpm-build 2bd099
                    do_handshake_on_connect=True,
rpm-build 2bd099
                    suppress_ragged_eofs=True,
rpm-build 2bd099
                    server_hostname=None, session=None):
rpm-build 2bd099
        return SSLSocket(sock=sock, server_side=server_side,
rpm-build 2bd099
                         do_handshake_on_connect=do_handshake_on_connect,
rpm-build 2bd099
                         suppress_ragged_eofs=suppress_ragged_eofs,
rpm-build 2bd099
                         server_hostname=server_hostname,
rpm-build 2bd099
                         _context=self, _session=session)
rpm-build 2bd099
rpm-build 2bd099
    def wrap_bio(self, incoming, outgoing, server_side=False,
rpm-build 2bd099
                 server_hostname=None, session=None):
rpm-build 2bd099
        sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
rpm-build 2bd099
                                server_hostname=server_hostname)
rpm-build 2bd099
        return SSLObject(sslobj, session=session)
rpm-build 2bd099
rpm-build 2bd099
    def set_npn_protocols(self, npn_protocols):
rpm-build 2bd099
        protos = bytearray()
rpm-build 2bd099
        for protocol in npn_protocols:
rpm-build 2bd099
            b = bytes(protocol, 'ascii')
rpm-build 2bd099
            if len(b) == 0 or len(b) > 255:
rpm-build 2bd099
                raise SSLError('NPN protocols must be 1 to 255 in length')
rpm-build 2bd099
            protos.append(len(b))
rpm-build 2bd099
            protos.extend(b)
rpm-build 2bd099
rpm-build 2bd099
        self._set_npn_protocols(protos)
rpm-build 2bd099
rpm-build 2bd099
    def set_alpn_protocols(self, alpn_protocols):
rpm-build 2bd099
        protos = bytearray()
rpm-build 2bd099
        for protocol in alpn_protocols:
rpm-build 2bd099
            b = bytes(protocol, 'ascii')
rpm-build 2bd099
            if len(b) == 0 or len(b) > 255:
rpm-build 2bd099
                raise SSLError('ALPN protocols must be 1 to 255 in length')
rpm-build 2bd099
            protos.append(len(b))
rpm-build 2bd099
            protos.extend(b)
rpm-build 2bd099
rpm-build 2bd099
        self._set_alpn_protocols(protos)
rpm-build 2bd099
rpm-build 2bd099
    def _load_windows_store_certs(self, storename, purpose):
rpm-build 2bd099
        certs = bytearray()
rpm-build 2bd099
        try:
rpm-build 2bd099
            for cert, encoding, trust in enum_certificates(storename):
rpm-build 2bd099
                # CA certs are never PKCS#7 encoded
rpm-build 2bd099
                if encoding == "x509_asn":
rpm-build 2bd099
                    if trust is True or purpose.oid in trust:
rpm-build 2bd099
                        certs.extend(cert)
rpm-build 2bd099
        except PermissionError:
rpm-build 2bd099
            warnings.warn("unable to enumerate Windows certificate store")
rpm-build 2bd099
        if certs:
rpm-build 2bd099
            self.load_verify_locations(cadata=certs)
rpm-build 2bd099
        return certs
rpm-build 2bd099
rpm-build 2bd099
    def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
rpm-build 2bd099
        if not isinstance(purpose, _ASN1Object):
rpm-build 2bd099
            raise TypeError(purpose)
rpm-build 2bd099
        if sys.platform == "win32":
rpm-build 2bd099
            for storename in self._windows_cert_stores:
rpm-build 2bd099
                self._load_windows_store_certs(storename, purpose)
rpm-build 2bd099
        self.set_default_verify_paths()
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def options(self):
rpm-build 2bd099
        return Options(super().options)
rpm-build 2bd099
rpm-build 2bd099
    @options.setter
rpm-build 2bd099
    def options(self, value):
rpm-build 2bd099
        super(SSLContext, SSLContext).options.__set__(self, value)
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def verify_flags(self):
rpm-build 2bd099
        return VerifyFlags(super().verify_flags)
rpm-build 2bd099
rpm-build 2bd099
    @verify_flags.setter
rpm-build 2bd099
    def verify_flags(self, value):
rpm-build 2bd099
        super(SSLContext, SSLContext).verify_flags.__set__(self, value)
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def verify_mode(self):
rpm-build 2bd099
        value = super().verify_mode
rpm-build 2bd099
        try:
rpm-build 2bd099
            return VerifyMode(value)
rpm-build 2bd099
        except ValueError:
rpm-build 2bd099
            return value
rpm-build 2bd099
rpm-build 2bd099
    @verify_mode.setter
rpm-build 2bd099
    def verify_mode(self, value):
rpm-build 2bd099
        super(SSLContext, SSLContext).verify_mode.__set__(self, value)
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
rpm-build 2bd099
                           capath=None, cadata=None):
rpm-build 2bd099
    """Create a SSLContext object with default settings.
rpm-build 2bd099
rpm-build 2bd099
    NOTE: The protocol and settings may change anytime without prior
rpm-build 2bd099
          deprecation. The values represent a fair balance between maximum
rpm-build 2bd099
          compatibility and security.
rpm-build 2bd099
    """
rpm-build 2bd099
    if not isinstance(purpose, _ASN1Object):
rpm-build 2bd099
        raise TypeError(purpose)
rpm-build 2bd099
rpm-build 2bd099
    # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
rpm-build 2bd099
    # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
rpm-build 2bd099
    # by default.
rpm-build 2bd099
    context = SSLContext(PROTOCOL_TLS)
rpm-build 2bd099
rpm-build 2bd099
    if purpose == Purpose.SERVER_AUTH:
rpm-build 2bd099
        # verify certs and host name in client mode
rpm-build 2bd099
        context.verify_mode = CERT_REQUIRED
rpm-build 2bd099
        context.check_hostname = True
rpm-build 2bd099
    elif purpose == Purpose.CLIENT_AUTH:
rpm-build 2bd099
        context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
rpm-build 2bd099
rpm-build 2bd099
    if cafile or capath or cadata:
rpm-build 2bd099
        context.load_verify_locations(cafile, capath, cadata)
rpm-build 2bd099
    elif context.verify_mode != CERT_NONE:
rpm-build 2bd099
        # no explicit cafile, capath or cadata but the verify mode is
rpm-build 2bd099
        # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
rpm-build 2bd099
        # root CA certificates for the given purpose. This may fail silently.
rpm-build 2bd099
        context.load_default_certs(purpose)
rpm-build 2bd099
    return context
rpm-build 2bd099
rpm-build 2bd099
def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
rpm-build 2bd099
                           check_hostname=False, purpose=Purpose.SERVER_AUTH,
rpm-build 2bd099
                           certfile=None, keyfile=None,
rpm-build 2bd099
                           cafile=None, capath=None, cadata=None):
rpm-build 2bd099
    """Create a SSLContext object for Python stdlib modules
rpm-build 2bd099
rpm-build 2bd099
    All Python stdlib modules shall use this function to create SSLContext
rpm-build 2bd099
    objects in order to keep common settings in one place. The configuration
rpm-build 2bd099
    is less restrict than create_default_context()'s to increase backward
rpm-build 2bd099
    compatibility.
rpm-build 2bd099
    """
rpm-build 2bd099
    if not isinstance(purpose, _ASN1Object):
rpm-build 2bd099
        raise TypeError(purpose)
rpm-build 2bd099
rpm-build 2bd099
    # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
rpm-build 2bd099
    # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
rpm-build 2bd099
    # by default.
rpm-build 2bd099
    context = SSLContext(protocol)
rpm-build 2bd099
rpm-build 2bd099
    if cert_reqs is not None:
rpm-build 2bd099
        context.verify_mode = cert_reqs
rpm-build 2bd099
    context.check_hostname = check_hostname
rpm-build 2bd099
rpm-build 2bd099
    if keyfile and not certfile:
rpm-build 2bd099
        raise ValueError("certfile must be specified")
rpm-build 2bd099
    if certfile or keyfile:
rpm-build 2bd099
        context.load_cert_chain(certfile, keyfile)
rpm-build 2bd099
rpm-build 2bd099
    # load CA root certs
rpm-build 2bd099
    if cafile or capath or cadata:
rpm-build 2bd099
        context.load_verify_locations(cafile, capath, cadata)
rpm-build 2bd099
    elif context.verify_mode != CERT_NONE:
rpm-build 2bd099
        # no explicit cafile, capath or cadata but the verify mode is
rpm-build 2bd099
        # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
rpm-build 2bd099
        # root CA certificates for the given purpose. This may fail silently.
rpm-build 2bd099
        context.load_default_certs(purpose)
rpm-build 2bd099
rpm-build 2bd099
    return context
rpm-build 2bd099
rpm-build 2bd099
# Used by http.client if no context is explicitly passed.
rpm-build 2bd099
_create_default_https_context = create_default_context
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
# Backwards compatibility alias, even though it's not a public name.
rpm-build 2bd099
_create_stdlib_context = _create_unverified_context
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class SSLObject:
rpm-build 2bd099
    """This class implements an interface on top of a low-level SSL object as
rpm-build 2bd099
    implemented by OpenSSL. This object captures the state of an SSL connection
rpm-build 2bd099
    but does not provide any network IO itself. IO needs to be performed
rpm-build 2bd099
    through separate "BIO" objects which are OpenSSL's IO abstraction layer.
rpm-build 2bd099
rpm-build 2bd099
    This class does not have a public constructor. Instances are returned by
rpm-build 2bd099
    ``SSLContext.wrap_bio``. This class is typically used by framework authors
rpm-build 2bd099
    that want to implement asynchronous IO for SSL through memory buffers.
rpm-build 2bd099
rpm-build 2bd099
    When compared to ``SSLSocket``, this object lacks the following features:
rpm-build 2bd099
rpm-build 2bd099
     * Any form of network IO incluging methods such as ``recv`` and ``send``.
rpm-build 2bd099
     * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
rpm-build 2bd099
    """
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, sslobj, owner=None, session=None):
rpm-build 2bd099
        self._sslobj = sslobj
rpm-build 2bd099
        # Note: _sslobj takes a weak reference to owner
rpm-build 2bd099
        self._sslobj.owner = owner or self
rpm-build 2bd099
        if session is not None:
rpm-build 2bd099
            self._sslobj.session = session
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def context(self):
rpm-build 2bd099
        """The SSLContext that is currently in use."""
rpm-build 2bd099
        return self._sslobj.context
rpm-build 2bd099
rpm-build 2bd099
    @context.setter
rpm-build 2bd099
    def context(self, ctx):
rpm-build 2bd099
        self._sslobj.context = ctx
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def session(self):
rpm-build 2bd099
        """The SSLSession for client socket."""
rpm-build 2bd099
        return self._sslobj.session
rpm-build 2bd099
rpm-build 2bd099
    @session.setter
rpm-build 2bd099
    def session(self, session):
rpm-build 2bd099
        self._sslobj.session = session
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def session_reused(self):
rpm-build 2bd099
        """Was the client session reused during handshake"""
rpm-build 2bd099
        return self._sslobj.session_reused
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def server_side(self):
rpm-build 2bd099
        """Whether this is a server-side socket."""
rpm-build 2bd099
        return self._sslobj.server_side
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def server_hostname(self):
rpm-build 2bd099
        """The currently set server hostname (for SNI), or ``None`` if no
rpm-build 2bd099
        server hostame is set."""
rpm-build 2bd099
        return self._sslobj.server_hostname
rpm-build 2bd099
rpm-build 2bd099
    def read(self, len=1024, buffer=None):
rpm-build 2bd099
        """Read up to 'len' bytes from the SSL object and return them.
rpm-build 2bd099
rpm-build 2bd099
        If 'buffer' is provided, read into this buffer and return the number of
rpm-build 2bd099
        bytes read.
rpm-build 2bd099
        """
rpm-build 2bd099
        if buffer is not None:
rpm-build 2bd099
            v = self._sslobj.read(len, buffer)
rpm-build 2bd099
        else:
rpm-build 2bd099
            v = self._sslobj.read(len)
rpm-build 2bd099
        return v
rpm-build 2bd099
rpm-build 2bd099
    def write(self, data):
rpm-build 2bd099
        """Write 'data' to the SSL object and return the number of bytes
rpm-build 2bd099
        written.
rpm-build 2bd099
rpm-build 2bd099
        The 'data' argument must support the buffer interface.
rpm-build 2bd099
        """
rpm-build 2bd099
        return self._sslobj.write(data)
rpm-build 2bd099
rpm-build 2bd099
    def getpeercert(self, binary_form=False):
rpm-build 2bd099
        """Returns a formatted version of the data in the certificate provided
rpm-build 2bd099
        by the other end of the SSL channel.
rpm-build 2bd099
rpm-build 2bd099
        Return None if no certificate was provided, {} if a certificate was
rpm-build 2bd099
        provided, but not validated.
rpm-build 2bd099
        """
rpm-build 2bd099
        return self._sslobj.peer_certificate(binary_form)
rpm-build 2bd099
rpm-build 2bd099
    def selected_npn_protocol(self):
rpm-build 2bd099
        """Return the currently selected NPN protocol as a string, or ``None``
rpm-build 2bd099
        if a next protocol was not negotiated or if NPN is not supported by one
rpm-build 2bd099
        of the peers."""
rpm-build 2bd099
        if _ssl.HAS_NPN:
rpm-build 2bd099
            return self._sslobj.selected_npn_protocol()
rpm-build 2bd099
rpm-build 2bd099
    def selected_alpn_protocol(self):
rpm-build 2bd099
        """Return the currently selected ALPN protocol as a string, or ``None``
rpm-build 2bd099
        if a next protocol was not negotiated or if ALPN is not supported by one
rpm-build 2bd099
        of the peers."""
rpm-build 2bd099
        if _ssl.HAS_ALPN:
rpm-build 2bd099
            return self._sslobj.selected_alpn_protocol()
rpm-build 2bd099
rpm-build 2bd099
    def cipher(self):
rpm-build 2bd099
        """Return the currently selected cipher as a 3-tuple ``(name,
rpm-build 2bd099
        ssl_version, secret_bits)``."""
rpm-build 2bd099
        return self._sslobj.cipher()
rpm-build 2bd099
rpm-build 2bd099
    def shared_ciphers(self):
rpm-build 2bd099
        """Return a list of ciphers shared by the client during the handshake or
rpm-build 2bd099
        None if this is not a valid server connection.
rpm-build 2bd099
        """
rpm-build 2bd099
        return self._sslobj.shared_ciphers()
rpm-build 2bd099
rpm-build 2bd099
    def compression(self):
rpm-build 2bd099
        """Return the current compression algorithm in use, or ``None`` if
rpm-build 2bd099
        compression was not negotiated or not supported by one of the peers."""
rpm-build 2bd099
        return self._sslobj.compression()
rpm-build 2bd099
rpm-build 2bd099
    def pending(self):
rpm-build 2bd099
        """Return the number of bytes that can be read immediately."""
rpm-build 2bd099
        return self._sslobj.pending()
rpm-build 2bd099
rpm-build 2bd099
    def do_handshake(self):
rpm-build 2bd099
        """Start the SSL/TLS handshake."""
rpm-build 2bd099
        self._sslobj.do_handshake()
rpm-build 2bd099
        if self.context.check_hostname:
rpm-build 2bd099
            if not self.server_hostname:
rpm-build 2bd099
                raise ValueError("check_hostname needs server_hostname "
rpm-build 2bd099
                                 "argument")
rpm-build 2bd099
            match_hostname(self.getpeercert(), self.server_hostname)
rpm-build 2bd099
rpm-build 2bd099
    def unwrap(self):
rpm-build 2bd099
        """Start the SSL shutdown handshake."""
rpm-build 2bd099
        return self._sslobj.shutdown()
rpm-build 2bd099
rpm-build 2bd099
    def get_channel_binding(self, cb_type="tls-unique"):
rpm-build 2bd099
        """Get channel binding data for current connection.  Raise ValueError
rpm-build 2bd099
        if the requested `cb_type` is not supported.  Return bytes of the data
rpm-build 2bd099
        or None if the data is not available (e.g. before the handshake)."""
rpm-build 2bd099
        if cb_type not in CHANNEL_BINDING_TYPES:
rpm-build 2bd099
            raise ValueError("Unsupported channel binding type")
rpm-build 2bd099
        if cb_type != "tls-unique":
rpm-build 2bd099
            raise NotImplementedError(
rpm-build 2bd099
                            "{0} channel binding type not implemented"
rpm-build 2bd099
                            .format(cb_type))
rpm-build 2bd099
        return self._sslobj.tls_unique_cb()
rpm-build 2bd099
rpm-build 2bd099
    def version(self):
rpm-build 2bd099
        """Return a string identifying the protocol version used by the
rpm-build 2bd099
        current SSL channel. """
rpm-build 2bd099
        return self._sslobj.version()
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
class SSLSocket(socket):
rpm-build 2bd099
    """This class implements a subtype of socket.socket that wraps
rpm-build 2bd099
    the underlying OS socket in an SSL context when necessary, and
rpm-build 2bd099
    provides read and write methods over that channel."""
rpm-build 2bd099
rpm-build 2bd099
    def __init__(self, sock=None, keyfile=None, certfile=None,
rpm-build 2bd099
                 server_side=False, cert_reqs=CERT_NONE,
rpm-build 2bd099
                 ssl_version=PROTOCOL_TLS, ca_certs=None,
rpm-build 2bd099
                 do_handshake_on_connect=True,
rpm-build 2bd099
                 family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
rpm-build 2bd099
                 suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
rpm-build 2bd099
                 server_hostname=None,
rpm-build 2bd099
                 _context=None, _session=None):
rpm-build 2bd099
rpm-build 2bd099
        if _context:
rpm-build 2bd099
            self._context = _context
rpm-build 2bd099
        else:
rpm-build 2bd099
            if server_side and not certfile:
rpm-build 2bd099
                raise ValueError("certfile must be specified for server-side "
rpm-build 2bd099
                                 "operations")
rpm-build 2bd099
            if keyfile and not certfile:
rpm-build 2bd099
                raise ValueError("certfile must be specified")
rpm-build 2bd099
            if certfile and not keyfile:
rpm-build 2bd099
                keyfile = certfile
rpm-build 2bd099
            self._context = SSLContext(ssl_version)
rpm-build 2bd099
            self._context.verify_mode = cert_reqs
rpm-build 2bd099
            if ca_certs:
rpm-build 2bd099
                self._context.load_verify_locations(ca_certs)
rpm-build 2bd099
            if certfile:
rpm-build 2bd099
                self._context.load_cert_chain(certfile, keyfile)
rpm-build 2bd099
            if npn_protocols:
rpm-build 2bd099
                self._context.set_npn_protocols(npn_protocols)
rpm-build 2bd099
            if ciphers:
rpm-build 2bd099
                self._context.set_ciphers(ciphers)
rpm-build 2bd099
            self.keyfile = keyfile
rpm-build 2bd099
            self.certfile = certfile
rpm-build 2bd099
            self.cert_reqs = cert_reqs
rpm-build 2bd099
            self.ssl_version = ssl_version
rpm-build 2bd099
            self.ca_certs = ca_certs
rpm-build 2bd099
            self.ciphers = ciphers
rpm-build 2bd099
        # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
rpm-build 2bd099
        # mixed in.
rpm-build 2bd099
        if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
rpm-build 2bd099
            raise NotImplementedError("only stream sockets are supported")
rpm-build 2bd099
        if server_side:
rpm-build 2bd099
            if server_hostname:
rpm-build 2bd099
                raise ValueError("server_hostname can only be specified "
rpm-build 2bd099
                                 "in client mode")
rpm-build 2bd099
            if _session is not None:
rpm-build 2bd099
                raise ValueError("session can only be specified in "
rpm-build 2bd099
                                 "client mode")
rpm-build 2bd099
        if self._context.check_hostname and not server_hostname:
rpm-build 2bd099
            raise ValueError("check_hostname requires server_hostname")
rpm-build 2bd099
        self._session = _session
rpm-build 2bd099
        self.server_side = server_side
rpm-build 2bd099
        self.server_hostname = server_hostname
rpm-build 2bd099
        self.do_handshake_on_connect = do_handshake_on_connect
rpm-build 2bd099
        self.suppress_ragged_eofs = suppress_ragged_eofs
rpm-build 2bd099
        if sock is not None:
rpm-build 2bd099
            socket.__init__(self,
rpm-build 2bd099
                            family=sock.family,
rpm-build 2bd099
                            type=sock.type,
rpm-build 2bd099
                            proto=sock.proto,
rpm-build 2bd099
                            fileno=sock.fileno())
rpm-build 2bd099
            self.settimeout(sock.gettimeout())
rpm-build 2bd099
            sock.detach()
rpm-build 2bd099
        elif fileno is not None:
rpm-build 2bd099
            socket.__init__(self, fileno=fileno)
rpm-build 2bd099
        else:
rpm-build 2bd099
            socket.__init__(self, family=family, type=type, proto=proto)
rpm-build 2bd099
rpm-build 2bd099
        # See if we are connected
rpm-build 2bd099
        try:
rpm-build 2bd099
            self.getpeername()
rpm-build 2bd099
        except OSError as e:
rpm-build 2bd099
            if e.errno != errno.ENOTCONN:
rpm-build 2bd099
                raise
rpm-build 2bd099
            connected = False
rpm-build 2bd099
        else:
rpm-build 2bd099
            connected = True
rpm-build 2bd099
rpm-build 2bd099
        self._closed = False
rpm-build 2bd099
        self._sslobj = None
rpm-build 2bd099
        self._connected = connected
rpm-build 2bd099
        if connected:
rpm-build 2bd099
            # create the SSL object
rpm-build 2bd099
            try:
rpm-build 2bd099
                sslobj = self._context._wrap_socket(self, server_side,
rpm-build 2bd099
                                                    server_hostname)
rpm-build 2bd099
                self._sslobj = SSLObject(sslobj, owner=self,
rpm-build 2bd099
                                         session=self._session)
rpm-build 2bd099
                if do_handshake_on_connect:
rpm-build 2bd099
                    timeout = self.gettimeout()
rpm-build 2bd099
                    if timeout == 0.0:
rpm-build 2bd099
                        # non-blocking
rpm-build 2bd099
                        raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
rpm-build 2bd099
                    self.do_handshake()
rpm-build 2bd099
rpm-build 2bd099
            except (OSError, ValueError):
rpm-build 2bd099
                self.close()
rpm-build 2bd099
                raise
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def context(self):
rpm-build 2bd099
        return self._context
rpm-build 2bd099
rpm-build 2bd099
    @context.setter
rpm-build 2bd099
    def context(self, ctx):
rpm-build 2bd099
        self._context = ctx
rpm-build 2bd099
        self._sslobj.context = ctx
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def session(self):
rpm-build 2bd099
        """The SSLSession for client socket."""
rpm-build 2bd099
        if self._sslobj is not None:
rpm-build 2bd099
            return self._sslobj.session
rpm-build 2bd099
rpm-build 2bd099
    @session.setter
rpm-build 2bd099
    def session(self, session):
rpm-build 2bd099
        self._session = session
rpm-build 2bd099
        if self._sslobj is not None:
rpm-build 2bd099
            self._sslobj.session = session
rpm-build 2bd099
rpm-build 2bd099
    @property
rpm-build 2bd099
    def session_reused(self):
rpm-build 2bd099
        """Was the client session reused during handshake"""
rpm-build 2bd099
        if self._sslobj is not None:
rpm-build 2bd099
            return self._sslobj.session_reused
rpm-build 2bd099
rpm-build 2bd099
    def dup(self):
rpm-build 2bd099
        raise NotImplemented("Can't dup() %s instances" %
rpm-build 2bd099
                             self.__class__.__name__)
rpm-build 2bd099
rpm-build 2bd099
    def _checkClosed(self, msg=None):
rpm-build 2bd099
        # raise an exception here if you wish to check for spurious closes
rpm-build 2bd099
        pass
rpm-build 2bd099
rpm-build 2bd099
    def _check_connected(self):
rpm-build 2bd099
        if not self._connected:
rpm-build 2bd099
            # getpeername() will raise ENOTCONN if the socket is really
rpm-build 2bd099
            # not connected; note that we can be connected even without
rpm-build 2bd099
            # _connected being set, e.g. if connect() first returned
rpm-build 2bd099
            # EAGAIN.
rpm-build 2bd099
            self.getpeername()
rpm-build 2bd099
rpm-build 2bd099
    def read(self, len=1024, buffer=None):
rpm-build 2bd099
        """Read up to LEN bytes and return them.
rpm-build 2bd099
        Return zero-length string on EOF."""
rpm-build 2bd099
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj:
rpm-build 2bd099
            raise ValueError("Read on closed or unwrapped SSL socket.")
rpm-build 2bd099
        try:
rpm-build 2bd099
            return self._sslobj.read(len, buffer)
rpm-build 2bd099
        except SSLError as x:
rpm-build 2bd099
            if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
rpm-build 2bd099
                if buffer is not None:
rpm-build 2bd099
                    return 0
rpm-build 2bd099
                else:
rpm-build 2bd099
                    return b''
rpm-build 2bd099
            else:
rpm-build 2bd099
                raise
rpm-build 2bd099
rpm-build 2bd099
    def write(self, data):
rpm-build 2bd099
        """Write DATA to the underlying SSL channel.  Returns
rpm-build 2bd099
        number of bytes of DATA actually transmitted."""
rpm-build 2bd099
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj:
rpm-build 2bd099
            raise ValueError("Write on closed or unwrapped SSL socket.")
rpm-build 2bd099
        return self._sslobj.write(data)
rpm-build 2bd099
rpm-build 2bd099
    def getpeercert(self, binary_form=False):
rpm-build 2bd099
        """Returns a formatted version of the data in the
rpm-build 2bd099
        certificate provided by the other end of the SSL channel.
rpm-build 2bd099
        Return None if no certificate was provided, {} if a
rpm-build 2bd099
        certificate was provided, but not validated."""
rpm-build 2bd099
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        self._check_connected()
rpm-build 2bd099
        return self._sslobj.getpeercert(binary_form)
rpm-build 2bd099
rpm-build 2bd099
    def selected_npn_protocol(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj or not _ssl.HAS_NPN:
rpm-build 2bd099
            return None
rpm-build 2bd099
        else:
rpm-build 2bd099
            return self._sslobj.selected_npn_protocol()
rpm-build 2bd099
rpm-build 2bd099
    def selected_alpn_protocol(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj or not _ssl.HAS_ALPN:
rpm-build 2bd099
            return None
rpm-build 2bd099
        else:
rpm-build 2bd099
            return self._sslobj.selected_alpn_protocol()
rpm-build 2bd099
rpm-build 2bd099
    def cipher(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj:
rpm-build 2bd099
            return None
rpm-build 2bd099
        else:
rpm-build 2bd099
            return self._sslobj.cipher()
rpm-build 2bd099
rpm-build 2bd099
    def shared_ciphers(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj:
rpm-build 2bd099
            return None
rpm-build 2bd099
        return self._sslobj.shared_ciphers()
rpm-build 2bd099
rpm-build 2bd099
    def compression(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if not self._sslobj:
rpm-build 2bd099
            return None
rpm-build 2bd099
        else:
rpm-build 2bd099
            return self._sslobj.compression()
rpm-build 2bd099
rpm-build 2bd099
    def send(self, data, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            if flags != 0:
rpm-build 2bd099
                raise ValueError(
rpm-build 2bd099
                    "non-zero flags not allowed in calls to send() on %s" %
rpm-build 2bd099
                    self.__class__)
rpm-build 2bd099
            return self._sslobj.write(data)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.send(self, data, flags)
rpm-build 2bd099
rpm-build 2bd099
    def sendto(self, data, flags_or_addr, addr=None):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            raise ValueError("sendto not allowed on instances of %s" %
rpm-build 2bd099
                             self.__class__)
rpm-build 2bd099
        elif addr is None:
rpm-build 2bd099
            return socket.sendto(self, data, flags_or_addr)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.sendto(self, data, flags_or_addr, addr)
rpm-build 2bd099
rpm-build 2bd099
    def sendmsg(self, *args, **kwargs):
rpm-build 2bd099
        # Ensure programs don't send data unencrypted if they try to
rpm-build 2bd099
        # use this method.
rpm-build 2bd099
        raise NotImplementedError("sendmsg not allowed on instances of %s" %
rpm-build 2bd099
                                  self.__class__)
rpm-build 2bd099
rpm-build 2bd099
    def sendall(self, data, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            if flags != 0:
rpm-build 2bd099
                raise ValueError(
rpm-build 2bd099
                    "non-zero flags not allowed in calls to sendall() on %s" %
rpm-build 2bd099
                    self.__class__)
rpm-build 2bd099
            count = 0
rpm-build 2bd099
            with memoryview(data) as view, view.cast("B") as byte_view:
rpm-build 2bd099
                amount = len(byte_view)
rpm-build 2bd099
                while count < amount:
rpm-build 2bd099
                    v = self.send(byte_view[count:])
rpm-build 2bd099
                    count += v
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.sendall(self, data, flags)
rpm-build 2bd099
rpm-build 2bd099
    def sendfile(self, file, offset=0, count=None):
rpm-build 2bd099
        """Send a file, possibly by using os.sendfile() if this is a
rpm-build 2bd099
        clear-text socket.  Return the total number of bytes sent.
rpm-build 2bd099
        """
rpm-build 2bd099
        if self._sslobj is None:
rpm-build 2bd099
            # os.sendfile() works with plain sockets only
rpm-build 2bd099
            return super().sendfile(file, offset, count)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return self._sendfile_use_send(file, offset, count)
rpm-build 2bd099
rpm-build 2bd099
    def recv(self, buflen=1024, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            if flags != 0:
rpm-build 2bd099
                raise ValueError(
rpm-build 2bd099
                    "non-zero flags not allowed in calls to recv() on %s" %
rpm-build 2bd099
                    self.__class__)
rpm-build 2bd099
            return self.read(buflen)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.recv(self, buflen, flags)
rpm-build 2bd099
rpm-build 2bd099
    def recv_into(self, buffer, nbytes=None, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if buffer and (nbytes is None):
rpm-build 2bd099
            nbytes = len(buffer)
rpm-build 2bd099
        elif nbytes is None:
rpm-build 2bd099
            nbytes = 1024
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            if flags != 0:
rpm-build 2bd099
                raise ValueError(
rpm-build 2bd099
                  "non-zero flags not allowed in calls to recv_into() on %s" %
rpm-build 2bd099
                  self.__class__)
rpm-build 2bd099
            return self.read(nbytes, buffer)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.recv_into(self, buffer, nbytes, flags)
rpm-build 2bd099
rpm-build 2bd099
    def recvfrom(self, buflen=1024, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            raise ValueError("recvfrom not allowed on instances of %s" %
rpm-build 2bd099
                             self.__class__)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.recvfrom(self, buflen, flags)
rpm-build 2bd099
rpm-build 2bd099
    def recvfrom_into(self, buffer, nbytes=None, flags=0):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            raise ValueError("recvfrom_into not allowed on instances of %s" %
rpm-build 2bd099
                             self.__class__)
rpm-build 2bd099
        else:
rpm-build 2bd099
            return socket.recvfrom_into(self, buffer, nbytes, flags)
rpm-build 2bd099
rpm-build 2bd099
    def recvmsg(self, *args, **kwargs):
rpm-build 2bd099
        raise NotImplementedError("recvmsg not allowed on instances of %s" %
rpm-build 2bd099
                                  self.__class__)
rpm-build 2bd099
rpm-build 2bd099
    def recvmsg_into(self, *args, **kwargs):
rpm-build 2bd099
        raise NotImplementedError("recvmsg_into not allowed on instances of "
rpm-build 2bd099
                                  "%s" % self.__class__)
rpm-build 2bd099
rpm-build 2bd099
    def pending(self):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            return self._sslobj.pending()
rpm-build 2bd099
        else:
rpm-build 2bd099
            return 0
rpm-build 2bd099
rpm-build 2bd099
    def shutdown(self, how):
rpm-build 2bd099
        self._checkClosed()
rpm-build 2bd099
        self._sslobj = None
rpm-build 2bd099
        socket.shutdown(self, how)
rpm-build 2bd099
rpm-build 2bd099
    def unwrap(self):
rpm-build 2bd099
        if self._sslobj:
rpm-build 2bd099
            s = self._sslobj.unwrap()
rpm-build 2bd099
            self._sslobj = None
rpm-build 2bd099
            return s
rpm-build 2bd099
        else:
rpm-build 2bd099
            raise ValueError("No SSL wrapper around " + str(self))
rpm-build 2bd099
rpm-build 2bd099
    def _real_close(self):
rpm-build 2bd099
        self._sslobj = None
rpm-build 2bd099
        socket._real_close(self)
rpm-build 2bd099
rpm-build 2bd099
    def do_handshake(self, block=False):
rpm-build 2bd099
        """Perform a TLS/SSL handshake."""
rpm-build 2bd099
        self._check_connected()
rpm-build 2bd099
        timeout = self.gettimeout()
rpm-build 2bd099
        try:
rpm-build 2bd099
            if timeout == 0.0 and block:
rpm-build 2bd099
                self.settimeout(None)
rpm-build 2bd099
            self._sslobj.do_handshake()
rpm-build 2bd099
        finally:
rpm-build 2bd099
            self.settimeout(timeout)
rpm-build 2bd099
rpm-build 2bd099
    def _real_connect(self, addr, connect_ex):
rpm-build 2bd099
        if self.server_side:
rpm-build 2bd099
            raise ValueError("can't connect in server-side mode")
rpm-build 2bd099
        # Here we assume that the socket is client-side, and not
rpm-build 2bd099
        # connected at the time of the call.  We connect it, then wrap it.
rpm-build 2bd099
        if self._connected:
rpm-build 2bd099
            raise ValueError("attempt to connect already-connected SSLSocket!")
rpm-build 2bd099
        sslobj = self.context._wrap_socket(self, False, self.server_hostname)
rpm-build 2bd099
        self._sslobj = SSLObject(sslobj, owner=self,
rpm-build 2bd099
                                 session=self._session)
rpm-build 2bd099
        try:
rpm-build 2bd099
            if connect_ex:
rpm-build 2bd099
                rc = socket.connect_ex(self, addr)
rpm-build 2bd099
            else:
rpm-build 2bd099
                rc = None
rpm-build 2bd099
                socket.connect(self, addr)
rpm-build 2bd099
            if not rc:
rpm-build 2bd099
                self._connected = True
rpm-build 2bd099
                if self.do_handshake_on_connect:
rpm-build 2bd099
                    self.do_handshake()
rpm-build 2bd099
            return rc
rpm-build 2bd099
        except (OSError, ValueError):
rpm-build 2bd099
            self._sslobj = None
rpm-build 2bd099
            raise
rpm-build 2bd099
rpm-build 2bd099
    def connect(self, addr):
rpm-build 2bd099
        """Connects to remote ADDR, and then wraps the connection in
rpm-build 2bd099
        an SSL channel."""
rpm-build 2bd099
        self._real_connect(addr, False)
rpm-build 2bd099
rpm-build 2bd099
    def connect_ex(self, addr):
rpm-build 2bd099
        """Connects to remote ADDR, and then wraps the connection in
rpm-build 2bd099
        an SSL channel."""
rpm-build 2bd099
        return self._real_connect(addr, True)
rpm-build 2bd099
rpm-build 2bd099
    def accept(self):
rpm-build 2bd099
        """Accepts a new connection from a remote client, and returns
rpm-build 2bd099
        a tuple containing that new connection wrapped with a server-side
rpm-build 2bd099
        SSL channel, and the address of the remote client."""
rpm-build 2bd099
rpm-build 2bd099
        newsock, addr = socket.accept(self)
rpm-build 2bd099
        newsock = self.context.wrap_socket(newsock,
rpm-build 2bd099
                    do_handshake_on_connect=self.do_handshake_on_connect,
rpm-build 2bd099
                    suppress_ragged_eofs=self.suppress_ragged_eofs,
rpm-build 2bd099
                    server_side=True)
rpm-build 2bd099
        return newsock, addr
rpm-build 2bd099
rpm-build 2bd099
    def get_channel_binding(self, cb_type="tls-unique"):
rpm-build 2bd099
        """Get channel binding data for current connection.  Raise ValueError
rpm-build 2bd099
        if the requested `cb_type` is not supported.  Return bytes of the data
rpm-build 2bd099
        or None if the data is not available (e.g. before the handshake).
rpm-build 2bd099
        """
rpm-build 2bd099
        if self._sslobj is None:
rpm-build 2bd099
            return None
rpm-build 2bd099
        return self._sslobj.get_channel_binding(cb_type)
rpm-build 2bd099
rpm-build 2bd099
    def version(self):
rpm-build 2bd099
        """
rpm-build 2bd099
        Return a string identifying the protocol version used by the
rpm-build 2bd099
        current SSL channel, or None if there is no established channel.
rpm-build 2bd099
        """
rpm-build 2bd099
        if self._sslobj is None:
rpm-build 2bd099
            return None
rpm-build 2bd099
        return self._sslobj.version()
rpm-build 2bd099
rpm-build 2bd099
rpm-build 2bd099
def wrap_socket(sock, keyfile=None, certfile=None,
rpm-build 2bd099
                server_side=False, cert_reqs=CERT_NONE,
rpm-build 2bd099
                ssl_version=PROTOCOL_TLS, ca_certs=None,
rpm-build 2bd099
                do_handshake_on_connect=True,
rpm-build 2bd099
                suppress_ragged_eofs=True,
rpm-build 2bd099
                ciphers=None):
rpm-build 2bd099
    return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
rpm-build 2bd099
                     server_side=server_side, cert_reqs=cert_reqs,
rpm-build 2bd099
                     ssl_version=ssl_version, ca_certs=ca_certs,
rpm-build 2bd099
                     do_handshake_on_connect=do_handshake_on_connect,
rpm-build 2bd099
                     suppress_ragged_eofs=suppress_ragged_eofs,
rpm-build 2bd099
                     ciphers=ciphers)
rpm-build 2bd099
rpm-build 2bd099
# some utility functions
rpm-build 2bd099
rpm-build 2bd099
def cert_time_to_seconds(cert_time):
rpm-build 2bd099
    """Return the time in seconds since the Epoch, given the timestring
rpm-build 2bd099
    representing the "notBefore" or "notAfter" date from a certificate
rpm-build 2bd099
    in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
rpm-build 2bd099
rpm-build 2bd099
    "notBefore" or "notAfter" dates must use UTC (RFC 5280).
rpm-build 2bd099
rpm-build 2bd099
    Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
rpm-build 2bd099
    UTC should be specified as GMT (see ASN1_TIME_print())
rpm-build 2bd099
    """
rpm-build 2bd099
    from time import strptime
rpm-build 2bd099
    from calendar import timegm
rpm-build 2bd099
rpm-build 2bd099
    months = (
rpm-build 2bd099
        "Jan","Feb","Mar","Apr","May","Jun",
rpm-build 2bd099
        "Jul","Aug","Sep","Oct","Nov","Dec"
rpm-build 2bd099
    )
rpm-build 2bd099
    time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
rpm-build 2bd099
    try:
rpm-build 2bd099
        month_number = months.index(cert_time[:3].title()) + 1
rpm-build 2bd099
    except ValueError:
rpm-build 2bd099
        raise ValueError('time data %r does not match '
rpm-build 2bd099
                         'format "%%b%s"' % (cert_time, time_format))
rpm-build 2bd099
    else:
rpm-build 2bd099
        # found valid month
rpm-build 2bd099
        tt = strptime(cert_time[3:], time_format)
rpm-build 2bd099
        # return an integer, the previous mktime()-based implementation
rpm-build 2bd099
        # returned a float (fractional seconds are always zero here).
rpm-build 2bd099
        return timegm((tt[0], month_number) + tt[2:6])
rpm-build 2bd099
rpm-build 2bd099
PEM_HEADER = "-----BEGIN CERTIFICATE-----"
rpm-build 2bd099
PEM_FOOTER = "-----END CERTIFICATE-----"
rpm-build 2bd099
rpm-build 2bd099
def DER_cert_to_PEM_cert(der_cert_bytes):
rpm-build 2bd099
    """Takes a certificate in binary DER format and returns the
rpm-build 2bd099
    PEM version of it as a string."""
rpm-build 2bd099
rpm-build 2bd099
    f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
rpm-build 2bd099
    return (PEM_HEADER + '\n' +
rpm-build 2bd099
            textwrap.fill(f, 64) + '\n' +
rpm-build 2bd099
            PEM_FOOTER + '\n')
rpm-build 2bd099
rpm-build 2bd099
def PEM_cert_to_DER_cert(pem_cert_string):
rpm-build 2bd099
    """Takes a certificate in ASCII PEM format and returns the
rpm-build 2bd099
    DER-encoded version of it as a byte sequence"""
rpm-build 2bd099
rpm-build 2bd099
    if not pem_cert_string.startswith(PEM_HEADER):
rpm-build 2bd099
        raise ValueError("Invalid PEM encoding; must start with %s"
rpm-build 2bd099
                         % PEM_HEADER)
rpm-build 2bd099
    if not pem_cert_string.strip().endswith(PEM_FOOTER):
rpm-build 2bd099
        raise ValueError("Invalid PEM encoding; must end with %s"
rpm-build 2bd099
                         % PEM_FOOTER)
rpm-build 2bd099
    d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
rpm-build 2bd099
    return base64.decodebytes(d.encode('ASCII', 'strict'))
rpm-build 2bd099
rpm-build 2bd099
def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
rpm-build 2bd099
    """Retrieve the certificate from the server at the specified address,
rpm-build 2bd099
    and return it as a PEM-encoded string.
rpm-build 2bd099
    If 'ca_certs' is specified, validate the server cert against it.
rpm-build 2bd099
    If 'ssl_version' is specified, use it in the connection attempt."""
rpm-build 2bd099
rpm-build 2bd099
    host, port = addr
rpm-build 2bd099
    if ca_certs is not None:
rpm-build 2bd099
        cert_reqs = CERT_REQUIRED
rpm-build 2bd099
    else:
rpm-build 2bd099
        cert_reqs = CERT_NONE
rpm-build 2bd099
    context = _create_stdlib_context(ssl_version,
rpm-build 2bd099
                                     cert_reqs=cert_reqs,
rpm-build 2bd099
                                     cafile=ca_certs)
rpm-build 2bd099
    with  create_connection(addr) as sock:
rpm-build 2bd099
        with context.wrap_socket(sock) as sslsock:
rpm-build 2bd099
            dercert = sslsock.getpeercert(True)
rpm-build 2bd099
    return DER_cert_to_PEM_cert(dercert)
rpm-build 2bd099
rpm-build 2bd099
def get_protocol_name(protocol_code):
rpm-build 2bd099
    return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')