ssl.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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. try:
  430. for cert, encoding, trust in enum_certificates(storename):
  431. # CA certs are never PKCS#7 encoded
  432. if encoding == "x509_asn":
  433. if trust is True or purpose.oid in trust:
  434. try:
  435. self.load_verify_locations(cadata=cert)
  436. except SSLError as exc:
  437. warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}")
  438. except PermissionError:
  439. warnings.warn("unable to enumerate Windows certificate store")
  440. def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
  441. if not isinstance(purpose, _ASN1Object):
  442. raise TypeError(purpose)
  443. self.load_verify_locations(cadata=builtin_cadata())
  444. if sys.platform == "win32":
  445. for storename in self._windows_cert_stores:
  446. self._load_windows_store_certs(storename, purpose)
  447. self.set_default_verify_paths()
  448. if hasattr(_SSLContext, 'minimum_version'):
  449. @property
  450. def minimum_version(self):
  451. return TLSVersion(super().minimum_version)
  452. @minimum_version.setter
  453. def minimum_version(self, value):
  454. if value == TLSVersion.SSLv3:
  455. self.options &= ~Options.OP_NO_SSLv3
  456. super(SSLContext, SSLContext).minimum_version.__set__(self, value)
  457. @property
  458. def maximum_version(self):
  459. return TLSVersion(super().maximum_version)
  460. @maximum_version.setter
  461. def maximum_version(self, value):
  462. super(SSLContext, SSLContext).maximum_version.__set__(self, value)
  463. @property
  464. def options(self):
  465. return Options(super().options)
  466. @options.setter
  467. def options(self, value):
  468. super(SSLContext, SSLContext).options.__set__(self, value)
  469. if hasattr(_ssl, 'HOSTFLAG_NEVER_CHECK_SUBJECT'):
  470. @property
  471. def hostname_checks_common_name(self):
  472. ncs = self._host_flags & _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  473. return ncs != _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  474. @hostname_checks_common_name.setter
  475. def hostname_checks_common_name(self, value):
  476. if value:
  477. self._host_flags &= ~_ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  478. else:
  479. self._host_flags |= _ssl.HOSTFLAG_NEVER_CHECK_SUBJECT
  480. else:
  481. @property
  482. def hostname_checks_common_name(self):
  483. return True
  484. @property
  485. def _msg_callback(self):
  486. """TLS message callback
  487. The message callback provides a debugging hook to analyze TLS
  488. connections. The callback is called for any TLS protocol message
  489. (header, handshake, alert, and more), but not for application data.
  490. Due to technical limitations, the callback can't be used to filter
  491. traffic or to abort a connection. Any exception raised in the
  492. callback is delayed until the handshake, read, or write operation
  493. has been performed.
  494. def msg_cb(conn, direction, version, content_type, msg_type, data):
  495. pass
  496. conn
  497. :class:`SSLSocket` or :class:`SSLObject` instance
  498. direction
  499. ``read`` or ``write``
  500. version
  501. :class:`TLSVersion` enum member or int for unknown version. For a
  502. frame header, it's the header version.
  503. content_type
  504. :class:`_TLSContentType` enum member or int for unsupported
  505. content type.
  506. msg_type
  507. Either a :class:`_TLSContentType` enum number for a header
  508. message, a :class:`_TLSAlertType` enum member for an alert
  509. message, a :class:`_TLSMessageType` enum member for other
  510. messages, or int for unsupported message types.
  511. data
  512. Raw, decrypted message content as bytes
  513. """
  514. inner = super()._msg_callback
  515. if inner is not None:
  516. return inner.user_function
  517. else:
  518. return None
  519. @_msg_callback.setter
  520. def _msg_callback(self, callback):
  521. if callback is None:
  522. super(SSLContext, SSLContext)._msg_callback.__set__(self, None)
  523. return
  524. if not hasattr(callback, '__call__'):
  525. raise TypeError(f"{callback} is not callable.")
  526. def inner(conn, direction, version, content_type, msg_type, data):
  527. try:
  528. version = TLSVersion(version)
  529. except ValueError:
  530. pass
  531. try:
  532. content_type = _TLSContentType(content_type)
  533. except ValueError:
  534. pass
  535. if content_type == _TLSContentType.HEADER:
  536. msg_enum = _TLSContentType
  537. elif content_type == _TLSContentType.ALERT:
  538. msg_enum = _TLSAlertType
  539. else:
  540. msg_enum = _TLSMessageType
  541. try:
  542. msg_type = msg_enum(msg_type)
  543. except ValueError:
  544. pass
  545. return callback(conn, direction, version,
  546. content_type, msg_type, data)
  547. inner.user_function = callback
  548. super(SSLContext, SSLContext)._msg_callback.__set__(self, inner)
  549. @property
  550. def protocol(self):
  551. return _SSLMethod(super().protocol)
  552. @property
  553. def verify_flags(self):
  554. return VerifyFlags(super().verify_flags)
  555. @verify_flags.setter
  556. def verify_flags(self, value):
  557. super(SSLContext, SSLContext).verify_flags.__set__(self, value)
  558. @property
  559. def verify_mode(self):
  560. value = super().verify_mode
  561. try:
  562. return VerifyMode(value)
  563. except ValueError:
  564. return value
  565. @verify_mode.setter
  566. def verify_mode(self, value):
  567. super(SSLContext, SSLContext).verify_mode.__set__(self, value)
  568. def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
  569. capath=None, cadata=None):
  570. """Create a SSLContext object with default settings.
  571. NOTE: The protocol and settings may change anytime without prior
  572. deprecation. The values represent a fair balance between maximum
  573. compatibility and security.
  574. """
  575. if not isinstance(purpose, _ASN1Object):
  576. raise TypeError(purpose)
  577. # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
  578. # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
  579. # by default.
  580. if purpose == Purpose.SERVER_AUTH:
  581. # verify certs and host name in client mode
  582. context = SSLContext(PROTOCOL_TLS_CLIENT)
  583. context.verify_mode = CERT_REQUIRED
  584. context.check_hostname = True
  585. elif purpose == Purpose.CLIENT_AUTH:
  586. context = SSLContext(PROTOCOL_TLS_SERVER)
  587. else:
  588. raise ValueError(purpose)
  589. if cafile or capath or cadata:
  590. context.load_verify_locations(cafile, capath, cadata)
  591. elif context.verify_mode != CERT_NONE:
  592. # no explicit cafile, capath or cadata but the verify mode is
  593. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  594. # root CA certificates for the given purpose. This may fail silently.
  595. context.load_default_certs(purpose)
  596. # OpenSSL 1.1.1 keylog file
  597. if hasattr(context, 'keylog_filename'):
  598. keylogfile = os.environ.get('SSLKEYLOGFILE')
  599. if keylogfile and not sys.flags.ignore_environment:
  600. context.keylog_filename = keylogfile
  601. return context
  602. def _create_unverified_context(protocol=None, *, cert_reqs=CERT_NONE,
  603. check_hostname=False, purpose=Purpose.SERVER_AUTH,
  604. certfile=None, keyfile=None,
  605. cafile=None, capath=None, cadata=None):
  606. """Create a SSLContext object for Python stdlib modules
  607. All Python stdlib modules shall use this function to create SSLContext
  608. objects in order to keep common settings in one place. The configuration
  609. is less restrict than create_default_context()'s to increase backward
  610. compatibility.
  611. """
  612. if not isinstance(purpose, _ASN1Object):
  613. raise TypeError(purpose)
  614. # SSLContext sets OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION,
  615. # OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE and OP_SINGLE_ECDH_USE
  616. # by default.
  617. if purpose == Purpose.SERVER_AUTH:
  618. # verify certs and host name in client mode
  619. if protocol is None:
  620. protocol = PROTOCOL_TLS_CLIENT
  621. elif purpose == Purpose.CLIENT_AUTH:
  622. if protocol is None:
  623. protocol = PROTOCOL_TLS_SERVER
  624. else:
  625. raise ValueError(purpose)
  626. context = SSLContext(protocol)
  627. context.check_hostname = check_hostname
  628. if cert_reqs is not None:
  629. context.verify_mode = cert_reqs
  630. if check_hostname:
  631. context.check_hostname = True
  632. if keyfile and not certfile:
  633. raise ValueError("certfile must be specified")
  634. if certfile or keyfile:
  635. context.load_cert_chain(certfile, keyfile)
  636. # load CA root certs
  637. if cafile or capath or cadata:
  638. context.load_verify_locations(cafile, capath, cadata)
  639. elif context.verify_mode != CERT_NONE:
  640. # no explicit cafile, capath or cadata but the verify mode is
  641. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  642. # root CA certificates for the given purpose. This may fail silently.
  643. context.load_default_certs(purpose)
  644. # OpenSSL 1.1.1 keylog file
  645. if hasattr(context, 'keylog_filename'):
  646. keylogfile = os.environ.get('SSLKEYLOGFILE')
  647. if keylogfile and not sys.flags.ignore_environment:
  648. context.keylog_filename = keylogfile
  649. return context
  650. # Used by http.client if no context is explicitly passed.
  651. _create_default_https_context = create_default_context
  652. # Backwards compatibility alias, even though it's not a public name.
  653. _create_stdlib_context = _create_unverified_context
  654. class SSLObject:
  655. """This class implements an interface on top of a low-level SSL object as
  656. implemented by OpenSSL. This object captures the state of an SSL connection
  657. but does not provide any network IO itself. IO needs to be performed
  658. through separate "BIO" objects which are OpenSSL's IO abstraction layer.
  659. This class does not have a public constructor. Instances are returned by
  660. ``SSLContext.wrap_bio``. This class is typically used by framework authors
  661. that want to implement asynchronous IO for SSL through memory buffers.
  662. When compared to ``SSLSocket``, this object lacks the following features:
  663. * Any form of network IO, including methods such as ``recv`` and ``send``.
  664. * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
  665. """
  666. def __init__(self, *args, **kwargs):
  667. raise TypeError(
  668. f"{self.__class__.__name__} does not have a public "
  669. f"constructor. Instances are returned by SSLContext.wrap_bio()."
  670. )
  671. @classmethod
  672. def _create(cls, incoming, outgoing, server_side=False,
  673. server_hostname=None, session=None, context=None):
  674. self = cls.__new__(cls)
  675. sslobj = context._wrap_bio(
  676. incoming, outgoing, server_side=server_side,
  677. server_hostname=server_hostname,
  678. owner=self, session=session
  679. )
  680. self._sslobj = sslobj
  681. return self
  682. @property
  683. def context(self):
  684. """The SSLContext that is currently in use."""
  685. return self._sslobj.context
  686. @context.setter
  687. def context(self, ctx):
  688. self._sslobj.context = ctx
  689. @property
  690. def session(self):
  691. """The SSLSession for client socket."""
  692. return self._sslobj.session
  693. @session.setter
  694. def session(self, session):
  695. self._sslobj.session = session
  696. @property
  697. def session_reused(self):
  698. """Was the client session reused during handshake"""
  699. return self._sslobj.session_reused
  700. @property
  701. def server_side(self):
  702. """Whether this is a server-side socket."""
  703. return self._sslobj.server_side
  704. @property
  705. def server_hostname(self):
  706. """The currently set server hostname (for SNI), or ``None`` if no
  707. server hostname is set."""
  708. return self._sslobj.server_hostname
  709. def read(self, len=1024, buffer=None):
  710. """Read up to 'len' bytes from the SSL object and return them.
  711. If 'buffer' is provided, read into this buffer and return the number of
  712. bytes read.
  713. """
  714. if buffer is not None:
  715. v = self._sslobj.read(len, buffer)
  716. else:
  717. v = self._sslobj.read(len)
  718. return v
  719. def write(self, data):
  720. """Write 'data' to the SSL object and return the number of bytes
  721. written.
  722. The 'data' argument must support the buffer interface.
  723. """
  724. return self._sslobj.write(data)
  725. def getpeercert(self, binary_form=False):
  726. """Returns a formatted version of the data in the certificate provided
  727. by the other end of the SSL channel.
  728. Return None if no certificate was provided, {} if a certificate was
  729. provided, but not validated.
  730. """
  731. return self._sslobj.getpeercert(binary_form)
  732. def selected_npn_protocol(self):
  733. """Return the currently selected NPN protocol as a string, or ``None``
  734. if a next protocol was not negotiated or if NPN is not supported by one
  735. of the peers."""
  736. warnings.warn(
  737. "ssl NPN is deprecated, use ALPN instead",
  738. DeprecationWarning,
  739. stacklevel=2
  740. )
  741. def selected_alpn_protocol(self):
  742. """Return the currently selected ALPN protocol as a string, or ``None``
  743. if a next protocol was not negotiated or if ALPN is not supported by one
  744. of the peers."""
  745. return self._sslobj.selected_alpn_protocol()
  746. def cipher(self):
  747. """Return the currently selected cipher as a 3-tuple ``(name,
  748. ssl_version, secret_bits)``."""
  749. return self._sslobj.cipher()
  750. def shared_ciphers(self):
  751. """Return a list of ciphers shared by the client during the handshake or
  752. None if this is not a valid server connection.
  753. """
  754. return self._sslobj.shared_ciphers()
  755. def compression(self):
  756. """Return the current compression algorithm in use, or ``None`` if
  757. compression was not negotiated or not supported by one of the peers."""
  758. return self._sslobj.compression()
  759. def pending(self):
  760. """Return the number of bytes that can be read immediately."""
  761. return self._sslobj.pending()
  762. def do_handshake(self):
  763. """Start the SSL/TLS handshake."""
  764. self._sslobj.do_handshake()
  765. def unwrap(self):
  766. """Start the SSL shutdown handshake."""
  767. return self._sslobj.shutdown()
  768. def get_channel_binding(self, cb_type="tls-unique"):
  769. """Get channel binding data for current connection. Raise ValueError
  770. if the requested `cb_type` is not supported. Return bytes of the data
  771. or None if the data is not available (e.g. before the handshake)."""
  772. return self._sslobj.get_channel_binding(cb_type)
  773. def version(self):
  774. """Return a string identifying the protocol version used by the
  775. current SSL channel. """
  776. return self._sslobj.version()
  777. def verify_client_post_handshake(self):
  778. return self._sslobj.verify_client_post_handshake()
  779. def _sslcopydoc(func):
  780. """Copy docstring from SSLObject to SSLSocket"""
  781. func.__doc__ = getattr(SSLObject, func.__name__).__doc__
  782. return func
  783. class SSLSocket(socket):
  784. """This class implements a subtype of socket.socket that wraps
  785. the underlying OS socket in an SSL context when necessary, and
  786. provides read and write methods over that channel. """
  787. def __init__(self, *args, **kwargs):
  788. raise TypeError(
  789. f"{self.__class__.__name__} does not have a public "
  790. f"constructor. Instances are returned by "
  791. f"SSLContext.wrap_socket()."
  792. )
  793. @classmethod
  794. def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
  795. suppress_ragged_eofs=True, server_hostname=None,
  796. context=None, session=None):
  797. if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
  798. raise NotImplementedError("only stream sockets are supported")
  799. if server_side:
  800. if server_hostname:
  801. raise ValueError("server_hostname can only be specified "
  802. "in client mode")
  803. if session is not None:
  804. raise ValueError("session can only be specified in "
  805. "client mode")
  806. if context.check_hostname and not server_hostname:
  807. raise ValueError("check_hostname requires server_hostname")
  808. sock_timeout = sock.gettimeout()
  809. kwargs = dict(
  810. family=sock.family, type=sock.type, proto=sock.proto,
  811. fileno=sock.fileno()
  812. )
  813. self = cls.__new__(cls, **kwargs)
  814. super(SSLSocket, self).__init__(**kwargs)
  815. sock.detach()
  816. # Now SSLSocket is responsible for closing the file descriptor.
  817. try:
  818. self._context = context
  819. self._session = session
  820. self._closed = False
  821. self._sslobj = None
  822. self.server_side = server_side
  823. self.server_hostname = context._encode_hostname(server_hostname)
  824. self.do_handshake_on_connect = do_handshake_on_connect
  825. self.suppress_ragged_eofs = suppress_ragged_eofs
  826. # See if we are connected
  827. try:
  828. self.getpeername()
  829. except OSError as e:
  830. if e.errno != errno.ENOTCONN:
  831. raise
  832. connected = False
  833. blocking = self.getblocking()
  834. self.setblocking(False)
  835. try:
  836. # We are not connected so this is not supposed to block, but
  837. # testing revealed otherwise on macOS and Windows so we do
  838. # the non-blocking dance regardless. Our raise when any data
  839. # is found means consuming the data is harmless.
  840. notconn_pre_handshake_data = self.recv(1)
  841. except OSError as e:
  842. # EINVAL occurs for recv(1) on non-connected on unix sockets.
  843. if e.errno not in (errno.ENOTCONN, errno.EINVAL):
  844. raise
  845. notconn_pre_handshake_data = b''
  846. self.setblocking(blocking)
  847. if notconn_pre_handshake_data:
  848. # This prevents pending data sent to the socket before it was
  849. # closed from escaping to the caller who could otherwise
  850. # presume it came through a successful TLS connection.
  851. reason = "Closed before TLS handshake with data in recv buffer."
  852. notconn_pre_handshake_data_error = SSLError(e.errno, reason)
  853. # Add the SSLError attributes that _ssl.c always adds.
  854. notconn_pre_handshake_data_error.reason = reason
  855. notconn_pre_handshake_data_error.library = None
  856. try:
  857. raise notconn_pre_handshake_data_error
  858. finally:
  859. # Explicitly break the reference cycle.
  860. notconn_pre_handshake_data_error = None
  861. else:
  862. connected = True
  863. self.settimeout(sock_timeout) # Must come after setblocking() calls.
  864. self._connected = connected
  865. if connected:
  866. # create the SSL object
  867. self._sslobj = self._context._wrap_socket(
  868. self, server_side, self.server_hostname,
  869. owner=self, session=self._session,
  870. )
  871. if do_handshake_on_connect:
  872. timeout = self.gettimeout()
  873. if timeout == 0.0:
  874. # non-blocking
  875. raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
  876. self.do_handshake()
  877. except:
  878. try:
  879. self.close()
  880. except OSError:
  881. pass
  882. raise
  883. return self
  884. @property
  885. @_sslcopydoc
  886. def context(self):
  887. return self._context
  888. @context.setter
  889. def context(self, ctx):
  890. self._context = ctx
  891. self._sslobj.context = ctx
  892. @property
  893. @_sslcopydoc
  894. def session(self):
  895. if self._sslobj is not None:
  896. return self._sslobj.session
  897. @session.setter
  898. def session(self, session):
  899. self._session = session
  900. if self._sslobj is not None:
  901. self._sslobj.session = session
  902. @property
  903. @_sslcopydoc
  904. def session_reused(self):
  905. if self._sslobj is not None:
  906. return self._sslobj.session_reused
  907. def dup(self):
  908. raise NotImplementedError("Can't dup() %s instances" %
  909. self.__class__.__name__)
  910. def _checkClosed(self, msg=None):
  911. # raise an exception here if you wish to check for spurious closes
  912. pass
  913. def _check_connected(self):
  914. if not self._connected:
  915. # getpeername() will raise ENOTCONN if the socket is really
  916. # not connected; note that we can be connected even without
  917. # _connected being set, e.g. if connect() first returned
  918. # EAGAIN.
  919. self.getpeername()
  920. def read(self, len=1024, buffer=None):
  921. """Read up to LEN bytes and return them.
  922. Return zero-length string on EOF."""
  923. self._checkClosed()
  924. if self._sslobj is None:
  925. raise ValueError("Read on closed or unwrapped SSL socket.")
  926. try:
  927. if buffer is not None:
  928. return self._sslobj.read(len, buffer)
  929. else:
  930. return self._sslobj.read(len)
  931. except SSLError as x:
  932. if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  933. if buffer is not None:
  934. return 0
  935. else:
  936. return b''
  937. else:
  938. raise
  939. def write(self, data):
  940. """Write DATA to the underlying SSL channel. Returns
  941. number of bytes of DATA actually transmitted."""
  942. self._checkClosed()
  943. if self._sslobj is None:
  944. raise ValueError("Write on closed or unwrapped SSL socket.")
  945. return self._sslobj.write(data)
  946. @_sslcopydoc
  947. def getpeercert(self, binary_form=False):
  948. self._checkClosed()
  949. self._check_connected()
  950. return self._sslobj.getpeercert(binary_form)
  951. @_sslcopydoc
  952. def selected_npn_protocol(self):
  953. self._checkClosed()
  954. warnings.warn(
  955. "ssl NPN is deprecated, use ALPN instead",
  956. DeprecationWarning,
  957. stacklevel=2
  958. )
  959. return None
  960. @_sslcopydoc
  961. def selected_alpn_protocol(self):
  962. self._checkClosed()
  963. if self._sslobj is None or not _ssl.HAS_ALPN:
  964. return None
  965. else:
  966. return self._sslobj.selected_alpn_protocol()
  967. @_sslcopydoc
  968. def cipher(self):
  969. self._checkClosed()
  970. if self._sslobj is None:
  971. return None
  972. else:
  973. return self._sslobj.cipher()
  974. @_sslcopydoc
  975. def shared_ciphers(self):
  976. self._checkClosed()
  977. if self._sslobj is None:
  978. return None
  979. else:
  980. return self._sslobj.shared_ciphers()
  981. @_sslcopydoc
  982. def compression(self):
  983. self._checkClosed()
  984. if self._sslobj is None:
  985. return None
  986. else:
  987. return self._sslobj.compression()
  988. def send(self, data, flags=0):
  989. self._checkClosed()
  990. if self._sslobj is not None:
  991. if flags != 0:
  992. raise ValueError(
  993. "non-zero flags not allowed in calls to send() on %s" %
  994. self.__class__)
  995. return self._sslobj.write(data)
  996. else:
  997. return super().send(data, flags)
  998. def sendto(self, data, flags_or_addr, addr=None):
  999. self._checkClosed()
  1000. if self._sslobj is not None:
  1001. raise ValueError("sendto not allowed on instances of %s" %
  1002. self.__class__)
  1003. elif addr is None:
  1004. return super().sendto(data, flags_or_addr)
  1005. else:
  1006. return super().sendto(data, flags_or_addr, addr)
  1007. def sendmsg(self, *args, **kwargs):
  1008. # Ensure programs don't send data unencrypted if they try to
  1009. # use this method.
  1010. raise NotImplementedError("sendmsg not allowed on instances of %s" %
  1011. self.__class__)
  1012. def sendall(self, data, flags=0):
  1013. self._checkClosed()
  1014. if self._sslobj is not None:
  1015. if flags != 0:
  1016. raise ValueError(
  1017. "non-zero flags not allowed in calls to sendall() on %s" %
  1018. self.__class__)
  1019. count = 0
  1020. with memoryview(data) as view, view.cast("B") as byte_view:
  1021. amount = len(byte_view)
  1022. while count < amount:
  1023. v = self.send(byte_view[count:])
  1024. count += v
  1025. else:
  1026. return super().sendall(data, flags)
  1027. def sendfile(self, file, offset=0, count=None):
  1028. """Send a file, possibly by using os.sendfile() if this is a
  1029. clear-text socket. Return the total number of bytes sent.
  1030. """
  1031. if self._sslobj is not None:
  1032. return self._sendfile_use_send(file, offset, count)
  1033. else:
  1034. # os.sendfile() works with plain sockets only
  1035. return super().sendfile(file, offset, count)
  1036. def recv(self, buflen=1024, flags=0):
  1037. self._checkClosed()
  1038. if self._sslobj is not None:
  1039. if flags != 0:
  1040. raise ValueError(
  1041. "non-zero flags not allowed in calls to recv() on %s" %
  1042. self.__class__)
  1043. return self.read(buflen)
  1044. else:
  1045. return super().recv(buflen, flags)
  1046. def recv_into(self, buffer, nbytes=None, flags=0):
  1047. self._checkClosed()
  1048. if nbytes is None:
  1049. if buffer is not None:
  1050. with memoryview(buffer) as view:
  1051. nbytes = view.nbytes
  1052. if not nbytes:
  1053. nbytes = 1024
  1054. else:
  1055. nbytes = 1024
  1056. if self._sslobj is not None:
  1057. if flags != 0:
  1058. raise ValueError(
  1059. "non-zero flags not allowed in calls to recv_into() on %s" %
  1060. self.__class__)
  1061. return self.read(nbytes, buffer)
  1062. else:
  1063. return super().recv_into(buffer, nbytes, flags)
  1064. def recvfrom(self, buflen=1024, flags=0):
  1065. self._checkClosed()
  1066. if self._sslobj is not None:
  1067. raise ValueError("recvfrom not allowed on instances of %s" %
  1068. self.__class__)
  1069. else:
  1070. return super().recvfrom(buflen, flags)
  1071. def recvfrom_into(self, buffer, nbytes=None, flags=0):
  1072. self._checkClosed()
  1073. if self._sslobj is not None:
  1074. raise ValueError("recvfrom_into not allowed on instances of %s" %
  1075. self.__class__)
  1076. else:
  1077. return super().recvfrom_into(buffer, nbytes, flags)
  1078. def recvmsg(self, *args, **kwargs):
  1079. raise NotImplementedError("recvmsg not allowed on instances of %s" %
  1080. self.__class__)
  1081. def recvmsg_into(self, *args, **kwargs):
  1082. raise NotImplementedError("recvmsg_into not allowed on instances of "
  1083. "%s" % self.__class__)
  1084. @_sslcopydoc
  1085. def pending(self):
  1086. self._checkClosed()
  1087. if self._sslobj is not None:
  1088. return self._sslobj.pending()
  1089. else:
  1090. return 0
  1091. def shutdown(self, how):
  1092. self._checkClosed()
  1093. self._sslobj = None
  1094. super().shutdown(how)
  1095. @_sslcopydoc
  1096. def unwrap(self):
  1097. if self._sslobj:
  1098. s = self._sslobj.shutdown()
  1099. self._sslobj = None
  1100. return s
  1101. else:
  1102. raise ValueError("No SSL wrapper around " + str(self))
  1103. @_sslcopydoc
  1104. def verify_client_post_handshake(self):
  1105. if self._sslobj:
  1106. return self._sslobj.verify_client_post_handshake()
  1107. else:
  1108. raise ValueError("No SSL wrapper around " + str(self))
  1109. def _real_close(self):
  1110. self._sslobj = None
  1111. super()._real_close()
  1112. @_sslcopydoc
  1113. def do_handshake(self, block=False):
  1114. self._check_connected()
  1115. timeout = self.gettimeout()
  1116. try:
  1117. if timeout == 0.0 and block:
  1118. self.settimeout(None)
  1119. self._sslobj.do_handshake()
  1120. finally:
  1121. self.settimeout(timeout)
  1122. def _real_connect(self, addr, connect_ex):
  1123. if self.server_side:
  1124. raise ValueError("can't connect in server-side mode")
  1125. # Here we assume that the socket is client-side, and not
  1126. # connected at the time of the call. We connect it, then wrap it.
  1127. if self._connected or self._sslobj is not None:
  1128. raise ValueError("attempt to connect already-connected SSLSocket!")
  1129. self._sslobj = self.context._wrap_socket(
  1130. self, False, self.server_hostname,
  1131. owner=self, session=self._session
  1132. )
  1133. try:
  1134. if connect_ex:
  1135. rc = super().connect_ex(addr)
  1136. else:
  1137. rc = None
  1138. super().connect(addr)
  1139. if not rc:
  1140. self._connected = True
  1141. if self.do_handshake_on_connect:
  1142. self.do_handshake()
  1143. return rc
  1144. except (OSError, ValueError):
  1145. self._sslobj = None
  1146. raise
  1147. def connect(self, addr):
  1148. """Connects to remote ADDR, and then wraps the connection in
  1149. an SSL channel."""
  1150. self._real_connect(addr, False)
  1151. def connect_ex(self, addr):
  1152. """Connects to remote ADDR, and then wraps the connection in
  1153. an SSL channel."""
  1154. return self._real_connect(addr, True)
  1155. def accept(self):
  1156. """Accepts a new connection from a remote client, and returns
  1157. a tuple containing that new connection wrapped with a server-side
  1158. SSL channel, and the address of the remote client."""
  1159. newsock, addr = super().accept()
  1160. newsock = self.context.wrap_socket(newsock,
  1161. do_handshake_on_connect=self.do_handshake_on_connect,
  1162. suppress_ragged_eofs=self.suppress_ragged_eofs,
  1163. server_side=True)
  1164. return newsock, addr
  1165. @_sslcopydoc
  1166. def get_channel_binding(self, cb_type="tls-unique"):
  1167. if self._sslobj is not None:
  1168. return self._sslobj.get_channel_binding(cb_type)
  1169. else:
  1170. if cb_type not in CHANNEL_BINDING_TYPES:
  1171. raise ValueError(
  1172. "{0} channel binding type not implemented".format(cb_type)
  1173. )
  1174. return None
  1175. @_sslcopydoc
  1176. def version(self):
  1177. if self._sslobj is not None:
  1178. return self._sslobj.version()
  1179. else:
  1180. return None
  1181. # Python does not support forward declaration of types.
  1182. SSLContext.sslsocket_class = SSLSocket
  1183. SSLContext.sslobject_class = SSLObject
  1184. # some utility functions
  1185. def cert_time_to_seconds(cert_time):
  1186. """Return the time in seconds since the Epoch, given the timestring
  1187. representing the "notBefore" or "notAfter" date from a certificate
  1188. in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
  1189. "notBefore" or "notAfter" dates must use UTC (RFC 5280).
  1190. Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  1191. UTC should be specified as GMT (see ASN1_TIME_print())
  1192. """
  1193. from time import strptime
  1194. from calendar import timegm
  1195. months = (
  1196. "Jan","Feb","Mar","Apr","May","Jun",
  1197. "Jul","Aug","Sep","Oct","Nov","Dec"
  1198. )
  1199. time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
  1200. try:
  1201. month_number = months.index(cert_time[:3].title()) + 1
  1202. except ValueError:
  1203. raise ValueError('time data %r does not match '
  1204. 'format "%%b%s"' % (cert_time, time_format))
  1205. else:
  1206. # found valid month
  1207. tt = strptime(cert_time[3:], time_format)
  1208. # return an integer, the previous mktime()-based implementation
  1209. # returned a float (fractional seconds are always zero here).
  1210. return timegm((tt[0], month_number) + tt[2:6])
  1211. PEM_HEADER = "-----BEGIN CERTIFICATE-----"
  1212. PEM_FOOTER = "-----END CERTIFICATE-----"
  1213. def DER_cert_to_PEM_cert(der_cert_bytes):
  1214. """Takes a certificate in binary DER format and returns the
  1215. PEM version of it as a string."""
  1216. f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
  1217. ss = [PEM_HEADER]
  1218. ss += [f[i:i+64] for i in range(0, len(f), 64)]
  1219. ss.append(PEM_FOOTER + '\n')
  1220. return '\n'.join(ss)
  1221. def PEM_cert_to_DER_cert(pem_cert_string):
  1222. """Takes a certificate in ASCII PEM format and returns the
  1223. DER-encoded version of it as a byte sequence"""
  1224. if not pem_cert_string.startswith(PEM_HEADER):
  1225. raise ValueError("Invalid PEM encoding; must start with %s"
  1226. % PEM_HEADER)
  1227. if not pem_cert_string.strip().endswith(PEM_FOOTER):
  1228. raise ValueError("Invalid PEM encoding; must end with %s"
  1229. % PEM_FOOTER)
  1230. d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
  1231. return base64.decodebytes(d.encode('ASCII', 'strict'))
  1232. def get_server_certificate(addr, ssl_version=PROTOCOL_TLS_CLIENT,
  1233. ca_certs=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
  1234. """Retrieve the certificate from the server at the specified address,
  1235. and return it as a PEM-encoded string.
  1236. If 'ca_certs' is specified, validate the server cert against it.
  1237. If 'ssl_version' is specified, use it in the connection attempt.
  1238. If 'timeout' is specified, use it in the connection attempt.
  1239. """
  1240. host, port = addr
  1241. if ca_certs is not None:
  1242. cert_reqs = CERT_REQUIRED
  1243. else:
  1244. cert_reqs = CERT_NONE
  1245. context = _create_stdlib_context(ssl_version,
  1246. cert_reqs=cert_reqs,
  1247. cafile=ca_certs)
  1248. with create_connection(addr, timeout=timeout) as sock:
  1249. with context.wrap_socket(sock, server_hostname=host) as sslsock:
  1250. dercert = sslsock.getpeercert(True)
  1251. return DER_cert_to_PEM_cert(dercert)
  1252. def get_protocol_name(protocol_code):
  1253. return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')