ssl.py 44 KB

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