ssl.py 37 KB

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