Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../lib64/python2....
File: ssl.py
# Wrapper module for _ssl, providing some additional facilities
[0] Fix | Delete
# implemented in Python. Written by Bill Janssen.
[1] Fix | Delete
[2] Fix | Delete
"""This module provides some more Pythonic support for SSL.
[3] Fix | Delete
[4] Fix | Delete
Object types:
[5] Fix | Delete
[6] Fix | Delete
SSLSocket -- subtype of socket.socket which does SSL over the socket
[7] Fix | Delete
[8] Fix | Delete
Exceptions:
[9] Fix | Delete
[10] Fix | Delete
SSLError -- exception raised for I/O errors
[11] Fix | Delete
[12] Fix | Delete
Functions:
[13] Fix | Delete
[14] Fix | Delete
cert_time_to_seconds -- convert time string used for certificate
[15] Fix | Delete
notBefore and notAfter functions to integer
[16] Fix | Delete
seconds past the Epoch (the time values
[17] Fix | Delete
returned from time.time())
[18] Fix | Delete
[19] Fix | Delete
fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
[20] Fix | Delete
by the server running on HOST at port PORT. No
[21] Fix | Delete
validation of the certificate is performed.
[22] Fix | Delete
[23] Fix | Delete
Integer constants:
[24] Fix | Delete
[25] Fix | Delete
SSL_ERROR_ZERO_RETURN
[26] Fix | Delete
SSL_ERROR_WANT_READ
[27] Fix | Delete
SSL_ERROR_WANT_WRITE
[28] Fix | Delete
SSL_ERROR_WANT_X509_LOOKUP
[29] Fix | Delete
SSL_ERROR_SYSCALL
[30] Fix | Delete
SSL_ERROR_SSL
[31] Fix | Delete
SSL_ERROR_WANT_CONNECT
[32] Fix | Delete
[33] Fix | Delete
SSL_ERROR_EOF
[34] Fix | Delete
SSL_ERROR_INVALID_ERROR_CODE
[35] Fix | Delete
[36] Fix | Delete
The following group define certificate requirements that one side is
[37] Fix | Delete
allowing/requiring from the other side:
[38] Fix | Delete
[39] Fix | Delete
CERT_NONE - no certificates from the other side are required (or will
[40] Fix | Delete
be looked at if provided)
[41] Fix | Delete
CERT_OPTIONAL - certificates are not required, but if provided will be
[42] Fix | Delete
validated, and if validation fails, the connection will
[43] Fix | Delete
also fail
[44] Fix | Delete
CERT_REQUIRED - certificates are required, and will be validated, and
[45] Fix | Delete
if validation fails, the connection will also fail
[46] Fix | Delete
[47] Fix | Delete
The following constants identify various SSL protocol variants:
[48] Fix | Delete
[49] Fix | Delete
PROTOCOL_SSLv2
[50] Fix | Delete
PROTOCOL_SSLv3
[51] Fix | Delete
PROTOCOL_SSLv23
[52] Fix | Delete
PROTOCOL_TLS
[53] Fix | Delete
PROTOCOL_TLSv1
[54] Fix | Delete
PROTOCOL_TLSv1_1
[55] Fix | Delete
PROTOCOL_TLSv1_2
[56] Fix | Delete
[57] Fix | Delete
The following constants identify various SSL alert message descriptions as per
[58] Fix | Delete
http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
[59] Fix | Delete
[60] Fix | Delete
ALERT_DESCRIPTION_CLOSE_NOTIFY
[61] Fix | Delete
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
[62] Fix | Delete
ALERT_DESCRIPTION_BAD_RECORD_MAC
[63] Fix | Delete
ALERT_DESCRIPTION_RECORD_OVERFLOW
[64] Fix | Delete
ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
[65] Fix | Delete
ALERT_DESCRIPTION_HANDSHAKE_FAILURE
[66] Fix | Delete
ALERT_DESCRIPTION_BAD_CERTIFICATE
[67] Fix | Delete
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
[68] Fix | Delete
ALERT_DESCRIPTION_CERTIFICATE_REVOKED
[69] Fix | Delete
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
[70] Fix | Delete
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
[71] Fix | Delete
ALERT_DESCRIPTION_ILLEGAL_PARAMETER
[72] Fix | Delete
ALERT_DESCRIPTION_UNKNOWN_CA
[73] Fix | Delete
ALERT_DESCRIPTION_ACCESS_DENIED
[74] Fix | Delete
ALERT_DESCRIPTION_DECODE_ERROR
[75] Fix | Delete
ALERT_DESCRIPTION_DECRYPT_ERROR
[76] Fix | Delete
ALERT_DESCRIPTION_PROTOCOL_VERSION
[77] Fix | Delete
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
[78] Fix | Delete
ALERT_DESCRIPTION_INTERNAL_ERROR
[79] Fix | Delete
ALERT_DESCRIPTION_USER_CANCELLED
[80] Fix | Delete
ALERT_DESCRIPTION_NO_RENEGOTIATION
[81] Fix | Delete
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
[82] Fix | Delete
ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
[83] Fix | Delete
ALERT_DESCRIPTION_UNRECOGNIZED_NAME
[84] Fix | Delete
ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
[85] Fix | Delete
ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
[86] Fix | Delete
ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
[87] Fix | Delete
"""
[88] Fix | Delete
[89] Fix | Delete
import textwrap
[90] Fix | Delete
import re
[91] Fix | Delete
import sys
[92] Fix | Delete
import os
[93] Fix | Delete
from collections import namedtuple
[94] Fix | Delete
from contextlib import closing
[95] Fix | Delete
[96] Fix | Delete
import _ssl # if we can't import it, let the error propagate
[97] Fix | Delete
[98] Fix | Delete
from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
[99] Fix | Delete
from _ssl import _SSLContext
[100] Fix | Delete
from _ssl import (
[101] Fix | Delete
SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
[102] Fix | Delete
SSLSyscallError, SSLEOFError,
[103] Fix | Delete
)
[104] Fix | Delete
from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
[105] Fix | Delete
from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
[106] Fix | Delete
from _ssl import RAND_status, RAND_add
[107] Fix | Delete
try:
[108] Fix | Delete
from _ssl import RAND_egd
[109] Fix | Delete
except ImportError:
[110] Fix | Delete
# LibreSSL does not provide RAND_egd
[111] Fix | Delete
pass
[112] Fix | Delete
[113] Fix | Delete
def _import_symbols(prefix):
[114] Fix | Delete
for n in dir(_ssl):
[115] Fix | Delete
if n.startswith(prefix):
[116] Fix | Delete
globals()[n] = getattr(_ssl, n)
[117] Fix | Delete
[118] Fix | Delete
_import_symbols('OP_')
[119] Fix | Delete
_import_symbols('ALERT_DESCRIPTION_')
[120] Fix | Delete
_import_symbols('SSL_ERROR_')
[121] Fix | Delete
_import_symbols('PROTOCOL_')
[122] Fix | Delete
_import_symbols('VERIFY_')
[123] Fix | Delete
[124] Fix | Delete
from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_TLSv1_3
[125] Fix | Delete
[126] Fix | Delete
from _ssl import _OPENSSL_API_VERSION
[127] Fix | Delete
[128] Fix | Delete
_PROTOCOL_NAMES = {value: name for name, value in globals().items()
[129] Fix | Delete
if name.startswith('PROTOCOL_')
[130] Fix | Delete
and name != 'PROTOCOL_SSLv23'}
[131] Fix | Delete
PROTOCOL_SSLv23 = PROTOCOL_TLS
[132] Fix | Delete
[133] Fix | Delete
try:
[134] Fix | Delete
_SSLv2_IF_EXISTS = PROTOCOL_SSLv2
[135] Fix | Delete
except NameError:
[136] Fix | Delete
_SSLv2_IF_EXISTS = None
[137] Fix | Delete
[138] Fix | Delete
from socket import socket, _fileobject, _delegate_methods, error as socket_error
[139] Fix | Delete
if sys.platform == "win32":
[140] Fix | Delete
from _ssl import enum_certificates, enum_crls
[141] Fix | Delete
[142] Fix | Delete
from socket import socket, AF_INET, SOCK_STREAM, create_connection
[143] Fix | Delete
from socket import SOL_SOCKET, SO_TYPE
[144] Fix | Delete
import base64 # for DER-to-PEM translation
[145] Fix | Delete
import errno
[146] Fix | Delete
import warnings
[147] Fix | Delete
[148] Fix | Delete
if _ssl.HAS_TLS_UNIQUE:
[149] Fix | Delete
CHANNEL_BINDING_TYPES = ['tls-unique']
[150] Fix | Delete
else:
[151] Fix | Delete
CHANNEL_BINDING_TYPES = []
[152] Fix | Delete
[153] Fix | Delete
[154] Fix | Delete
# Disable weak or insecure ciphers by default
[155] Fix | Delete
# (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
[156] Fix | Delete
# Enable a better set of ciphers by default
[157] Fix | Delete
# This list has been explicitly chosen to:
[158] Fix | Delete
# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
[159] Fix | Delete
# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
[160] Fix | Delete
# * Prefer ECDHE over DHE for better performance
[161] Fix | Delete
# * Prefer AEAD over CBC for better performance and security
[162] Fix | Delete
# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
[163] Fix | Delete
# (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
[164] Fix | Delete
# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
[165] Fix | Delete
# performance and security
[166] Fix | Delete
# * Then Use HIGH cipher suites as a fallback
[167] Fix | Delete
# * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
[168] Fix | Delete
# for security reasons
[169] Fix | Delete
_DEFAULT_CIPHERS = (
[170] Fix | Delete
'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
[171] Fix | Delete
'TLS13-AES-128-GCM-SHA256:'
[172] Fix | Delete
'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
[173] Fix | Delete
'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
[174] Fix | Delete
'!aNULL:!eNULL:!MD5:!3DES'
[175] Fix | Delete
)
[176] Fix | Delete
[177] Fix | Delete
# Restricted and more secure ciphers for the server side
[178] Fix | Delete
# This list has been explicitly chosen to:
[179] Fix | Delete
# * TLS 1.3 ChaCha20 and AES-GCM cipher suites
[180] Fix | Delete
# * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
[181] Fix | Delete
# * Prefer ECDHE over DHE for better performance
[182] Fix | Delete
# * Prefer AEAD over CBC for better performance and security
[183] Fix | Delete
# * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
[184] Fix | Delete
# * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
[185] Fix | Delete
# performance and security
[186] Fix | Delete
# * Then Use HIGH cipher suites as a fallback
[187] Fix | Delete
# * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
[188] Fix | Delete
# 3DES for security reasons
[189] Fix | Delete
_RESTRICTED_SERVER_CIPHERS = (
[190] Fix | Delete
'TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:'
[191] Fix | Delete
'TLS13-AES-128-GCM-SHA256:'
[192] Fix | Delete
'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
[193] Fix | Delete
'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
[194] Fix | Delete
'!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
[195] Fix | Delete
)
[196] Fix | Delete
[197] Fix | Delete
[198] Fix | Delete
class CertificateError(ValueError):
[199] Fix | Delete
pass
[200] Fix | Delete
[201] Fix | Delete
[202] Fix | Delete
def _dnsname_match(dn, hostname, max_wildcards=1):
[203] Fix | Delete
"""Matching according to RFC 6125, section 6.4.3
[204] Fix | Delete
[205] Fix | Delete
http://tools.ietf.org/html/rfc6125#section-6.4.3
[206] Fix | Delete
"""
[207] Fix | Delete
pats = []
[208] Fix | Delete
if not dn:
[209] Fix | Delete
return False
[210] Fix | Delete
[211] Fix | Delete
pieces = dn.split(r'.')
[212] Fix | Delete
leftmost = pieces[0]
[213] Fix | Delete
remainder = pieces[1:]
[214] Fix | Delete
[215] Fix | Delete
wildcards = leftmost.count('*')
[216] Fix | Delete
if wildcards > max_wildcards:
[217] Fix | Delete
# Issue #17980: avoid denials of service by refusing more
[218] Fix | Delete
# than one wildcard per fragment. A survery of established
[219] Fix | Delete
# policy among SSL implementations showed it to be a
[220] Fix | Delete
# reasonable choice.
[221] Fix | Delete
raise CertificateError(
[222] Fix | Delete
"too many wildcards in certificate DNS name: " + repr(dn))
[223] Fix | Delete
[224] Fix | Delete
# speed up common case w/o wildcards
[225] Fix | Delete
if not wildcards:
[226] Fix | Delete
return dn.lower() == hostname.lower()
[227] Fix | Delete
[228] Fix | Delete
# RFC 6125, section 6.4.3, subitem 1.
[229] Fix | Delete
# The client SHOULD NOT attempt to match a presented identifier in which
[230] Fix | Delete
# the wildcard character comprises a label other than the left-most label.
[231] Fix | Delete
if leftmost == '*':
[232] Fix | Delete
# When '*' is a fragment by itself, it matches a non-empty dotless
[233] Fix | Delete
# fragment.
[234] Fix | Delete
pats.append('[^.]+')
[235] Fix | Delete
elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
[236] Fix | Delete
# RFC 6125, section 6.4.3, subitem 3.
[237] Fix | Delete
# The client SHOULD NOT attempt to match a presented identifier
[238] Fix | Delete
# where the wildcard character is embedded within an A-label or
[239] Fix | Delete
# U-label of an internationalized domain name.
[240] Fix | Delete
pats.append(re.escape(leftmost))
[241] Fix | Delete
else:
[242] Fix | Delete
# Otherwise, '*' matches any dotless string, e.g. www*
[243] Fix | Delete
pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
[244] Fix | Delete
[245] Fix | Delete
# add the remaining fragments, ignore any wildcards
[246] Fix | Delete
for frag in remainder:
[247] Fix | Delete
pats.append(re.escape(frag))
[248] Fix | Delete
[249] Fix | Delete
pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
[250] Fix | Delete
return pat.match(hostname)
[251] Fix | Delete
[252] Fix | Delete
[253] Fix | Delete
def match_hostname(cert, hostname):
[254] Fix | Delete
"""Verify that *cert* (in decoded format as returned by
[255] Fix | Delete
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
[256] Fix | Delete
rules are followed, but IP addresses are not accepted for *hostname*.
[257] Fix | Delete
[258] Fix | Delete
CertificateError is raised on failure. On success, the function
[259] Fix | Delete
returns nothing.
[260] Fix | Delete
"""
[261] Fix | Delete
if not cert:
[262] Fix | Delete
raise ValueError("empty or no certificate, match_hostname needs a "
[263] Fix | Delete
"SSL socket or SSL context with either "
[264] Fix | Delete
"CERT_OPTIONAL or CERT_REQUIRED")
[265] Fix | Delete
dnsnames = []
[266] Fix | Delete
san = cert.get('subjectAltName', ())
[267] Fix | Delete
for key, value in san:
[268] Fix | Delete
if key == 'DNS':
[269] Fix | Delete
if _dnsname_match(value, hostname):
[270] Fix | Delete
return
[271] Fix | Delete
dnsnames.append(value)
[272] Fix | Delete
if not dnsnames:
[273] Fix | Delete
# The subject is only checked when there is no dNSName entry
[274] Fix | Delete
# in subjectAltName
[275] Fix | Delete
for sub in cert.get('subject', ()):
[276] Fix | Delete
for key, value in sub:
[277] Fix | Delete
# XXX according to RFC 2818, the most specific Common Name
[278] Fix | Delete
# must be used.
[279] Fix | Delete
if key == 'commonName':
[280] Fix | Delete
if _dnsname_match(value, hostname):
[281] Fix | Delete
return
[282] Fix | Delete
dnsnames.append(value)
[283] Fix | Delete
if len(dnsnames) > 1:
[284] Fix | Delete
raise CertificateError("hostname %r "
[285] Fix | Delete
"doesn't match either of %s"
[286] Fix | Delete
% (hostname, ', '.join(map(repr, dnsnames))))
[287] Fix | Delete
elif len(dnsnames) == 1:
[288] Fix | Delete
raise CertificateError("hostname %r "
[289] Fix | Delete
"doesn't match %r"
[290] Fix | Delete
% (hostname, dnsnames[0]))
[291] Fix | Delete
else:
[292] Fix | Delete
raise CertificateError("no appropriate commonName or "
[293] Fix | Delete
"subjectAltName fields were found")
[294] Fix | Delete
[295] Fix | Delete
[296] Fix | Delete
DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
[297] Fix | Delete
"cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
[298] Fix | Delete
"openssl_capath")
[299] Fix | Delete
[300] Fix | Delete
def get_default_verify_paths():
[301] Fix | Delete
"""Return paths to default cafile and capath.
[302] Fix | Delete
"""
[303] Fix | Delete
parts = _ssl.get_default_verify_paths()
[304] Fix | Delete
[305] Fix | Delete
# environment vars shadow paths
[306] Fix | Delete
cafile = os.environ.get(parts[0], parts[1])
[307] Fix | Delete
capath = os.environ.get(parts[2], parts[3])
[308] Fix | Delete
[309] Fix | Delete
return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
[310] Fix | Delete
capath if os.path.isdir(capath) else None,
[311] Fix | Delete
*parts)
[312] Fix | Delete
[313] Fix | Delete
[314] Fix | Delete
class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
[315] Fix | Delete
"""ASN.1 object identifier lookup
[316] Fix | Delete
"""
[317] Fix | Delete
__slots__ = ()
[318] Fix | Delete
[319] Fix | Delete
def __new__(cls, oid):
[320] Fix | Delete
return super(_ASN1Object, cls).__new__(cls, *_txt2obj(oid, name=False))
[321] Fix | Delete
[322] Fix | Delete
@classmethod
[323] Fix | Delete
def fromnid(cls, nid):
[324] Fix | Delete
"""Create _ASN1Object from OpenSSL numeric ID
[325] Fix | Delete
"""
[326] Fix | Delete
return super(_ASN1Object, cls).__new__(cls, *_nid2obj(nid))
[327] Fix | Delete
[328] Fix | Delete
@classmethod
[329] Fix | Delete
def fromname(cls, name):
[330] Fix | Delete
"""Create _ASN1Object from short name, long name or OID
[331] Fix | Delete
"""
[332] Fix | Delete
return super(_ASN1Object, cls).__new__(cls, *_txt2obj(name, name=True))
[333] Fix | Delete
[334] Fix | Delete
[335] Fix | Delete
class Purpose(_ASN1Object):
[336] Fix | Delete
"""SSLContext purpose flags with X509v3 Extended Key Usage objects
[337] Fix | Delete
"""
[338] Fix | Delete
[339] Fix | Delete
Purpose.SERVER_AUTH = Purpose('1.3.6.1.5.5.7.3.1')
[340] Fix | Delete
Purpose.CLIENT_AUTH = Purpose('1.3.6.1.5.5.7.3.2')
[341] Fix | Delete
[342] Fix | Delete
[343] Fix | Delete
class SSLContext(_SSLContext):
[344] Fix | Delete
"""An SSLContext holds various SSL-related configuration options and
[345] Fix | Delete
data, such as certificates and possibly a private key."""
[346] Fix | Delete
[347] Fix | Delete
__slots__ = ('protocol', '__weakref__')
[348] Fix | Delete
_windows_cert_stores = ("CA", "ROOT")
[349] Fix | Delete
[350] Fix | Delete
def __new__(cls, protocol, *args, **kwargs):
[351] Fix | Delete
self = _SSLContext.__new__(cls, protocol)
[352] Fix | Delete
if protocol != _SSLv2_IF_EXISTS:
[353] Fix | Delete
self.set_ciphers(_DEFAULT_CIPHERS)
[354] Fix | Delete
return self
[355] Fix | Delete
[356] Fix | Delete
def __init__(self, protocol):
[357] Fix | Delete
self.protocol = protocol
[358] Fix | Delete
[359] Fix | Delete
def wrap_socket(self, sock, server_side=False,
[360] Fix | Delete
do_handshake_on_connect=True,
[361] Fix | Delete
suppress_ragged_eofs=True,
[362] Fix | Delete
server_hostname=None):
[363] Fix | Delete
return SSLSocket(sock=sock, server_side=server_side,
[364] Fix | Delete
do_handshake_on_connect=do_handshake_on_connect,
[365] Fix | Delete
suppress_ragged_eofs=suppress_ragged_eofs,
[366] Fix | Delete
server_hostname=server_hostname,
[367] Fix | Delete
_context=self)
[368] Fix | Delete
[369] Fix | Delete
def set_npn_protocols(self, npn_protocols):
[370] Fix | Delete
protos = bytearray()
[371] Fix | Delete
for protocol in npn_protocols:
[372] Fix | Delete
b = protocol.encode('ascii')
[373] Fix | Delete
if len(b) == 0 or len(b) > 255:
[374] Fix | Delete
raise SSLError('NPN protocols must be 1 to 255 in length')
[375] Fix | Delete
protos.append(len(b))
[376] Fix | Delete
protos.extend(b)
[377] Fix | Delete
[378] Fix | Delete
self._set_npn_protocols(protos)
[379] Fix | Delete
[380] Fix | Delete
def set_alpn_protocols(self, alpn_protocols):
[381] Fix | Delete
protos = bytearray()
[382] Fix | Delete
for protocol in alpn_protocols:
[383] Fix | Delete
b = protocol.encode('ascii')
[384] Fix | Delete
if len(b) == 0 or len(b) > 255:
[385] Fix | Delete
raise SSLError('ALPN protocols must be 1 to 255 in length')
[386] Fix | Delete
protos.append(len(b))
[387] Fix | Delete
protos.extend(b)
[388] Fix | Delete
[389] Fix | Delete
self._set_alpn_protocols(protos)
[390] Fix | Delete
[391] Fix | Delete
def _load_windows_store_certs(self, storename, purpose):
[392] Fix | Delete
certs = bytearray()
[393] Fix | Delete
try:
[394] Fix | Delete
for cert, encoding, trust in enum_certificates(storename):
[395] Fix | Delete
# CA certs are never PKCS#7 encoded
[396] Fix | Delete
if encoding == "x509_asn":
[397] Fix | Delete
if trust is True or purpose.oid in trust:
[398] Fix | Delete
certs.extend(cert)
[399] Fix | Delete
except OSError:
[400] Fix | Delete
warnings.warn("unable to enumerate Windows certificate store")
[401] Fix | Delete
if certs:
[402] Fix | Delete
self.load_verify_locations(cadata=certs)
[403] Fix | Delete
return certs
[404] Fix | Delete
[405] Fix | Delete
def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
[406] Fix | Delete
if not isinstance(purpose, _ASN1Object):
[407] Fix | Delete
raise TypeError(purpose)
[408] Fix | Delete
if sys.platform == "win32":
[409] Fix | Delete
for storename in self._windows_cert_stores:
[410] Fix | Delete
self._load_windows_store_certs(storename, purpose)
[411] Fix | Delete
self.set_default_verify_paths()
[412] Fix | Delete
[413] Fix | Delete
[414] Fix | Delete
def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None,
[415] Fix | Delete
capath=None, cadata=None):
[416] Fix | Delete
"""Create a SSLContext object with default settings.
[417] Fix | Delete
[418] Fix | Delete
NOTE: The protocol and settings may change anytime without prior
[419] Fix | Delete
deprecation. The values represent a fair balance between maximum
[420] Fix | Delete
compatibility and security.
[421] Fix | Delete
"""
[422] Fix | Delete
if not isinstance(purpose, _ASN1Object):
[423] Fix | Delete
raise TypeError(purpose)
[424] Fix | Delete
[425] Fix | Delete
# SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
[426] Fix | Delete
# OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
[427] Fix | Delete
# by default.
[428] Fix | Delete
context = SSLContext(PROTOCOL_TLS)
[429] Fix | Delete
[430] Fix | Delete
if purpose == Purpose.SERVER_AUTH:
[431] Fix | Delete
# verify certs and host name in client mode
[432] Fix | Delete
context.verify_mode = CERT_REQUIRED
[433] Fix | Delete
context.check_hostname = True
[434] Fix | Delete
elif purpose == Purpose.CLIENT_AUTH:
[435] Fix | Delete
context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
[436] Fix | Delete
[437] Fix | Delete
if cafile or capath or cadata:
[438] Fix | Delete
context.load_verify_locations(cafile, capath, cadata)
[439] Fix | Delete
elif context.verify_mode != CERT_NONE:
[440] Fix | Delete
# no explicit cafile, capath or cadata but the verify mode is
[441] Fix | Delete
# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
[442] Fix | Delete
# root CA certificates for the given purpose. This may fail silently.
[443] Fix | Delete
context.load_default_certs(purpose)
[444] Fix | Delete
return context
[445] Fix | Delete
[446] Fix | Delete
def _create_unverified_context(protocol=PROTOCOL_TLS, cert_reqs=None,
[447] Fix | Delete
check_hostname=False, purpose=Purpose.SERVER_AUTH,
[448] Fix | Delete
certfile=None, keyfile=None,
[449] Fix | Delete
cafile=None, capath=None, cadata=None):
[450] Fix | Delete
"""Create a SSLContext object for Python stdlib modules
[451] Fix | Delete
[452] Fix | Delete
All Python stdlib modules shall use this function to create SSLContext
[453] Fix | Delete
objects in order to keep common settings in one place. The configuration
[454] Fix | Delete
is less restrict than create_default_context()'s to increase backward
[455] Fix | Delete
compatibility.
[456] Fix | Delete
"""
[457] Fix | Delete
if not isinstance(purpose, _ASN1Object):
[458] Fix | Delete
raise TypeError(purpose)
[459] Fix | Delete
[460] Fix | Delete
# SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
[461] Fix | Delete
# OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
[462] Fix | Delete
# by default.
[463] Fix | Delete
context = SSLContext(protocol)
[464] Fix | Delete
[465] Fix | Delete
if cert_reqs is not None:
[466] Fix | Delete
context.verify_mode = cert_reqs
[467] Fix | Delete
context.check_hostname = check_hostname
[468] Fix | Delete
[469] Fix | Delete
if keyfile and not certfile:
[470] Fix | Delete
raise ValueError("certfile must be specified")
[471] Fix | Delete
if certfile or keyfile:
[472] Fix | Delete
context.load_cert_chain(certfile, keyfile)
[473] Fix | Delete
[474] Fix | Delete
# load CA root certs
[475] Fix | Delete
if cafile or capath or cadata:
[476] Fix | Delete
context.load_verify_locations(cafile, capath, cadata)
[477] Fix | Delete
elif context.verify_mode != CERT_NONE:
[478] Fix | Delete
# no explicit cafile, capath or cadata but the verify mode is
[479] Fix | Delete
# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
[480] Fix | Delete
# root CA certificates for the given purpose. This may fail silently.
[481] Fix | Delete
context.load_default_certs(purpose)
[482] Fix | Delete
[483] Fix | Delete
return context
[484] Fix | Delete
[485] Fix | Delete
# Backwards compatibility alias, even though it's not a public name.
[486] Fix | Delete
_create_stdlib_context = _create_unverified_context
[487] Fix | Delete
[488] Fix | Delete
# PEP 493: Verify HTTPS by default, but allow envvar to override that
[489] Fix | Delete
_https_verify_envvar = 'PYTHONHTTPSVERIFY'
[490] Fix | Delete
[491] Fix | Delete
def _get_https_context_factory():
[492] Fix | Delete
if not sys.flags.ignore_environment:
[493] Fix | Delete
config_setting = os.environ.get(_https_verify_envvar)
[494] Fix | Delete
if config_setting == '0':
[495] Fix | Delete
return _create_unverified_context
[496] Fix | Delete
return create_default_context
[497] Fix | Delete
[498] Fix | Delete
_create_default_https_context = _get_https_context_factory()
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function