ssl.py 50 KB

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