ssl.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
  14. by the server running on HOST at port PORT. No
  15. validation of the certificate is performed.
  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_TLSv1
  40. PROTOCOL_TLSv1_1
  41. PROTOCOL_TLSv1_2
  42. The following constants identify various SSL alert message descriptions as per
  43. http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6
  44. ALERT_DESCRIPTION_CLOSE_NOTIFY
  45. ALERT_DESCRIPTION_UNEXPECTED_MESSAGE
  46. ALERT_DESCRIPTION_BAD_RECORD_MAC
  47. ALERT_DESCRIPTION_RECORD_OVERFLOW
  48. ALERT_DESCRIPTION_DECOMPRESSION_FAILURE
  49. ALERT_DESCRIPTION_HANDSHAKE_FAILURE
  50. ALERT_DESCRIPTION_BAD_CERTIFICATE
  51. ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE
  52. ALERT_DESCRIPTION_CERTIFICATE_REVOKED
  53. ALERT_DESCRIPTION_CERTIFICATE_EXPIRED
  54. ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN
  55. ALERT_DESCRIPTION_ILLEGAL_PARAMETER
  56. ALERT_DESCRIPTION_UNKNOWN_CA
  57. ALERT_DESCRIPTION_ACCESS_DENIED
  58. ALERT_DESCRIPTION_DECODE_ERROR
  59. ALERT_DESCRIPTION_DECRYPT_ERROR
  60. ALERT_DESCRIPTION_PROTOCOL_VERSION
  61. ALERT_DESCRIPTION_INSUFFICIENT_SECURITY
  62. ALERT_DESCRIPTION_INTERNAL_ERROR
  63. ALERT_DESCRIPTION_USER_CANCELLED
  64. ALERT_DESCRIPTION_NO_RENEGOTIATION
  65. ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION
  66. ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE
  67. ALERT_DESCRIPTION_UNRECOGNIZED_NAME
  68. ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE
  69. ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE
  70. ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY
  71. """
  72. import ipaddress
  73. import textwrap
  74. import re
  75. import sys
  76. import os
  77. from collections import namedtuple
  78. from enum import Enum as _Enum, IntEnum as _IntEnum
  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
  82. from _ssl import (
  83. SSLError, SSLZeroReturnError, SSLWantReadError, SSLWantWriteError,
  84. SSLSyscallError, SSLEOFError,
  85. )
  86. from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
  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. def _import_symbols(prefix):
  95. for n in dir(_ssl):
  96. if n.startswith(prefix):
  97. globals()[n] = getattr(_ssl, n)
  98. _import_symbols('OP_')
  99. _import_symbols('ALERT_DESCRIPTION_')
  100. _import_symbols('SSL_ERROR_')
  101. _import_symbols('VERIFY_')
  102. from _ssl import HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN
  103. from _ssl import _OPENSSL_API_VERSION
  104. _IntEnum._convert(
  105. '_SSLMethod', __name__,
  106. lambda name: name.startswith('PROTOCOL_'),
  107. source=_ssl)
  108. _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
  109. try:
  110. _SSLv2_IF_EXISTS = PROTOCOL_SSLv2
  111. except NameError:
  112. _SSLv2_IF_EXISTS = None
  113. if sys.platform == "win32":
  114. from _ssl import enum_certificates, enum_crls
  115. from socket import socket, AF_INET, SOCK_STREAM, create_connection
  116. from socket import SOL_SOCKET, SO_TYPE
  117. import base64 # for DER-to-PEM translation
  118. import errno
  119. import warnings
  120. socket_error = OSError # keep that public name in module namespace
  121. if _ssl.HAS_TLS_UNIQUE:
  122. CHANNEL_BINDING_TYPES = ['tls-unique']
  123. else:
  124. CHANNEL_BINDING_TYPES = []
  125. # Disable weak or insecure ciphers by default
  126. # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
  127. # Enable a better set of ciphers by default
  128. # This list has been explicitly chosen to:
  129. # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
  130. # * Prefer ECDHE over DHE for better performance
  131. # * Prefer any AES-GCM over any AES-CBC for better performance and security
  132. # * Then Use HIGH cipher suites as a fallback
  133. # * Then Use 3DES as fallback which is secure but slow
  134. # * Disable NULL authentication, NULL encryption, and MD5 MACs for security
  135. # reasons
  136. _DEFAULT_CIPHERS = (
  137. 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
  138. 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
  139. '!eNULL:!MD5'
  140. )
  141. # Restricted and more secure ciphers for the server side
  142. # This list has been explicitly chosen to:
  143. # * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
  144. # * Prefer ECDHE over DHE for better performance
  145. # * Prefer any AES-GCM over any AES-CBC for better performance and security
  146. # * Then Use HIGH cipher suites as a fallback
  147. # * Then Use 3DES as fallback which is secure but slow
  148. # * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
  149. # security reasons
  150. _RESTRICTED_SERVER_CIPHERS = (
  151. 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
  152. 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
  153. '!eNULL:!MD5:!DSS:!RC4'
  154. )
  155. class CertificateError(ValueError):
  156. pass
  157. def _dnsname_match(dn, hostname, max_wildcards=1):
  158. """Matching according to RFC 6125, section 6.4.3
  159. http://tools.ietf.org/html/rfc6125#section-6.4.3
  160. """
  161. pats = []
  162. if not dn:
  163. return False
  164. leftmost, *remainder = dn.split(r'.')
  165. wildcards = leftmost.count('*')
  166. if wildcards > max_wildcards:
  167. # Issue #17980: avoid denials of service by refusing more
  168. # than one wildcard per fragment. A survey of established
  169. # policy among SSL implementations showed it to be a
  170. # reasonable choice.
  171. raise CertificateError(
  172. "too many wildcards in certificate DNS name: " + repr(dn))
  173. # speed up common case w/o wildcards
  174. if not wildcards:
  175. return dn.lower() == hostname.lower()
  176. # RFC 6125, section 6.4.3, subitem 1.
  177. # The client SHOULD NOT attempt to match a presented identifier in which
  178. # the wildcard character comprises a label other than the left-most label.
  179. if leftmost == '*':
  180. # When '*' is a fragment by itself, it matches a non-empty dotless
  181. # fragment.
  182. pats.append('[^.]+')
  183. elif leftmost.startswith('xn--') or hostname.startswith('xn--'):
  184. # RFC 6125, section 6.4.3, subitem 3.
  185. # The client SHOULD NOT attempt to match a presented identifier
  186. # where the wildcard character is embedded within an A-label or
  187. # U-label of an internationalized domain name.
  188. pats.append(re.escape(leftmost))
  189. else:
  190. # Otherwise, '*' matches any dotless string, e.g. www*
  191. pats.append(re.escape(leftmost).replace(r'\*', '[^.]*'))
  192. # add the remaining fragments, ignore any wildcards
  193. for frag in remainder:
  194. pats.append(re.escape(frag))
  195. pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
  196. return pat.match(hostname)
  197. def _ipaddress_match(ipname, host_ip):
  198. """Exact matching of IP addresses.
  199. RFC 6125 explicitly doesn't define an algorithm for this
  200. (section 1.7.2 - "Out of Scope").
  201. """
  202. # OpenSSL may add a trailing newline to a subjectAltName's IP address
  203. ip = ipaddress.ip_address(ipname.rstrip())
  204. return ip == host_ip
  205. def match_hostname(cert, hostname):
  206. """Verify that *cert* (in decoded format as returned by
  207. SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
  208. rules are followed, but IP addresses are not accepted for *hostname*.
  209. CertificateError is raised on failure. On success, the function
  210. returns nothing.
  211. """
  212. if not cert:
  213. raise ValueError("empty or no certificate, match_hostname needs a "
  214. "SSL socket or SSL context with either "
  215. "CERT_OPTIONAL or CERT_REQUIRED")
  216. try:
  217. host_ip = ipaddress.ip_address(hostname)
  218. except ValueError:
  219. # Not an IP address (common case)
  220. host_ip = None
  221. dnsnames = []
  222. san = cert.get('subjectAltName', ())
  223. for key, value in san:
  224. if key == 'DNS':
  225. if host_ip is None and _dnsname_match(value, hostname):
  226. return
  227. dnsnames.append(value)
  228. elif key == 'IP Address':
  229. if host_ip is not None and _ipaddress_match(value, host_ip):
  230. return
  231. dnsnames.append(value)
  232. if not dnsnames:
  233. # The subject is only checked when there is no dNSName entry
  234. # in subjectAltName
  235. for sub in cert.get('subject', ()):
  236. for key, value in sub:
  237. # XXX according to RFC 2818, the most specific Common Name
  238. # must be used.
  239. if key == 'commonName':
  240. if _dnsname_match(value, hostname):
  241. return
  242. dnsnames.append(value)
  243. if len(dnsnames) > 1:
  244. raise CertificateError("hostname %r "
  245. "doesn't match either of %s"
  246. % (hostname, ', '.join(map(repr, dnsnames))))
  247. elif len(dnsnames) == 1:
  248. raise CertificateError("hostname %r "
  249. "doesn't match %r"
  250. % (hostname, dnsnames[0]))
  251. else:
  252. raise CertificateError("no appropriate commonName or "
  253. "subjectAltName fields were found")
  254. DefaultVerifyPaths = namedtuple("DefaultVerifyPaths",
  255. "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env "
  256. "openssl_capath")
  257. def get_default_verify_paths():
  258. """Return paths to default cafile and capath.
  259. """
  260. parts = _ssl.get_default_verify_paths()
  261. # environment vars shadow paths
  262. cafile = os.environ.get(parts[0], parts[1])
  263. capath = os.environ.get(parts[2], parts[3])
  264. return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
  265. capath if os.path.isdir(capath) else None,
  266. *parts)
  267. class _ASN1Object(namedtuple("_ASN1Object", "nid shortname longname oid")):
  268. """ASN.1 object identifier lookup
  269. """
  270. __slots__ = ()
  271. def __new__(cls, oid):
  272. return super().__new__(cls, *_txt2obj(oid, name=False))
  273. @classmethod
  274. def fromnid(cls, nid):
  275. """Create _ASN1Object from OpenSSL numeric ID
  276. """
  277. return super().__new__(cls, *_nid2obj(nid))
  278. @classmethod
  279. def fromname(cls, name):
  280. """Create _ASN1Object from short name, long name or OID
  281. """
  282. return super().__new__(cls, *_txt2obj(name, name=True))
  283. class Purpose(_ASN1Object, _Enum):
  284. """SSLContext purpose flags with X509v3 Extended Key Usage objects
  285. """
  286. SERVER_AUTH = '1.3.6.1.5.5.7.3.1'
  287. CLIENT_AUTH = '1.3.6.1.5.5.7.3.2'
  288. class SSLContext(_SSLContext):
  289. """An SSLContext holds various SSL-related configuration options and
  290. data, such as certificates and possibly a private key."""
  291. __slots__ = ('protocol', '__weakref__')
  292. _windows_cert_stores = ("CA", "ROOT")
  293. def __new__(cls, protocol, *args, **kwargs):
  294. self = _SSLContext.__new__(cls, protocol)
  295. if protocol != _SSLv2_IF_EXISTS:
  296. self.set_ciphers(_DEFAULT_CIPHERS)
  297. return self
  298. def __init__(self, protocol):
  299. self.protocol = protocol
  300. def wrap_socket(self, sock, server_side=False,
  301. do_handshake_on_connect=True,
  302. suppress_ragged_eofs=True,
  303. server_hostname=None):
  304. return SSLSocket(sock=sock, server_side=server_side,
  305. do_handshake_on_connect=do_handshake_on_connect,
  306. suppress_ragged_eofs=suppress_ragged_eofs,
  307. server_hostname=server_hostname,
  308. _context=self)
  309. def wrap_bio(self, incoming, outgoing, server_side=False,
  310. server_hostname=None):
  311. sslobj = self._wrap_bio(incoming, outgoing, server_side=server_side,
  312. server_hostname=server_hostname)
  313. return SSLObject(sslobj)
  314. def set_npn_protocols(self, npn_protocols):
  315. protos = bytearray()
  316. for protocol in npn_protocols:
  317. b = bytes(protocol, 'ascii')
  318. if len(b) == 0 or len(b) > 255:
  319. raise SSLError('NPN protocols must be 1 to 255 in length')
  320. protos.append(len(b))
  321. protos.extend(b)
  322. self._set_npn_protocols(protos)
  323. def set_alpn_protocols(self, alpn_protocols):
  324. protos = bytearray()
  325. for protocol in alpn_protocols:
  326. b = bytes(protocol, 'ascii')
  327. if len(b) == 0 or len(b) > 255:
  328. raise SSLError('ALPN protocols must be 1 to 255 in length')
  329. protos.append(len(b))
  330. protos.extend(b)
  331. self._set_alpn_protocols(protos)
  332. def _load_windows_store_certs(self, storename, purpose):
  333. certs = bytearray()
  334. try:
  335. for cert, encoding, trust in enum_certificates(storename):
  336. # CA certs are never PKCS#7 encoded
  337. if encoding == "x509_asn":
  338. if trust is True or purpose.oid in trust:
  339. certs.extend(cert)
  340. except PermissionError:
  341. warnings.warn("unable to enumerate Windows certificate store")
  342. if certs:
  343. self.load_verify_locations(cadata=certs)
  344. return certs
  345. def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
  346. if not isinstance(purpose, _ASN1Object):
  347. raise TypeError(purpose)
  348. if sys.platform == "win32":
  349. for storename in self._windows_cert_stores:
  350. self._load_windows_store_certs(storename, purpose)
  351. self.set_default_verify_paths()
  352. def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
  353. capath=None, cadata=None):
  354. """Create a SSLContext object with default settings.
  355. NOTE: The protocol and settings may change anytime without prior
  356. deprecation. The values represent a fair balance between maximum
  357. compatibility and security.
  358. """
  359. if not isinstance(purpose, _ASN1Object):
  360. raise TypeError(purpose)
  361. context = SSLContext(PROTOCOL_SSLv23)
  362. # SSLv2 considered harmful.
  363. context.options |= OP_NO_SSLv2
  364. # SSLv3 has problematic security and is only required for really old
  365. # clients such as IE6 on Windows XP
  366. context.options |= OP_NO_SSLv3
  367. # disable compression to prevent CRIME attacks (OpenSSL 1.0+)
  368. context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
  369. if purpose == Purpose.SERVER_AUTH:
  370. # verify certs and host name in client mode
  371. context.verify_mode = CERT_REQUIRED
  372. context.check_hostname = True
  373. elif purpose == Purpose.CLIENT_AUTH:
  374. # Prefer the server's ciphers by default so that we get stronger
  375. # encryption
  376. context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
  377. # Use single use keys in order to improve forward secrecy
  378. context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
  379. context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
  380. # disallow ciphers with known vulnerabilities
  381. context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
  382. if cafile or capath or cadata:
  383. context.load_verify_locations(cafile, capath, cadata)
  384. elif context.verify_mode != CERT_NONE:
  385. # no explicit cafile, capath or cadata but the verify mode is
  386. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  387. # root CA certificates for the given purpose. This may fail silently.
  388. context.load_default_certs(purpose)
  389. return context
  390. def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
  391. check_hostname=False, purpose=Purpose.SERVER_AUTH,
  392. certfile=None, keyfile=None,
  393. cafile=None, capath=None, cadata=None):
  394. """Create a SSLContext object for Python stdlib modules
  395. All Python stdlib modules shall use this function to create SSLContext
  396. objects in order to keep common settings in one place. The configuration
  397. is less restrict than create_default_context()'s to increase backward
  398. compatibility.
  399. """
  400. if not isinstance(purpose, _ASN1Object):
  401. raise TypeError(purpose)
  402. context = SSLContext(protocol)
  403. # SSLv2 considered harmful.
  404. context.options |= OP_NO_SSLv2
  405. # SSLv3 has problematic security and is only required for really old
  406. # clients such as IE6 on Windows XP
  407. context.options |= OP_NO_SSLv3
  408. if cert_reqs is not None:
  409. context.verify_mode = cert_reqs
  410. context.check_hostname = check_hostname
  411. if keyfile and not certfile:
  412. raise ValueError("certfile must be specified")
  413. if certfile or keyfile:
  414. context.load_cert_chain(certfile, keyfile)
  415. # load CA root certs
  416. if cafile or capath or cadata:
  417. context.load_verify_locations(cafile, capath, cadata)
  418. elif context.verify_mode != CERT_NONE:
  419. # no explicit cafile, capath or cadata but the verify mode is
  420. # CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
  421. # root CA certificates for the given purpose. This may fail silently.
  422. context.load_default_certs(purpose)
  423. return context
  424. # Used by http.client if no context is explicitly passed.
  425. _create_default_https_context = create_default_context
  426. # Backwards compatibility alias, even though it's not a public name.
  427. _create_stdlib_context = _create_unverified_context
  428. class SSLObject:
  429. """This class implements an interface on top of a low-level SSL object as
  430. implemented by OpenSSL. This object captures the state of an SSL connection
  431. but does not provide any network IO itself. IO needs to be performed
  432. through separate "BIO" objects which are OpenSSL's IO abstraction layer.
  433. This class does not have a public constructor. Instances are returned by
  434. ``SSLContext.wrap_bio``. This class is typically used by framework authors
  435. that want to implement asynchronous IO for SSL through memory buffers.
  436. When compared to ``SSLSocket``, this object lacks the following features:
  437. * Any form of network IO incluging methods such as ``recv`` and ``send``.
  438. * The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
  439. """
  440. def __init__(self, sslobj, owner=None):
  441. self._sslobj = sslobj
  442. # Note: _sslobj takes a weak reference to owner
  443. self._sslobj.owner = owner or self
  444. @property
  445. def context(self):
  446. """The SSLContext that is currently in use."""
  447. return self._sslobj.context
  448. @context.setter
  449. def context(self, ctx):
  450. self._sslobj.context = ctx
  451. @property
  452. def server_side(self):
  453. """Whether this is a server-side socket."""
  454. return self._sslobj.server_side
  455. @property
  456. def server_hostname(self):
  457. """The currently set server hostname (for SNI), or ``None`` if no
  458. server hostame is set."""
  459. return self._sslobj.server_hostname
  460. def read(self, len=1024, buffer=None):
  461. """Read up to 'len' bytes from the SSL object and return them.
  462. If 'buffer' is provided, read into this buffer and return the number of
  463. bytes read.
  464. """
  465. if buffer is not None:
  466. v = self._sslobj.read(len, buffer)
  467. else:
  468. v = self._sslobj.read(len)
  469. return v
  470. def write(self, data):
  471. """Write 'data' to the SSL object and return the number of bytes
  472. written.
  473. The 'data' argument must support the buffer interface.
  474. """
  475. return self._sslobj.write(data)
  476. def getpeercert(self, binary_form=False):
  477. """Returns a formatted version of the data in the certificate provided
  478. by the other end of the SSL channel.
  479. Return None if no certificate was provided, {} if a certificate was
  480. provided, but not validated.
  481. """
  482. return self._sslobj.peer_certificate(binary_form)
  483. def selected_npn_protocol(self):
  484. """Return the currently selected NPN protocol as a string, or ``None``
  485. if a next protocol was not negotiated or if NPN is not supported by one
  486. of the peers."""
  487. if _ssl.HAS_NPN:
  488. return self._sslobj.selected_npn_protocol()
  489. def selected_alpn_protocol(self):
  490. """Return the currently selected ALPN protocol as a string, or ``None``
  491. if a next protocol was not negotiated or if ALPN is not supported by one
  492. of the peers."""
  493. if _ssl.HAS_ALPN:
  494. return self._sslobj.selected_alpn_protocol()
  495. def cipher(self):
  496. """Return the currently selected cipher as a 3-tuple ``(name,
  497. ssl_version, secret_bits)``."""
  498. return self._sslobj.cipher()
  499. def shared_ciphers(self):
  500. """Return a list of ciphers shared by the client during the handshake or
  501. None if this is not a valid server connection.
  502. """
  503. return self._sslobj.shared_ciphers()
  504. def compression(self):
  505. """Return the current compression algorithm in use, or ``None`` if
  506. compression was not negotiated or not supported by one of the peers."""
  507. return self._sslobj.compression()
  508. def pending(self):
  509. """Return the number of bytes that can be read immediately."""
  510. return self._sslobj.pending()
  511. def do_handshake(self):
  512. """Start the SSL/TLS handshake."""
  513. self._sslobj.do_handshake()
  514. if self.context.check_hostname:
  515. if not self.server_hostname:
  516. raise ValueError("check_hostname needs server_hostname "
  517. "argument")
  518. match_hostname(self.getpeercert(), self.server_hostname)
  519. def unwrap(self):
  520. """Start the SSL shutdown handshake."""
  521. return self._sslobj.shutdown()
  522. def get_channel_binding(self, cb_type="tls-unique"):
  523. """Get channel binding data for current connection. Raise ValueError
  524. if the requested `cb_type` is not supported. Return bytes of the data
  525. or None if the data is not available (e.g. before the handshake)."""
  526. if cb_type not in CHANNEL_BINDING_TYPES:
  527. raise ValueError("Unsupported channel binding type")
  528. if cb_type != "tls-unique":
  529. raise NotImplementedError(
  530. "{0} channel binding type not implemented"
  531. .format(cb_type))
  532. return self._sslobj.tls_unique_cb()
  533. def version(self):
  534. """Return a string identifying the protocol version used by the
  535. current SSL channel. """
  536. return self._sslobj.version()
  537. class SSLSocket(socket):
  538. """This class implements a subtype of socket.socket that wraps
  539. the underlying OS socket in an SSL context when necessary, and
  540. provides read and write methods over that channel."""
  541. def __init__(self, sock=None, keyfile=None, certfile=None,
  542. server_side=False, cert_reqs=CERT_NONE,
  543. ssl_version=PROTOCOL_SSLv23, ca_certs=None,
  544. do_handshake_on_connect=True,
  545. family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
  546. suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
  547. server_hostname=None,
  548. _context=None):
  549. if _context:
  550. self._context = _context
  551. else:
  552. if server_side and not certfile:
  553. raise ValueError("certfile must be specified for server-side "
  554. "operations")
  555. if keyfile and not certfile:
  556. raise ValueError("certfile must be specified")
  557. if certfile and not keyfile:
  558. keyfile = certfile
  559. self._context = SSLContext(ssl_version)
  560. self._context.verify_mode = cert_reqs
  561. if ca_certs:
  562. self._context.load_verify_locations(ca_certs)
  563. if certfile:
  564. self._context.load_cert_chain(certfile, keyfile)
  565. if npn_protocols:
  566. self._context.set_npn_protocols(npn_protocols)
  567. if ciphers:
  568. self._context.set_ciphers(ciphers)
  569. self.keyfile = keyfile
  570. self.certfile = certfile
  571. self.cert_reqs = cert_reqs
  572. self.ssl_version = ssl_version
  573. self.ca_certs = ca_certs
  574. self.ciphers = ciphers
  575. # Can't use sock.type as other flags (such as SOCK_NONBLOCK) get
  576. # mixed in.
  577. if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM:
  578. raise NotImplementedError("only stream sockets are supported")
  579. if server_side and server_hostname:
  580. raise ValueError("server_hostname can only be specified "
  581. "in client mode")
  582. if self._context.check_hostname and not server_hostname:
  583. raise ValueError("check_hostname requires server_hostname")
  584. self.server_side = server_side
  585. self.server_hostname = server_hostname
  586. self.do_handshake_on_connect = do_handshake_on_connect
  587. self.suppress_ragged_eofs = suppress_ragged_eofs
  588. if sock is not None:
  589. socket.__init__(self,
  590. family=sock.family,
  591. type=sock.type,
  592. proto=sock.proto,
  593. fileno=sock.fileno())
  594. self.settimeout(sock.gettimeout())
  595. sock.detach()
  596. elif fileno is not None:
  597. socket.__init__(self, fileno=fileno)
  598. else:
  599. socket.__init__(self, family=family, type=type, proto=proto)
  600. # See if we are connected
  601. try:
  602. self.getpeername()
  603. except OSError as e:
  604. if e.errno != errno.ENOTCONN:
  605. raise
  606. connected = False
  607. else:
  608. connected = True
  609. self._closed = False
  610. self._sslobj = None
  611. self._connected = connected
  612. if connected:
  613. # create the SSL object
  614. try:
  615. sslobj = self._context._wrap_socket(self, server_side,
  616. server_hostname)
  617. self._sslobj = SSLObject(sslobj, owner=self)
  618. if do_handshake_on_connect:
  619. timeout = self.gettimeout()
  620. if timeout == 0.0:
  621. # non-blocking
  622. raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
  623. self.do_handshake()
  624. except (OSError, ValueError):
  625. self.close()
  626. raise
  627. @property
  628. def context(self):
  629. return self._context
  630. @context.setter
  631. def context(self, ctx):
  632. self._context = ctx
  633. self._sslobj.context = ctx
  634. def dup(self):
  635. raise NotImplemented("Can't dup() %s instances" %
  636. self.__class__.__name__)
  637. def _checkClosed(self, msg=None):
  638. # raise an exception here if you wish to check for spurious closes
  639. pass
  640. def _check_connected(self):
  641. if not self._connected:
  642. # getpeername() will raise ENOTCONN if the socket is really
  643. # not connected; note that we can be connected even without
  644. # _connected being set, e.g. if connect() first returned
  645. # EAGAIN.
  646. self.getpeername()
  647. def read(self, len=1024, buffer=None):
  648. """Read up to LEN bytes and return them.
  649. Return zero-length string on EOF."""
  650. self._checkClosed()
  651. if not self._sslobj:
  652. raise ValueError("Read on closed or unwrapped SSL socket.")
  653. try:
  654. return self._sslobj.read(len, buffer)
  655. except SSLError as x:
  656. if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
  657. if buffer is not None:
  658. return 0
  659. else:
  660. return b''
  661. else:
  662. raise
  663. def write(self, data):
  664. """Write DATA to the underlying SSL channel. Returns
  665. number of bytes of DATA actually transmitted."""
  666. self._checkClosed()
  667. if not self._sslobj:
  668. raise ValueError("Write on closed or unwrapped SSL socket.")
  669. return self._sslobj.write(data)
  670. def getpeercert(self, binary_form=False):
  671. """Returns a formatted version of the data in the
  672. certificate provided by the other end of the SSL channel.
  673. Return None if no certificate was provided, {} if a
  674. certificate was provided, but not validated."""
  675. self._checkClosed()
  676. self._check_connected()
  677. return self._sslobj.getpeercert(binary_form)
  678. def selected_npn_protocol(self):
  679. self._checkClosed()
  680. if not self._sslobj or not _ssl.HAS_NPN:
  681. return None
  682. else:
  683. return self._sslobj.selected_npn_protocol()
  684. def selected_alpn_protocol(self):
  685. self._checkClosed()
  686. if not self._sslobj or not _ssl.HAS_ALPN:
  687. return None
  688. else:
  689. return self._sslobj.selected_alpn_protocol()
  690. def cipher(self):
  691. self._checkClosed()
  692. if not self._sslobj:
  693. return None
  694. else:
  695. return self._sslobj.cipher()
  696. def shared_ciphers(self):
  697. self._checkClosed()
  698. if not self._sslobj:
  699. return None
  700. return self._sslobj.shared_ciphers()
  701. def compression(self):
  702. self._checkClosed()
  703. if not self._sslobj:
  704. return None
  705. else:
  706. return self._sslobj.compression()
  707. def send(self, data, flags=0):
  708. self._checkClosed()
  709. if self._sslobj:
  710. if flags != 0:
  711. raise ValueError(
  712. "non-zero flags not allowed in calls to send() on %s" %
  713. self.__class__)
  714. return self._sslobj.write(data)
  715. else:
  716. return socket.send(self, data, flags)
  717. def sendto(self, data, flags_or_addr, addr=None):
  718. self._checkClosed()
  719. if self._sslobj:
  720. raise ValueError("sendto not allowed on instances of %s" %
  721. self.__class__)
  722. elif addr is None:
  723. return socket.sendto(self, data, flags_or_addr)
  724. else:
  725. return socket.sendto(self, data, flags_or_addr, addr)
  726. def sendmsg(self, *args, **kwargs):
  727. # Ensure programs don't send data unencrypted if they try to
  728. # use this method.
  729. raise NotImplementedError("sendmsg not allowed on instances of %s" %
  730. self.__class__)
  731. def sendall(self, data, flags=0):
  732. self._checkClosed()
  733. if self._sslobj:
  734. if flags != 0:
  735. raise ValueError(
  736. "non-zero flags not allowed in calls to sendall() on %s" %
  737. self.__class__)
  738. amount = len(data)
  739. count = 0
  740. while (count < amount):
  741. v = self.send(data[count:])
  742. count += v
  743. return amount
  744. else:
  745. return socket.sendall(self, data, flags)
  746. def sendfile(self, file, offset=0, count=None):
  747. """Send a file, possibly by using os.sendfile() if this is a
  748. clear-text socket. Return the total number of bytes sent.
  749. """
  750. if self._sslobj is None:
  751. # os.sendfile() works with plain sockets only
  752. return super().sendfile(file, offset, count)
  753. else:
  754. return self._sendfile_use_send(file, offset, count)
  755. def recv(self, buflen=1024, flags=0):
  756. self._checkClosed()
  757. if self._sslobj:
  758. if flags != 0:
  759. raise ValueError(
  760. "non-zero flags not allowed in calls to recv() on %s" %
  761. self.__class__)
  762. return self.read(buflen)
  763. else:
  764. return socket.recv(self, buflen, flags)
  765. def recv_into(self, buffer, nbytes=None, flags=0):
  766. self._checkClosed()
  767. if buffer and (nbytes is None):
  768. nbytes = len(buffer)
  769. elif nbytes is None:
  770. nbytes = 1024
  771. if self._sslobj:
  772. if flags != 0:
  773. raise ValueError(
  774. "non-zero flags not allowed in calls to recv_into() on %s" %
  775. self.__class__)
  776. return self.read(nbytes, buffer)
  777. else:
  778. return socket.recv_into(self, buffer, nbytes, flags)
  779. def recvfrom(self, buflen=1024, flags=0):
  780. self._checkClosed()
  781. if self._sslobj:
  782. raise ValueError("recvfrom not allowed on instances of %s" %
  783. self.__class__)
  784. else:
  785. return socket.recvfrom(self, buflen, flags)
  786. def recvfrom_into(self, buffer, nbytes=None, flags=0):
  787. self._checkClosed()
  788. if self._sslobj:
  789. raise ValueError("recvfrom_into not allowed on instances of %s" %
  790. self.__class__)
  791. else:
  792. return socket.recvfrom_into(self, buffer, nbytes, flags)
  793. def recvmsg(self, *args, **kwargs):
  794. raise NotImplementedError("recvmsg not allowed on instances of %s" %
  795. self.__class__)
  796. def recvmsg_into(self, *args, **kwargs):
  797. raise NotImplementedError("recvmsg_into not allowed on instances of "
  798. "%s" % self.__class__)
  799. def pending(self):
  800. self._checkClosed()
  801. if self._sslobj:
  802. return self._sslobj.pending()
  803. else:
  804. return 0
  805. def shutdown(self, how):
  806. self._checkClosed()
  807. self._sslobj = None
  808. socket.shutdown(self, how)
  809. def unwrap(self):
  810. if self._sslobj:
  811. s = self._sslobj.unwrap()
  812. self._sslobj = None
  813. return s
  814. else:
  815. raise ValueError("No SSL wrapper around " + str(self))
  816. def _real_close(self):
  817. self._sslobj = None
  818. socket._real_close(self)
  819. def do_handshake(self, block=False):
  820. """Perform a TLS/SSL handshake."""
  821. self._check_connected()
  822. timeout = self.gettimeout()
  823. try:
  824. if timeout == 0.0 and block:
  825. self.settimeout(None)
  826. self._sslobj.do_handshake()
  827. finally:
  828. self.settimeout(timeout)
  829. def _real_connect(self, addr, connect_ex):
  830. if self.server_side:
  831. raise ValueError("can't connect in server-side mode")
  832. # Here we assume that the socket is client-side, and not
  833. # connected at the time of the call. We connect it, then wrap it.
  834. if self._connected:
  835. raise ValueError("attempt to connect already-connected SSLSocket!")
  836. sslobj = self.context._wrap_socket(self, False, self.server_hostname)
  837. self._sslobj = SSLObject(sslobj, owner=self)
  838. try:
  839. if connect_ex:
  840. rc = socket.connect_ex(self, addr)
  841. else:
  842. rc = None
  843. socket.connect(self, addr)
  844. if not rc:
  845. self._connected = True
  846. if self.do_handshake_on_connect:
  847. self.do_handshake()
  848. return rc
  849. except (OSError, ValueError):
  850. self._sslobj = None
  851. raise
  852. def connect(self, addr):
  853. """Connects to remote ADDR, and then wraps the connection in
  854. an SSL channel."""
  855. self._real_connect(addr, False)
  856. def connect_ex(self, addr):
  857. """Connects to remote ADDR, and then wraps the connection in
  858. an SSL channel."""
  859. return self._real_connect(addr, True)
  860. def accept(self):
  861. """Accepts a new connection from a remote client, and returns
  862. a tuple containing that new connection wrapped with a server-side
  863. SSL channel, and the address of the remote client."""
  864. newsock, addr = socket.accept(self)
  865. newsock = self.context.wrap_socket(newsock,
  866. do_handshake_on_connect=self.do_handshake_on_connect,
  867. suppress_ragged_eofs=self.suppress_ragged_eofs,
  868. server_side=True)
  869. return newsock, addr
  870. def get_channel_binding(self, cb_type="tls-unique"):
  871. """Get channel binding data for current connection. Raise ValueError
  872. if the requested `cb_type` is not supported. Return bytes of the data
  873. or None if the data is not available (e.g. before the handshake).
  874. """
  875. if self._sslobj is None:
  876. return None
  877. return self._sslobj.get_channel_binding(cb_type)
  878. def version(self):
  879. """
  880. Return a string identifying the protocol version used by the
  881. current SSL channel, or None if there is no established channel.
  882. """
  883. if self._sslobj is None:
  884. return None
  885. return self._sslobj.version()
  886. def wrap_socket(sock, keyfile=None, certfile=None,
  887. server_side=False, cert_reqs=CERT_NONE,
  888. ssl_version=PROTOCOL_SSLv23, ca_certs=None,
  889. do_handshake_on_connect=True,
  890. suppress_ragged_eofs=True,
  891. ciphers=None):
  892. return SSLSocket(sock=sock, keyfile=keyfile, certfile=certfile,
  893. server_side=server_side, cert_reqs=cert_reqs,
  894. ssl_version=ssl_version, ca_certs=ca_certs,
  895. do_handshake_on_connect=do_handshake_on_connect,
  896. suppress_ragged_eofs=suppress_ragged_eofs,
  897. ciphers=ciphers)
  898. # some utility functions
  899. def cert_time_to_seconds(cert_time):
  900. """Return the time in seconds since the Epoch, given the timestring
  901. representing the "notBefore" or "notAfter" date from a certificate
  902. in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale).
  903. "notBefore" or "notAfter" dates must use UTC (RFC 5280).
  904. Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  905. UTC should be specified as GMT (see ASN1_TIME_print())
  906. """
  907. from time import strptime
  908. from calendar import timegm
  909. months = (
  910. "Jan","Feb","Mar","Apr","May","Jun",
  911. "Jul","Aug","Sep","Oct","Nov","Dec"
  912. )
  913. time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT
  914. try:
  915. month_number = months.index(cert_time[:3].title()) + 1
  916. except ValueError:
  917. raise ValueError('time data %r does not match '
  918. 'format "%%b%s"' % (cert_time, time_format))
  919. else:
  920. # found valid month
  921. tt = strptime(cert_time[3:], time_format)
  922. # return an integer, the previous mktime()-based implementation
  923. # returned a float (fractional seconds are always zero here).
  924. return timegm((tt[0], month_number) + tt[2:6])
  925. PEM_HEADER = "-----BEGIN CERTIFICATE-----"
  926. PEM_FOOTER = "-----END CERTIFICATE-----"
  927. def DER_cert_to_PEM_cert(der_cert_bytes):
  928. """Takes a certificate in binary DER format and returns the
  929. PEM version of it as a string."""
  930. f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict')
  931. return (PEM_HEADER + '\n' +
  932. textwrap.fill(f, 64) + '\n' +
  933. PEM_FOOTER + '\n')
  934. def PEM_cert_to_DER_cert(pem_cert_string):
  935. """Takes a certificate in ASCII PEM format and returns the
  936. DER-encoded version of it as a byte sequence"""
  937. if not pem_cert_string.startswith(PEM_HEADER):
  938. raise ValueError("Invalid PEM encoding; must start with %s"
  939. % PEM_HEADER)
  940. if not pem_cert_string.strip().endswith(PEM_FOOTER):
  941. raise ValueError("Invalid PEM encoding; must end with %s"
  942. % PEM_FOOTER)
  943. d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
  944. return base64.decodebytes(d.encode('ASCII', 'strict'))
  945. def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
  946. """Retrieve the certificate from the server at the specified address,
  947. and return it as a PEM-encoded string.
  948. If 'ca_certs' is specified, validate the server cert against it.
  949. If 'ssl_version' is specified, use it in the connection attempt."""
  950. host, port = addr
  951. if ca_certs is not None:
  952. cert_reqs = CERT_REQUIRED
  953. else:
  954. cert_reqs = CERT_NONE
  955. context = _create_stdlib_context(ssl_version,
  956. cert_reqs=cert_reqs,
  957. cafile=ca_certs)
  958. with create_connection(addr) as sock:
  959. with context.wrap_socket(sock) as sslsock:
  960. dercert = sslsock.getpeercert(True)
  961. return DER_cert_to_PEM_cert(dercert)
  962. def get_protocol_name(protocol_code):
  963. return _PROTOCOL_NAMES.get(protocol_code, '<unknown>')