ssl.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. # Wrapper module for _ssl, providing some additional facilities
  2. # implemented in Python. Written by Bill Janssen.
  3. """This module provides some more Pythonic support for SSL.
  4. Object types:
  5. SSLSocket -- subtype of socket.socket which does SSL over the socket
  6. Exceptions:
  7. SSLError -- exception raised for I/O errors
  8. Functions:
  9. cert_time_to_seconds -- convert time string used for certificate
  10. notBefore and notAfter functions to integer
  11. seconds past the Epoch (the time values
  12. returned from time.time())
  13. get_server_certificate (addr, ssl_version, ca_certs, timeout) -- Retrieve the
  14. certificate from the server at the specified
  15. address and return it as a PEM-encoded string
  16. Integer constants:
  17. SSL_ERROR_ZERO_RETURN
  18. SSL_ERROR_WANT_READ
  19. SSL_ERROR_WANT_WRITE
  20. SSL_ERROR_WANT_X509_LOOKUP
  21. SSL_ERROR_SYSCALL
  22. SSL_ERROR_SSL
  23. SSL_ERROR_WANT_CONNECT
  24. SSL_ERROR_EOF
  25. SSL_ERROR_INVALID_ERROR_CODE
  26. The following group define certificate requirements that one side is
  27. allowing/requiring from the other side:
  28. CERT_NONE - no certificates from the other side are required (or will
  29. be looked at if provided)
  30. CERT_OPTIONAL - certificates are not required, but if provided will be
  31. validated, and if validation fails, the connection will
  32. also fail
  33. CERT_REQUIRED - certificates are required, and will be validated, and
  34. if validation fails, the connection will also fail
  35. The following constants identify various SSL protocol variants:
  36. PROTOCOL_SSLv2
  37. PROTOCOL_SSLv3
  38. PROTOCOL_SSLv23
  39. PROTOCOL_TLS
  40. PROTOCOL_TLS_CLIENT
  41. PROTOCOL_TLS_SERVER
  42. PROTOCOL_TLSv1
  43. PROTOCOL_TLSv1_1
  44. PROTOCOL_TLSv1_2
  45. The following constants identify various SSL alert message descriptions as per
  46. http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
  47. ALERT_DESCRIPTION_CLOSE_NOTIFY
  48. ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
  49. ALERT_DESCRIPTION_BAD_RECORD_MAC
  50. ALERT_DESCRIPTION_RECORD_OVERFLOW
  51. ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
  52. ALERT_DESCRIPTION_HANDSHAKE_FAILURE
  53. ALERT_DESCRIPTION_BAD_CERTIFICATE
  54. ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
  55. ALERT_DESCRIPTION_CERTIFICATE_REVOKED
  56. ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
  57. ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
  58. ALERT_DESCRIPTION_ILLEGAL_PARAMETER
  59. ALERT_DESCRIPTION_UNKNOWN_CA
  60. ALERT_DESCRIPTION_ACCESS_DENIED
  61. ALERT_DESCRIPTION_DECODE_ERROR
  62. ALERT_DESCRIPTION_DECRYPT_ERROR
  63. ALERT_DESCRIPTION_PROTOCOL_VERSION
  64. ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
  65. ALERT_DESCRIPTION_INTERNAL_ERROR
  66. ALERT_DESCRIPTION_USER_CANCELLED
  67. ALERT_DESCRIPTION_NO_RENEGOTIATION
  68. ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
  69. ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
  70. ALERT_DESCRIPTION_UNRECOGNIZED_NAME
  71. ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
  72. ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
  73. ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
  74. """
  75. import sys
  76. import os
  77. from collections import namedtuple
  78. from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
  79. from enum import _simple_enum
  80. import _ssl # if we can't import it, let the error propagate
  81. from _ssl import OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_INFO, OPENSSL_VERSION
  82. from _ssl import _SSLContext, MemoryBIO, SSLSession
  83. from _ssl import (
  84. SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
  85. SSLSyscallError, SSLEOFError, SSLCertVerificationError
  86. )
  87. from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj
  88. from _ssl import RAND_status, RAND_add, RAND_bytes
  89. try:
  90. from _ssl import RAND_egd
  91. except ImportError:
  92. # LibreSSL does not provide RAND_egd
  93. pass
  94. from _ssl import (
  95. HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_SSLv2, HAS_SSLv3, HAS_TLSv1,
  96. HAS_TLSv1_1, HAS_TLSv1_2, HAS_TLSv1_3
  97. )
  98. from _ssl import _DEFAULT_CIPHERS, _OPENSSL_API_VERSION
  99. _IntEnum._convert_(
  100. '_SSLMethod', __name__,
  101. lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
  102. source=_ssl)
  103. _IntFlag._convert_(
  104. 'Options', __name__,
  105. lambda name: name.startswith('OP_'),
  106. source=_ssl)
  107. _IntEnum._convert_(
  108. 'AlertDescription', __name__,
  109. lambda name: name.startswith('ALERT_DESCRIPTION_'),
  110. source=_ssl)
  111. _IntEnum._convert_(
  112. 'SSLErrorNumber', __name__,
  113. lambda name: name.startswith('SSL_ERROR_'),
  114. source=_ssl)
  115. _IntFlag._convert_(
  116. 'VerifyFlags', __name__,
  117. lambda name: name.startswith('VERIFY_'),
  118. source=_ssl)
  119. _IntEnum._convert_(
  120. 'VerifyMode', __name__,
  121. lambda name: name.startswith('CERT_'),
  122. source=_ssl)
  123. PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
  124. _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
  125. _SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None)
  126. @_simple_enum(_IntEnum)
  127. class TLSVersion:
  128. MINIMUM_SUPPORTED = _ssl.PROTO_MINIMUM_SUPPORTED
  129. SSLv3 = _ssl.PROTO_SSLv3
  130. TLSv1 = _ssl.PROTO_TLSv1
  131. TLSv1_1 = _ssl.PROTO_TLSv1_1
  132. TLSv1_2 = _ssl.PROTO_TLSv1_2
  133. TLSv1_3 = _ssl.PROTO_TLSv1_3
  134. MAXIMUM_SUPPORTED = _ssl.PROTO_MAXIMUM_SUPPORTED
  135. @_simple_enum(_IntEnum)
  136. class _TLSContentType:
  137. """Content types (record layer)
  138. See RFC 8446, section B.1
  139. """
  140. CHANGE_CIPHER_SPEC = 20
  141. ALERT = 21
  142. HANDSHAKE = 22
  143. APPLICATION_DATA = 23
  144. # pseudo content types
  145. HEADER = 0x100
  146. INNER_CONTENT_TYPE = 0x101
  147. @_simple_enum(_IntEnum)
  148. class _TLSAlertType:
  149. """Alert types for TLSContentType.ALERT messages
  150. See RFC 8466, section B.2
  151. """
  152. CLOSE_NOTIFY = 0
  153. UNEXPECTED_MESSAGE = 10
  154. BAD_RECORD_MAC = 20
  155. DECRYPTION_FAILED = 21
  156. RECORD_OVERFLOW = 22
  157. DECOMPRESSION_FAILURE = 30
  158. HANDSHAKE_FAILURE = 40
  159. NO_CERTIFICATE = 41
  160. BAD_CERTIFICATE = 42
  161. UNSUPPORTED_CERTIFICATE = 43
  162. CERTIFICATE_REVOKED = 44
  163. CERTIFICATE_EXPIRED = 45
  164. CERTIFICATE_UNKNOWN = 46
  165. ILLEGAL_PARAMETER = 47
  166. UNKNOWN_CA = 48
  167. ACCESS_DENIED = 49
  168. DECODE_ERROR = 50
  169. DECRYPT_ERROR = 51
  170. EXPORT_RESTRICTION = 60
  171. PROTOCOL_VERSION = 70
  172. INSUFFICIENT_SECURITY = 71
  173. INTERNAL_ERROR = 80
  174. INAPPROPRIATE_FALLBACK = 86
  175. USER_CANCELED = 90
  176. NO_RENEGOTIATION = 100
  177. MISSING_EXTENSION = 109
  178. UNSUPPORTED_EXTENSION = 110
  179. CERTIFICATE_UNOBTAINABLE = 111
  180. UNRECOGNIZED_NAME = 112
  181. BAD_CERTIFICATE_STATUS_RESPONSE = 113
  182. BAD_CERTIFICATE_HASH_VALUE = 114
  183. UNKNOWN_PSK_IDENTITY = 115
  184. CERTIFICATE_REQUIRED = 116
  185. NO_APPLICATION_PROTOCOL = 120
  186. @_simple_enum(_IntEnum)
  187. class _TLSMessageType:
  188. """Message types (handshake protocol)
  189. See RFC 8446, section B.3
  190. """
  191. HELLO_REQUEST = 0
  192. CLIENT_HELLO = 1
  193. SERVER_HELLO = 2
  194. HELLO_VERIFY_REQUEST = 3
  195. NEWSESSION_TICKET = 4
  196. END_OF_EARLY_DATA = 5
  197. HELLO_RETRY_REQUEST = 6
  198. ENCRYPTED_EXTENSIONS = 8
  199. CERTIFICATE = 11
  200. SERVER_KEY_EXCHANGE = 12
  201. CERTIFICATE_REQUEST = 13
  202. SERVER_DONE = 14
  203. CERTIFICATE_VERIFY = 15
  204. CLIENT_KEY_EXCHANGE = 16
  205. FINISHED = 20
  206. CERTIFICATE_URL = 21
  207. CERTIFICATE_STATUS = 22
  208. SUPPLEMENTAL_DATA = 23
  209. KEY_UPDATE = 24
  210. NEXT_PROTO = 67
  211. MESSAGE_HASH = 254
  212. CHANGE_CIPHER_SPEC = 0x0101
  213. if sys.platform == "win32":
  214. from _ssl import enum_certificates, enum_crls
  215. from socket import socket, SOCK_STREAM, create_connection
  216. from socket import SOL_SOCKET, SO_TYPE, _GLOBAL_DEFAULT_TIMEOUT
  217. import socket as _socket
  218. import base64 # for DER-to-PEM translation
  219. import errno
  220. import warnings
  221. socket_error = OSError # keep that public name in module namespace
  222. CHANNEL_BINDING_TYPES = ['tls-unique']
  223. HAS_NEVER_CHECK_COMMON_NAME = hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT')
  224. _RESTRICTED_SERVER_CIPHERS = _DEFAULT_CIPHERS
  225. CertificateError = SSLCertVerificationError
  226. def _dnsname_match(dn, hostname):
  227. """Matching according to RFC 6125, section 6.4.3
  228. - Hostnames are compared lower-case.
  229. - For IDNA, both dn and hostname must be encoded as IDN A-label (ACE).
  230. - Partial wildcards like 'www*.example.org', multiple wildcards, sole
  231. wildcard or wildcards in labels other then the left-most label are not
  232. supported and a CertificateError is raised.
  233. - A wildcard must match at least one character.
  234. """
  235. if not dn:
  236. return False
  237. wildcards = dn.count('*')
  238. # speed up common case w/o wildcards
  239. if not wildcards:
  240. return dn.lower() == hostname.lower()
  241. if wildcards > 1:
  242. raise CertificateError(
  243. "too many wildcards in certificate DNS name: {!r}.".format(dn))
  244. dn_leftmost, sep, dn_remainder = dn.partition('.')
  245. if '*' in dn_remainder:
  246. # Only match wildcard in leftmost segment.
  247. raise CertificateError(
  248. "wildcard can only be present in the leftmost label: "
  249. "{!r}.".format(dn))
  250. if not sep:
  251. # no right side
  252. raise CertificateError(
  253. "sole wildcard without additional labels are not support: "
  254. "{!r}.".format(dn))
  255. if dn_leftmost != '*':
  256. # no partial wildcard matching
  257. raise CertificateError(
  258. "partial wildcards in leftmost label are not supported: "
  259. "{!r}.".format(dn))
  260. hostname_leftmost, sep, hostname_remainder = hostname.partition('.')
  261. if not hostname_leftmost or not sep:
  262. # wildcard must match at least one char
  263. return False
  264. return dn_remainder.lower() == hostname_remainder.lower()
  265. def _inet_paton(ipname):
  266. """Try to convert an IP address to packed binary form
  267. Supports IPv4 addresses on all platforms and IPv6 on platforms with IPv6
  268. support.
  269. """
  270. # inet_aton() also accepts strings like '1', '127.1', some also trailing
  271. # data like '127.0.0.1 whatever'.
  272. try:
  273. addr = _socket.inet_aton(ipname)
  274. except OSError:
  275. # not an IPv4 address
  276. pass
  277. else:
  278. if _socket.inet_ntoa(addr) == ipname:
  279. # only accept injective ipnames
  280. return addr
  281. else:
  282. # refuse for short IPv4 notation and additional trailing data
  283. raise ValueError(
  284. "{!r} is not a quad-dotted IPv4 address.".format(ipname)
  285. )
  286. try:
  287. return _socket.inet_pton(_socket.AF_INET6, ipname)
  288. except OSError:
  289. raise ValueError("{!r} is neither an IPv4 nor an IP6 "
  290. "address.".format(ipname))
  291. except AttributeError:
  292. # AF_INET6 not available
  293. pass
  294. raise ValueError("{!r} is not an IPv4 address.".format(ipname))
  295. def _ipaddress_match(cert_ipaddress, host_ip):
  296. """Exact matching of IP addresses.
  297. RFC 6125 explicitly doesn't define an algorithm for this
  298. (section 1.7.2 - "Out of Scope").
  299. """
  300. # OpenSSL may add a trailing newline to a subjectAltName's IP address,
  301. # commonly with IPv6 addresses. Strip off trailing \n.
  302. ip = _inet_paton(cert_ipaddress.rstrip())
  303. return ip == host_ip
  304. DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
  305. "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
  306. "openssl_capath")
  307. def get_default_verify_paths():
  308. """Return paths to default cafile and capath.
  309. """
  310. parts = _ssl.get_default_verify_paths()
  311. # environment vars shadow paths
  312. cafile = os.environ.get(parts[0], parts[1])
  313. capath = os.environ.get(parts[2], parts[3])
  314. return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
  315. capath if os.path.isdir(capath) else None,
  316. *parts)
  317. class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
  318. """ASN.1 object identifier lookup
  319. """
  320. __slots__ = ()
  321. def __new__(cls, oid):
  322. return super().__new__(cls, *_txt2obj(oid, name=False))
  323. @classmethod
  324. def fromnid(cls, nid):
  325. """Create _ASN1Object from OpenSSL numeric ID
  326. """
  327. return super().__new__(cls, *_nid2obj(nid))
  328. @classmethod
  329. def fromname(cls, name):
  330. """Create _ASN1Object from short name, long name or OID
  331. """
  332. return super().__new__(cls, *_txt2obj(name, name=True))
  333. class Purpose(_ASN1Object, _Enum):
  334. """SSLContext purpose flags with X509v3 Extended Key Usage objects
  335. """
  336. SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
  337. CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
  338. _builtin_cadata = None
  339. def builtin_cadata():
  340. global _builtin_cadata
  341. if _builtin_cadata is None:
  342. import __res
  343. data = __res.find(b'/builtin/cacert')
  344. # load_verify_locations expects PEM cadata to be an ASCII-only unicode
  345. # object, so we discard unicode in comments.
  346. _builtin_cadata = data.decode('ASCII', errors='ignore')
  347. return _builtin_cadata
  348. class SSLContext(_SSLContext):
  349. """An SSLContext holds various SSL-related configuration options and
  350. data, such as certificates and possibly a private key."""
  351. _windows_cert_stores = ("CA", "ROOT")
  352. sslsocket_class = None # SSLSocket is assigned later.
  353. sslobject_class = None # SSLObject is assigned later.
  354. def __new__(cls, protocol=None, *args, **kwargs):
  355. if protocol is None:
  356. warnings.warn(
  357. "ssl.SSLContext() without protocol argument is deprecated.",
  358. category=DeprecationWarning,
  359. stacklevel=2
  360. )
  361. protocol = PROTOCOL_TLS
  362. self = _SSLContext.__new__(cls, protocol)
  363. return self
  364. def _encode_hostname(self, hostname):
  365. if hostname is None:
  366. return None
  367. elif isinstance(hostname, str):
  368. return hostname.encode('idna').decode('ascii')
  369. else:
  370. return hostname.decode('ascii')
  371. def wrap_socket(self, sock, server_side=False,
  372. do_handshake_on_connect=True,
  373. suppress_ragged_eofs=True,
  374. server_hostname=None, session=None):
  375. # SSLSocket class handles server_hostname encoding before it calls
  376. # ctx._wrap_socket()
  377. return self.sslsocket_class._create(
  378. sock=sock,
  379. server_side=server_side,
  380. do_handshake_on_connect=do_handshake_on_connect,
  381. suppress_ragged_eofs=suppress_ragged_eofs,
  382. server_hostname=server_hostname,
  383. context=self,
  384. session=session
  385. )
  386. def wrap_bio(self, incoming, outgoing, server_side=False,
  387. server_hostname=None, session=None):
  388. # Need to encode server_hostname here because _wrap_bio() can only
  389. # handle ASCII str.
  390. return self.sslobject_class._create(
  391. incoming, outgoing, server_side=server_side,
  392. server_hostname=self._encode_hostname(server_hostname),
  393. session=session, context=self,
  394. )
  395. def set_npn_protocols(self, npn_protocols):
  396. warnings.warn(
  397. "ssl NPN is deprecated, use ALPN instead",
  398. DeprecationWarning,
  399. stacklevel=2
  400. )
  401. protos = bytearray()
  402. for protocol in npn_protocols:
  403. b = bytes(protocol, 'ascii')
  404. if len(b) == 0 or len(b) > 255:
  405. raise SSLError('NPN protocols must be 1 to 255 in length')
  406. protos.append(len(b))
  407. protos.extend(b)
  408. self._set_npn_protocols(protos)
  409. def set_servername_callback(self, server_name_callback):
  410. if server_name_callback is None:
  411. self.sni_callback = None
  412. else:
  413. if not callable(server_name_callback):
  414. raise TypeError("not a callable object")
  415. def shim_cb(sslobj, servername, sslctx):
  416. servername = self._encode_hostname(servername)
  417. return server_name_callback(sslobj, servername, sslctx)
  418. self.sni_callback = shim_cb
  419. def set_alpn_protocols(self, alpn_protocols):
  420. protos = bytearray()
  421. for protocol in alpn_protocols:
  422. b = bytes(protocol, 'ascii')
  423. if len(b) == 0 or len(b) > 255:
  424. raise SSLError('ALPN protocols must be 1 to 255 in length')
  425. protos.append(len(b))
  426. protos.extend(b)
  427. self._set_alpn_protocols(protos)
  428. def _load_windows_store_certs(self, storename, purpose):
  429. certs = bytearray()
  430. try:
  431. for cert, encoding, trust in enum_certificates(storename):
  432. # CA certs are never PKCS#7 encoded
  433. if encoding == "x509_asn":
  434. if trust is True or purpose.oid in trust:
  435. certs.extend(cert)
  436. except PermissionError:
  437. warnings.warn("unable to enumerate Windows certificate store")
  438. if certs:
  439. self.load_verify_locations(cadata=certs)
  440. return certs
  441. def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
  442. if not isinstance(purpose, _ASN1Object):
  443. raise TypeError(purpose)
  444. self.load_verify_locations(cadata=builtin_cadata())
  445. if sys.platform == "win32":
  446. for storename in self._windows_cert_stores:
  447. self._load_windows_store_certs(storename, purpose)
  448. self.set_default_verify_paths()
  449. if hasattr(_SSLContext, 'minimum_version'):
  450. @property
  451. def minimum_version(self):
  452. return TLSVersion(super().minimum_version)
  453. @minimum_version.setter
  454. def minimum_version(self, value):
  455. if value == TLSVersion.SSLv3:
  456. self.options &= ~Options.OP_NO_SSLv3
  457. super(SSLContext, SSLContext).minimum_version.__set__(self, value)
  458. @property
  459. def maximum_version(self):
  460. return TLSVersion(super().maximum_version)
  461. @maximum_version.setter
  462. def maximum_version(self, value):
  463. super(SSLContext, SSLContext).maximum_version.__set__(self, value)
  464. @property
  465. def options(self):
  466. return Options(super().options)
  467. @options.setter
  468. def options(self, value):
  469. super(SSLContext, SSLContext).options.__set__(self, value)
  470. if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
  471. @property
  472. def hostname_checks_common_name(self):
  473. ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  474. return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  475. @hostname_checks_common_name.setter
  476. def hostname_checks_common_name(self, value):
  477. if value:
  478. self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  479. else:
  480. self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  481. else:
  482. @property
  483. def hostname_checks_common_name(self):
  484. return True
  485. @property
  486. def _msg_callback(self):
  487. """TLS message callback
  488. The message callback provides a debugging hook to analyze TLS
  489. connections. The callback is called for any TLS protocol message
  490. (header, handshake, alert, and more), but not for application data.
  491. Due to technical limitations, the callback can't be used to filter
  492. traffic or to abort a connection. Any exception raised in the
  493. callback is delayed until the handshake, read, or write operation
  494. has been performed.
  495. def msg_cb(conn, direction, version, content_type, msg_type, data):
  496. pass
  497. conn
  498. :class:`SSLSocket` or :class:`SSLObject` instance
  499. direction
  500. ``read`` or ``write``
  501. version
  502. :class:`TLSVersion` enum member or int for unknown version. For a
  503. frame header, it's the header version.
  504. content_type
  505. :class:`_TLSContentType` enum member or int for unsupported
  506. content type.
  507. msg_type
  508. Either a :class:`_TLSContentType` enum number for a header
  509. message, a :class:`_TLSAlertType` enum member for an alert
  510. message, a :class:`_TLSMessageType` enum member for other
  511. messages, or int for unsupported message types.
  512. data
  513. Raw, decrypted message content as bytes
  514. """
  515. inner = super()._msg_callback
  516. if inner is not None:
  517. return inner.user_function
  518. else:
  519. return None
  520. @_msg_callback.setter
  521. def _msg_callback(self, callback):
  522. if callback is None:
  523. super(SSLContext, SSLContext)._msg_callback.__set__(self, None)
  524. return
  525. if not hasattr(callback, '__call__'):
  526. raise TypeError(f"{callback} is not callable.")
  527. def inner(conn, direction, version, content_type, msg_type, data):
  528. try:
  529. version = TLSVersion(version)
  530. except ValueError:
  531. pass
  532. try:
  533. content_type = _TLSContentType(content_type)
  534. except ValueError:
  535. pass
  536. if content_type == _TLSContentType.HEADER:
  537. msg_enum = _TLSContentType
  538. elif content_type == _TLSContentType.ALERT:
  539. msg_enum = _TLSAlertType
  540. else:
  541. msg_enum = _TLSMessageType
  542. try:
  543. msg_type = msg_enum(msg_type)
  544. except ValueError:
  545. pass
  546. return callback(conn, direction, version,
  547. content_type, msg_type, data)
  548. inner.user_function = callback
  549. super(SSLContext, SSLContext)._msg_callback.__set__(self, inner)
  550. @property
  551. def protocol(self):
  552. return _SSLMethod(super().protocol)
  553. @property
  554. def verify_flags(self):
  555. return VerifyFlags(super().verify_flags)
  556. @verify_flags.setter
  557. def verify_flags(self, value):
  558. super(SSLContext, SSLContext).verify_flags.__set__(self, value)
  559. @property
  560. def verify_mode(self):
  561. value = super().verify_mode
  562. try:
  563. return VerifyMode(value)
  564. except ValueError:
  565. return value
  566. @verify_mode.setter
  567. def verify_mode(self, value):
  568. super(SSLContext, SSLContext).verify_mode.__set__(self, value)
  569. def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
  570. capath=None, cadata=None):
  571. """Create a SSLContext object with default settings.
  572. NOTE: The protocol and settings may change anytime without prior
  573. deprecation. The values represent a fair balance between maximum
  574. compatibility and security.
  575. """
  576. if not isinstance(purpose, _ASN1Object):
  577. raise TypeError(purpose)
  578. # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
  579. # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
  580. # by default.
  581. if purpose == Purpose.SERVER_AUTH:
  582. # verify certs and host name in client mode
  583. context = SSLContext(PROTOCOL_TLS_CLIENT)
  584. context.verify_mode = CERT_REQUIRED
  585. context.check_hostname = True
  586. elif purpose == Purpose.CLIENT_AUTH:
  587. context = SSLContext(PROTOCOL_TLS_SERVER)
  588. else:
  589. raise ValueError(purpose)
  590. if cafile or capath or cadata:
  591. context.load_verify_locations(cafile, capath, cadata)
  592. elif context.verify_mode != CERT_NONE:
  593. # no explicit cafile, capath or cadata but the verify mode is
  594. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  595. # root CA certificates for the given purpose. This may fail silently.
  596. context.load_default_certs(purpose)
  597. # OpenSSL 1.1.1 keylog file
  598. if hasattr(context, 'keylog_filename'):
  599. keylogfile = os.environ.get('SSLKEYLOGFILE')
  600. if keylogfile and not sys.flags.ignore_environment:
  601. context.keylog_filename = keylogfile
  602. return context
  603. def _create_unverified_context(protocol=None, *, cert_reqs=CERT_NONE,
  604. check_hostname=False, purpose=Purpose.SERVER_AUTH,
  605. certfile=None, keyfile=None,
  606. cafile=None, capath=None, cadata=None):
  607. """Create a SSLContext object for Python stdlib modules
  608. All Python stdlib modules shall use this function to create SSLContext
  609. objects in order to keep common settings in one place. The configuration
  610. is less restrict than create_default_context()'s to increase backward
  611. compatibility.
  612. """
  613. if not isinstance(purpose, _ASN1Object):
  614. raise TypeError(purpose)
  615. # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
  616. # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
  617. # by default.
  618. if purpose == Purpose.SERVER_AUTH:
  619. # verify certs and host name in client mode
  620. if protocol is None:
  621. protocol = PROTOCOL_TLS_CLIENT
  622. elif purpose == Purpose.CLIENT_AUTH:
  623. if protocol is None:
  624. protocol = PROTOCOL_TLS_SERVER
  625. else:
  626. raise ValueError(purpose)
  627. context = SSLContext(protocol)
  628. context.check_hostname = check_hostname
  629. if cert_reqs is not None:
  630. context.verify_mode = cert_reqs
  631. if check_hostname:
  632. context.check_hostname = True
  633. if keyfile and not certfile:
  634. raise ValueError("certfile must be specified")
  635. if certfile or keyfile:
  636. context.load_cert_chain(certfile, keyfile)
  637. # load CA root certs
  638. if cafile or capath or cadata:
  639. context.load_verify_locations(cafile, capath, cadata)
  640. elif context.verify_mode != CERT_NONE:
  641. # no explicit cafile, capath or cadata but the verify mode is
  642. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  643. # root CA certificates for the given purpose. This may fail silently.
  644. context.load_default_certs(purpose)
  645. # OpenSSL 1.1.1 keylog file
  646. if hasattr(context, 'keylog_filename'):
  647. keylogfile = os.environ.get('SSLKEYLOGFILE')
  648. if keylogfile and not sys.flags.ignore_environment:
  649. context.keylog_filename = keylogfile
  650. return context
  651. # Used by http.client if no context is explicitly passed.
  652. _create_default_https_context = create_default_context
  653. # Backwards compatibility alias, even though it's not a public name.
  654. _create_stdlib_context = _create_unverified_context
  655. class SSLObject:
  656. """This class implements an interface on top of a low-level SSL object as
  657. implemented by OpenSSL. This object captures the state of an SSL connection
  658. but does not provide any network IO itself. IO needs to be performed
  659. through separate "BIO" objects which are OpenSSL's IO abstraction layer.
  660. This class does not have a public constructor. Instances are returned by
  661. ``SSLContext.wrap_bio``. This class is typically used by framework authors
  662. that want to implement asynchronous IO for SSL through memory buffers.
  663. When compared to ``SSLSocket``, this object lacks the following features:
  664. * Any form of network IO, including methods such as ``recv`` and ``send``.
  665. * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
  666. """
  667. def __init__(self, *args, **kwargs):
  668. raise TypeError(
  669. f"{self.__class__.__name__} does not have a public "
  670. f"constructor. Instances are returned by SSLContext.wrap_bio()."
  671. )
  672. @classmethod
  673. def _create(cls, incoming, outgoing, server_side=False,
  674. server_hostname=None, session=None, context=None):
  675. self = cls.__new__(cls)
  676. sslobj = context._wrap_bio(
  677. incoming, outgoing, server_side=server_side,
  678. server_hostname=server_hostname,
  679. owner=self, session=session
  680. )
  681. self._sslobj = sslobj
  682. return self
  683. @property
  684. def context(self):
  685. """The SSLContext that is currently in use."""
  686. return self._sslobj.context
  687. @context.setter
  688. def context(self, ctx):
  689. self._sslobj.context = ctx
  690. @property
  691. def session(self):
  692. """The SSLSession for client socket."""
  693. return self._sslobj.session
  694. @session.setter
  695. def session(self, session):
  696. self._sslobj.session = session
  697. @property
  698. def session_reused(self):
  699. """Was the client session reused during handshake"""
  700. return self._sslobj.session_reused
  701. @property
  702. def server_side(self):
  703. """Whether this is a server-side socket."""
  704. return self._sslobj.server_side
  705. @property
  706. def server_hostname(self):
  707. """The currently set server hostname (for SNI), or ``None`` if no
  708. server hostname is set."""
  709. return self._sslobj.server_hostname
  710. def read(self, len=1024, buffer=None):
  711. """Read up to 'len' bytes from the SSL object and return them.
  712. If 'buffer' is provided, read into this buffer and return the number of
  713. bytes read.
  714. """
  715. if buffer is not None:
  716. v = self._sslobj.read(len, buffer)
  717. else:
  718. v = self._sslobj.read(len)
  719. return v
  720. def write(self, data):
  721. """Write 'data' to the SSL object and return the number of bytes
  722. written.
  723. The 'data' argument must support the buffer interface.
  724. """
  725. return self._sslobj.write(data)
  726. def getpeercert(self, binary_form=False):
  727. """Returns a formatted version of the data in the certificate provided
  728. by the other end of the SSL channel.
  729. Return None if no certificate was provided, {} if a certificate was
  730. provided, but not validated.
  731. """
  732. return self._sslobj.getpeercert(binary_form)
  733. def selected_npn_protocol(self):
  734. """Return the currently selected NPN protocol as a string, or ``None``
  735. if a next protocol was not negotiated or if NPN is not supported by one
  736. of the peers."""
  737. warnings.warn(
  738. "ssl NPN is deprecated, use ALPN instead",
  739. DeprecationWarning,
  740. stacklevel=2
  741. )
  742. def selected_alpn_protocol(self):
  743. """Return the currently selected ALPN protocol as a string, or ``None``
  744. if a next protocol was not negotiated or if ALPN is not supported by one
  745. of the peers."""
  746. return self._sslobj.selected_alpn_protocol()
  747. def cipher(self):
  748. """Return the currently selected cipher as a 3-tuple ``(name,
  749. ssl_version, secret_bits)``."""
  750. return self._sslobj.cipher()
  751. def shared_ciphers(self):
  752. """Return a list of ciphers shared by the client during the handshake or
  753. None if this is not a valid server connection.
  754. """
  755. return self._sslobj.shared_ciphers()
  756. def compression(self):
  757. """Return the current compression algorithm in use, or ``None`` if
  758. compression was not negotiated or not supported by one of the peers."""
  759. return self._sslobj.compression()
  760. def pending(self):
  761. """Return the number of bytes that can be read immediately."""
  762. return self._sslobj.pending()
  763. def do_handshake(self):
  764. """Start the SSL/TLS handshake."""
  765. self._sslobj.do_handshake()
  766. def unwrap(self):
  767. """Start the SSL shutdown handshake."""
  768. return self._sslobj.shutdown()
  769. def get_channel_binding(self, cb_type="tls-unique"):
  770. """Get channel binding data for current connection. Raise ValueError
  771. if the requested `cb_type` is not supported. Return bytes of the data
  772. or None if the data is not available (e.g. before the handshake)."""
  773. return self._sslobj.get_channel_binding(cb_type)
  774. def version(self):
  775. """Return a string identifying the protocol version used by the
  776. current SSL channel. """
  777. return self._sslobj.version()
  778. def verify_client_post_handshake(self):
  779. return self._sslobj.verify_client_post_handshake()
  780. def _sslcopydoc(func):
  781. """Copy docstring from SSLObject to SSLSocket"""
  782. func.__doc__ = getattr(SSLObject, func.__name__).__doc__
  783. return func
  784. class SSLSocket(socket):
  785. """This class implements a subtype of socket.socket that wraps
  786. the underlying OS socket in an SSL context when necessary, and
  787. provides read and write methods over that channel. """
  788. def __init__(self, *args, **kwargs):
  789. raise TypeError(
  790. f"{self.__class__.__name__} does not have a public "
  791. f"constructor. Instances are returned by "
  792. f"SSLContext.wrap_socket()."
  793. )
  794. @classmethod
  795. def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
  796. suppress_ragged_eofs=True, server_hostname=None,
  797. context=None, session=None):
  798. if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
  799. raise NotImplementedError("only stream sockets are supported")
  800. if server_side:
  801. if server_hostname:
  802. raise ValueError("server_hostname can only be specified "
  803. "in client mode")
  804. if session is not None:
  805. raise ValueError("session can only be specified in "
  806. "client mode")
  807. if context.check_hostname and not server_hostname:
  808. raise ValueError("check_hostname requires server_hostname")
  809. sock_timeout = sock.gettimeout()
  810. kwargs = dict(
  811. family=sock.family, type=sock.type, proto=sock.proto,
  812. fileno=sock.fileno()
  813. )
  814. self = cls.__new__(cls, **kwargs)
  815. super(SSLSocket, self).__init__(**kwargs)
  816. sock.detach()
  817. # Now SSLSocket is responsible for closing the file descriptor.
  818. try:
  819. self._context = context
  820. self._session = session
  821. self._closed = False
  822. self._sslobj = None
  823. self.server_side = server_side
  824. self.server_hostname = context._encode_hostname(server_hostname)
  825. self.do_handshake_on_connect = do_handshake_on_connect
  826. self.suppress_ragged_eofs = suppress_ragged_eofs
  827. # See if we are connected
  828. try:
  829. self.getpeername()
  830. except OSError as e:
  831. if e.errno != errno.ENOTCONN:
  832. raise
  833. connected = False
  834. blocking = self.getblocking()
  835. self.setblocking(False)
  836. try:
  837. # We are not connected so this is not supposed to block, but
  838. # testing revealed otherwise on macOS and Windows so we do
  839. # the non-blocking dance regardless. Our raise when any data
  840. # is found means consuming the data is harmless.
  841. notconn_pre_handshake_data = self.recv(1)
  842. except OSError as e:
  843. # EINVAL occurs for recv(1) on non-connected on unix sockets.
  844. if e.errno not in (errno.ENOTCONN, errno.EINVAL):
  845. raise
  846. notconn_pre_handshake_data = b''
  847. self.setblocking(blocking)
  848. if notconn_pre_handshake_data:
  849. # This prevents pending data sent to the socket before it was
  850. # closed from escaping to the caller who could otherwise
  851. # presume it came through a successful TLS connection.
  852. reason = "Closed before TLS handshake with data in recv buffer."
  853. notconn_pre_handshake_data_error = SSLError(e.errno, reason)
  854. # Add the SSLError attributes that _ssl.c always adds.
  855. notconn_pre_handshake_data_error.reason = reason
  856. notconn_pre_handshake_data_error.library = None
  857. try:
  858. raise notconn_pre_handshake_data_error
  859. finally:
  860. # Explicitly break the reference cycle.
  861. notconn_pre_handshake_data_error = None
  862. else:
  863. connected = True
  864. self.settimeout(sock_timeout) # Must come after setblocking() calls.
  865. self._connected = connected
  866. if connected:
  867. # create the SSL object
  868. self._sslobj = self._context._wrap_socket(
  869. self, server_side, self.server_hostname,
  870. owner=self, session=self._session,
  871. )
  872. if do_handshake_on_connect:
  873. timeout = self.gettimeout()
  874. if timeout == 0.0:
  875. # non-blocking
  876. raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
  877. self.do_handshake()
  878. except:
  879. try:
  880. self.close()
  881. except OSError:
  882. pass
  883. raise
  884. return self
  885. @property
  886. @_sslcopydoc
  887. def context(self):
  888. return self._context
  889. @context.setter
  890. def context(self, ctx):
  891. self._context = ctx
  892. self._sslobj.context = ctx
  893. @property
  894. @_sslcopydoc
  895. def session(self):
  896. if self._sslobj is not None:
  897. return self._sslobj.session
  898. @session.setter
  899. def session(self, session):
  900. self._session = session
  901. if self._sslobj is not None:
  902. self._sslobj.session = session
  903. @property
  904. @_sslcopydoc
  905. def session_reused(self):
  906. if self._sslobj is not None:
  907. return self._sslobj.session_reused
  908. def dup(self):
  909. raise NotImplementedError("Can't dup() %s instances" %
  910. self.__class__.__name__)
  911. def _checkClosed(self, msg=None):
  912. # raise an exception here if you wish to check for spurious closes
  913. pass
  914. def _check_connected(self):
  915. if not self._connected:
  916. # getpeername() will raise ENOTCONN if the socket is really
  917. # not connected; note that we can be connected even without
  918. # _connected being set, e.g. if connect() first returned
  919. # EAGAIN.
  920. self.getpeername()
  921. def read(self, len=1024, buffer=None):
  922. """Read up to LEN bytes and return them.
  923. Return zero-length string on EOF."""
  924. self._checkClosed()
  925. if self._sslobj is None:
  926. raise ValueError("Read on closed or unwrapped SSL socket.")
  927. try:
  928. if buffer is not None:
  929. return self._sslobj.read(len, buffer)
  930. else:
  931. return self._sslobj.read(len)
  932. except SSLError as x:
  933. if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  934. if buffer is not None:
  935. return 0
  936. else:
  937. return b''
  938. else:
  939. raise
  940. def write(self, data):
  941. """Write DATA to the underlying SSL channel. Returns
  942. number of bytes of DATA actually transmitted."""
  943. self._checkClosed()
  944. if self._sslobj is None:
  945. raise ValueError("Write on closed or unwrapped SSL socket.")
  946. return self._sslobj.write(data)
  947. @_sslcopydoc
  948. def getpeercert(self, binary_form=False):
  949. self._checkClosed()
  950. self._check_connected()
  951. return self._sslobj.getpeercert(binary_form)
  952. @_sslcopydoc
  953. def selected_npn_protocol(self):
  954. self._checkClosed()
  955. warnings.warn(
  956. "ssl NPN is deprecated, use ALPN instead",
  957. DeprecationWarning,
  958. stacklevel=2
  959. )
  960. return None
  961. @_sslcopydoc
  962. def selected_alpn_protocol(self):
  963. self._checkClosed()
  964. if self._sslobj is None or not _ssl.HAS_ALPN:
  965. return None
  966. else:
  967. return self._sslobj.selected_alpn_protocol()
  968. @_sslcopydoc
  969. def cipher(self):
  970. self._checkClosed()
  971. if self._sslobj is None:
  972. return None
  973. else:
  974. return self._sslobj.cipher()
  975. @_sslcopydoc
  976. def shared_ciphers(self):
  977. self._checkClosed()
  978. if self._sslobj is None:
  979. return None
  980. else:
  981. return self._sslobj.shared_ciphers()
  982. @_sslcopydoc
  983. def compression(self):
  984. self._checkClosed()
  985. if self._sslobj is None:
  986. return None
  987. else:
  988. return self._sslobj.compression()
  989. def send(self, data, flags=0):
  990. self._checkClosed()
  991. if self._sslobj is not None:
  992. if flags != 0:
  993. raise ValueError(
  994. "non-zero flags not allowed in calls to send() on %s" %
  995. self.__class__)
  996. return self._sslobj.write(data)
  997. else:
  998. return super().send(data, flags)
  999. def sendto(self, data, flags_or_addr, addr=None):
  1000. self._checkClosed()
  1001. if self._sslobj is not None:
  1002. raise ValueError("sendto not allowed on instances of %s" %
  1003. self.__class__)
  1004. elif addr is None:
  1005. return super().sendto(data, flags_or_addr)
  1006. else:
  1007. return super().sendto(data, flags_or_addr, addr)
  1008. def sendmsg(self, *args, **kwargs):
  1009. # Ensure programs don't send data unencrypted if they try to
  1010. # use this method.
  1011. raise NotImplementedError("sendmsg not allowed on instances of %s" %
  1012. self.__class__)
  1013. def sendall(self, data, flags=0):
  1014. self._checkClosed()
  1015. if self._sslobj is not None:
  1016. if flags != 0:
  1017. raise ValueError(
  1018. "non-zero flags not allowed in calls to sendall() on %s" %
  1019. self.__class__)
  1020. count = 0
  1021. with memoryview(data) as view, view.cast("B") as byte_view:
  1022. amount = len(byte_view)
  1023. while count < amount:
  1024. v = self.send(byte_view[count:])
  1025. count += v
  1026. else:
  1027. return super().sendall(data, flags)
  1028. def sendfile(self, file, offset=0, count=None):
  1029. """Send a file, possibly by using os.sendfile() if this is a
  1030. clear-text socket. Return the total number of bytes sent.
  1031. """
  1032. if self._sslobj is not None:
  1033. return self._sendfile_use_send(file, offset, count)
  1034. else:
  1035. # os.sendfile() works with plain sockets only
  1036. return super().sendfile(file, offset, count)
  1037. def recv(self, buflen=1024, flags=0):
  1038. self._checkClosed()
  1039. if self._sslobj is not None:
  1040. if flags != 0:
  1041. raise ValueError(
  1042. "non-zero flags not allowed in calls to recv() on %s" %
  1043. self.__class__)
  1044. return self.read(buflen)
  1045. else:
  1046. return super().recv(buflen, flags)
  1047. def recv_into(self, buffer, nbytes=None, flags=0):
  1048. self._checkClosed()
  1049. if nbytes is None:
  1050. if buffer is not None:
  1051. with memoryview(buffer) as view:
  1052. nbytes = view.nbytes
  1053. if not nbytes:
  1054. nbytes = 1024
  1055. else:
  1056. nbytes = 1024
  1057. if self._sslobj is not None:
  1058. if flags != 0:
  1059. raise ValueError(
  1060. "non-zero flags not allowed in calls to recv_into() on %s" %
  1061. self.__class__)
  1062. return self.read(nbytes, buffer)
  1063. else:
  1064. return super().recv_into(buffer, nbytes, flags)
  1065. def recvfrom(self, buflen=1024, flags=0):
  1066. self._checkClosed()
  1067. if self._sslobj is not None:
  1068. raise ValueError("recvfrom not allowed on instances of %s" %
  1069. self.__class__)
  1070. else:
  1071. return super().recvfrom(buflen, flags)
  1072. def recvfrom_into(self, buffer, nbytes=None, flags=0):
  1073. self._checkClosed()
  1074. if self._sslobj is not None:
  1075. raise ValueError("recvfrom_into not allowed on instances of %s" %
  1076. self.__class__)
  1077. else:
  1078. return super().recvfrom_into(buffer, nbytes, flags)
  1079. def recvmsg(self, *args, **kwargs):
  1080. raise NotImplementedError("recvmsg not allowed on instances of %s" %
  1081. self.__class__)
  1082. def recvmsg_into(self, *args, **kwargs):
  1083. raise NotImplementedError("recvmsg_into not allowed on instances of "
  1084. "%s" % self.__class__)
  1085. @_sslcopydoc
  1086. def pending(self):
  1087. self._checkClosed()
  1088. if self._sslobj is not None:
  1089. return self._sslobj.pending()
  1090. else:
  1091. return 0
  1092. def shutdown(self, how):
  1093. self._checkClosed()
  1094. self._sslobj = None
  1095. super().shutdown(how)
  1096. @_sslcopydoc
  1097. def unwrap(self):
  1098. if self._sslobj:
  1099. s = self._sslobj.shutdown()
  1100. self._sslobj = None
  1101. return s
  1102. else:
  1103. raise ValueError("No SSL wrapper around " + str(self))
  1104. @_sslcopydoc
  1105. def verify_client_post_handshake(self):
  1106. if self._sslobj:
  1107. return self._sslobj.verify_client_post_handshake()
  1108. else:
  1109. raise ValueError("No SSL wrapper around " + str(self))
  1110. def _real_close(self):
  1111. self._sslobj = None
  1112. super()._real_close()
  1113. @_sslcopydoc
  1114. def do_handshake(self, block=False):
  1115. self._check_connected()
  1116. timeout = self.gettimeout()
  1117. try:
  1118. if timeout == 0.0 and block:
  1119. self.settimeout(None)
  1120. self._sslobj.do_handshake()
  1121. finally:
  1122. self.settimeout(timeout)
  1123. def _real_connect(self, addr, connect_ex):
  1124. if self.server_side:
  1125. raise ValueError("can't connect in server-side mode")
  1126. # Here we assume that the socket is client-side, and not
  1127. # connected at the time of the call. We connect it, then wrap it.
  1128. if self._connected or self._sslobj is not None:
  1129. raise ValueError("attempt to connect already-connected SSLSocket!")
  1130. self._sslobj = self.context._wrap_socket(
  1131. self, False, self.server_hostname,
  1132. owner=self, session=self._session
  1133. )
  1134. try:
  1135. if connect_ex:
  1136. rc = super().connect_ex(addr)
  1137. else:
  1138. rc = None
  1139. super().connect(addr)
  1140. if not rc:
  1141. self._connected = True
  1142. if self.do_handshake_on_connect:
  1143. self.do_handshake()
  1144. return rc
  1145. except (OSError, ValueError):
  1146. self._sslobj = None
  1147. raise
  1148. def connect(self, addr):
  1149. """Connects to remote ADDR, and then wraps the connection in
  1150. an SSL channel."""
  1151. self._real_connect(addr, False)
  1152. def connect_ex(self, addr):
  1153. """Connects to remote ADDR, and then wraps the connection in
  1154. an SSL channel."""
  1155. return self._real_connect(addr, True)
  1156. def accept(self):
  1157. """Accepts a new connection from a remote client, and returns
  1158. a tuple containing that new connection wrapped with a server-side
  1159. SSL channel, and the address of the remote client."""
  1160. newsock, addr = super().accept()
  1161. newsock = self.context.wrap_socket(newsock,
  1162. do_handshake_on_connect=self.do_handshake_on_connect,
  1163. suppress_ragged_eofs=self.suppress_ragged_eofs,
  1164. server_side=True)
  1165. return newsock, addr
  1166. @_sslcopydoc
  1167. def get_channel_binding(self, cb_type="tls-unique"):
  1168. if self._sslobj is not None:
  1169. return self._sslobj.get_channel_binding(cb_type)
  1170. else:
  1171. if cb_type not in CHANNEL_BINDING_TYPES:
  1172. raise ValueError(
  1173. "{0} channel binding type not implemented".format(cb_type)
  1174. )
  1175. return None
  1176. @_sslcopydoc
  1177. def version(self):
  1178. if self._sslobj is not None:
  1179. return self._sslobj.version()
  1180. else:
  1181. return None
  1182. # Python does not support forward declaration of types.
  1183. SSLContext.sslsocket_class = SSLSocket
  1184. SSLContext.sslobject_class = SSLObject
  1185. # some utility functions
  1186. def cert_time_to_seconds(cert_time):
  1187. """Return the time in seconds since the Epoch, given the timestring
  1188. representing the "notBefore" or "notAfter" date from a certificate
  1189. in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
  1190. "notBefore" or "notAfter" dates must use UTC (RFC 5280).
  1191. Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  1192. UTC should be specified as GMT (see ASN1_TIME_print())
  1193. """
  1194. from time import strptime
  1195. from calendar import timegm
  1196. months = (
  1197. "Jan","Feb","Mar","Apr","May","Jun",
  1198. "Jul","Aug","Sep","Oct","Nov","Dec"
  1199. )
  1200. time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
  1201. try:
  1202. month_number = months.index(cert_time[:3].title()) + 1
  1203. except ValueError:
  1204. raise ValueError('time data %r does not match '
  1205. 'format "%%b%s"' % (cert_time, time_format))
  1206. else:
  1207. # found valid month
  1208. tt = strptime(cert_time[3:], time_format)
  1209. # return an integer, the previous mktime()-based implementation
  1210. # returned a float (fractional seconds are always zero here).
  1211. return timegm((tt[0], month_number) + tt[2:6])
  1212. PEM_HEADER = "-----BEGIN CERTIFICATE-----"
  1213. PEM_FOOTER = "-----END CERTIFICATE-----"
  1214. def DER_cert_to_PEM_cert(der_cert_bytes):
  1215. """Takes a certificate in binary DER format and returns the
  1216. PEM version of it as a string."""
  1217. f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
  1218. ss = [PEM_HEADER]
  1219. ss += [f[i:i+64] for i in range(0, len(f), 64)]
  1220. ss.append(PEM_FOOTER + '\n')
  1221. return '\n'.join(ss)
  1222. def PEM_cert_to_DER_cert(pem_cert_string):
  1223. """Takes a certificate in ASCII PEM format and returns the
  1224. DER-encoded version of it as a byte sequence"""
  1225. if not pem_cert_string.startswith(PEM_HEADER):
  1226. raise ValueError("Invalid PEM encoding; must start with %s"
  1227. % PEM_HEADER)
  1228. if not pem_cert_string.strip().endswith(PEM_FOOTER):
  1229. raise ValueError("Invalid PEM encoding; must end with %s"
  1230. % PEM_FOOTER)
  1231. d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
  1232. return base64.decodebytes(d.encode('ASCII', 'strict'))
  1233. def get_server_certificate(addr, ssl_version=PROTOCOL_TLS_CLIENT,
  1234. ca_certs=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
  1235. """Retrieve the certificate from the server at the specified address,
  1236. and return it as a PEM-encoded string.
  1237. If 'ca_certs' is specified, validate the server cert against it.
  1238. If 'ssl_version' is specified, use it in the connection attempt.
  1239. If 'timeout' is specified, use it in the connection attempt.
  1240. """
  1241. host, port = addr
  1242. if ca_certs is not None:
  1243. cert_reqs = CERT_REQUIRED
  1244. else:
  1245. cert_reqs = CERT_NONE
  1246. context = _create_stdlib_context(ssl_version,
  1247. cert_reqs=cert_reqs,
  1248. cafile=ca_certs)
  1249. with create_connection(addr, timeout=timeout) as sock:
  1250. with context.wrap_socket(sock, server_hostname=host) as sslsock:
  1251. dercert = sslsock.getpeercert(True)
  1252. return DER_cert_to_PEM_cert(dercert)
  1253. def get_protocol_name(protocol_code):
  1254. return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')