ssl.py 51 KB

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