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