_sslverify.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  1. # -*- test-case-name: twisted.test.test_sslverify -*-
  2. # Copyright (c) 2005 Divmod, Inc.
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. from __future__ import annotations
  6. import warnings
  7. from binascii import hexlify
  8. from functools import lru_cache
  9. from hashlib import md5
  10. from typing import Dict
  11. from zope.interface import Interface, implementer
  12. from OpenSSL import SSL, crypto
  13. from OpenSSL._util import lib as pyOpenSSLlib
  14. import attr
  15. from constantly import FlagConstant, Flags, NamedConstant, Names
  16. from incremental import Version
  17. from twisted.internet.abstract import isIPAddress, isIPv6Address
  18. from twisted.internet.defer import Deferred
  19. from twisted.internet.error import CertificateError, VerifyError
  20. from twisted.internet.interfaces import (
  21. IAcceptableCiphers,
  22. ICipher,
  23. IOpenSSLClientConnectionCreator,
  24. IOpenSSLContextFactory,
  25. )
  26. from twisted.logger import Logger
  27. from twisted.python.compat import nativeString
  28. from twisted.python.deprecate import _mutuallyExclusiveArguments, deprecated
  29. from twisted.python.failure import Failure
  30. from twisted.python.randbytes import secureRandom
  31. from twisted.python.util import nameToLabel
  32. from ._idna import _idnaBytes
  33. _log = Logger()
  34. class TLSVersion(Names):
  35. """
  36. TLS versions that we can negotiate with the client/server.
  37. """
  38. SSLv3 = NamedConstant()
  39. TLSv1_0 = NamedConstant()
  40. TLSv1_1 = NamedConstant()
  41. TLSv1_2 = NamedConstant()
  42. TLSv1_3 = NamedConstant()
  43. _tlsDisableFlags = {
  44. TLSVersion.SSLv3: SSL.OP_NO_SSLv3,
  45. TLSVersion.TLSv1_0: SSL.OP_NO_TLSv1,
  46. TLSVersion.TLSv1_1: SSL.OP_NO_TLSv1_1,
  47. TLSVersion.TLSv1_2: SSL.OP_NO_TLSv1_2,
  48. # If we don't have TLS v1.3 yet, we can't disable it -- this is just so
  49. # when it makes it into OpenSSL, connections knowingly bracketed to v1.2
  50. # don't end up going to v1.3
  51. TLSVersion.TLSv1_3: getattr(SSL, "OP_NO_TLSv1_3", 0x00),
  52. }
  53. def _getExcludedTLSProtocols(oldest, newest):
  54. """
  55. Given a pair of L{TLSVersion} constants, figure out what versions we want
  56. to disable (as OpenSSL is an exclusion based API).
  57. @param oldest: The oldest L{TLSVersion} we want to allow.
  58. @type oldest: L{TLSVersion} constant
  59. @param newest: The newest L{TLSVersion} we want to allow, or L{None} for no
  60. upper limit.
  61. @type newest: L{TLSVersion} constant or L{None}
  62. @return: The versions we want to disable.
  63. @rtype: L{list} of L{TLSVersion} constants.
  64. """
  65. versions = list(TLSVersion.iterconstants())
  66. excludedVersions = [x for x in versions[: versions.index(oldest)]]
  67. if newest:
  68. excludedVersions.extend([x for x in versions[versions.index(newest) :]])
  69. return excludedVersions
  70. class SimpleVerificationError(Exception):
  71. """
  72. Not a very useful verification error.
  73. """
  74. def simpleVerifyHostname(connection, hostname):
  75. """
  76. Check only the common name in the certificate presented by the peer and
  77. only for an exact match.
  78. This is to provide I{something} in the way of hostname verification to
  79. users who haven't installed C{service_identity}. This check is overly
  80. strict, relies on a deprecated TLS feature (you're supposed to ignore the
  81. commonName if the subjectAlternativeName extensions are present, I
  82. believe), and lots of valid certificates will fail.
  83. @param connection: the OpenSSL connection to verify.
  84. @type connection: L{OpenSSL.SSL.Connection}
  85. @param hostname: The hostname expected by the user.
  86. @type hostname: L{unicode}
  87. @raise twisted.internet.ssl.VerificationError: if the common name and
  88. hostname don't match.
  89. """
  90. commonName = connection.get_peer_certificate().get_subject().commonName
  91. if commonName != hostname:
  92. raise SimpleVerificationError(repr(commonName) + "!=" + repr(hostname))
  93. def simpleVerifyIPAddress(connection, hostname):
  94. """
  95. Always fails validation of IP addresses
  96. @param connection: the OpenSSL connection to verify.
  97. @type connection: L{OpenSSL.SSL.Connection}
  98. @param hostname: The hostname expected by the user.
  99. @type hostname: L{unicode}
  100. @raise twisted.internet.ssl.VerificationError: Always raised
  101. """
  102. raise SimpleVerificationError("Cannot verify certificate IP addresses")
  103. def _usablePyOpenSSL(version):
  104. """
  105. Check pyOpenSSL version string whether we can use it for host verification.
  106. @param version: A pyOpenSSL version string.
  107. @type version: L{str}
  108. @rtype: L{bool}
  109. """
  110. major, minor = (int(part) for part in version.split(".")[:2])
  111. return (major, minor) >= (0, 12)
  112. def _selectVerifyImplementation():
  113. """
  114. Determine if C{service_identity} is installed. If so, use it. If not, use
  115. simplistic and incorrect checking as implemented in
  116. L{simpleVerifyHostname}.
  117. @return: 2-tuple of (C{verify_hostname}, C{VerificationError})
  118. @rtype: L{tuple}
  119. """
  120. whatsWrong = (
  121. "Without the service_identity module, Twisted can perform only "
  122. "rudimentary TLS client hostname verification. Many valid "
  123. "certificate/hostname mappings may be rejected."
  124. )
  125. try:
  126. from service_identity import VerificationError
  127. from service_identity.pyopenssl import verify_hostname, verify_ip_address
  128. return verify_hostname, verify_ip_address, VerificationError
  129. except ImportError as e:
  130. warnings.warn_explicit(
  131. "You do not have a working installation of the "
  132. "service_identity module: '" + str(e) + "'. "
  133. "Please install it from "
  134. "<https://pypi.python.org/pypi/service_identity> and make "
  135. "sure all of its dependencies are satisfied. " + whatsWrong,
  136. # Unfortunately the lineno is required.
  137. category=UserWarning,
  138. filename="",
  139. lineno=0,
  140. )
  141. return simpleVerifyHostname, simpleVerifyIPAddress, SimpleVerificationError
  142. verifyHostname, verifyIPAddress, VerificationError = _selectVerifyImplementation()
  143. class ProtocolNegotiationSupport(Flags):
  144. """
  145. L{ProtocolNegotiationSupport} defines flags which are used to indicate the
  146. level of NPN/ALPN support provided by the TLS backend.
  147. @cvar NOSUPPORT: There is no support for NPN or ALPN. This is exclusive
  148. with both L{NPN} and L{ALPN}.
  149. @cvar NPN: The implementation supports Next Protocol Negotiation.
  150. @cvar ALPN: The implementation supports Application Layer Protocol
  151. Negotiation.
  152. """
  153. NPN = FlagConstant(0x0001)
  154. ALPN = FlagConstant(0x0002)
  155. # FIXME: https://twistedmatrix.com/trac/ticket/8074
  156. # Currently flags with literal zero values behave incorrectly. However,
  157. # creating a flag by NOTing a flag with itself appears to work totally fine, so
  158. # do that instead.
  159. ProtocolNegotiationSupport.NOSUPPORT = (
  160. ProtocolNegotiationSupport.NPN ^ ProtocolNegotiationSupport.NPN
  161. )
  162. def protocolNegotiationMechanisms():
  163. """
  164. Checks whether your versions of PyOpenSSL and OpenSSL are recent enough to
  165. support protocol negotiation, and if they are, what kind of protocol
  166. negotiation is supported.
  167. @return: A combination of flags from L{ProtocolNegotiationSupport} that
  168. indicate which mechanisms for protocol negotiation are supported.
  169. @rtype: L{constantly.FlagConstant}
  170. """
  171. support = ProtocolNegotiationSupport.NOSUPPORT
  172. ctx = SSL.Context(SSL.SSLv23_METHOD)
  173. try:
  174. ctx.set_npn_advertise_callback(lambda c: None)
  175. except (AttributeError, NotImplementedError):
  176. pass
  177. else:
  178. support |= ProtocolNegotiationSupport.NPN
  179. try:
  180. ctx.set_alpn_select_callback(lambda c: None)
  181. except (AttributeError, NotImplementedError):
  182. pass
  183. else:
  184. support |= ProtocolNegotiationSupport.ALPN
  185. return support
  186. _x509names = {
  187. "CN": "commonName",
  188. "commonName": "commonName",
  189. "O": "organizationName",
  190. "organizationName": "organizationName",
  191. "OU": "organizationalUnitName",
  192. "organizationalUnitName": "organizationalUnitName",
  193. "L": "localityName",
  194. "localityName": "localityName",
  195. "ST": "stateOrProvinceName",
  196. "stateOrProvinceName": "stateOrProvinceName",
  197. "C": "countryName",
  198. "countryName": "countryName",
  199. "emailAddress": "emailAddress",
  200. }
  201. class DistinguishedName(Dict[str, bytes]):
  202. """
  203. Identify and describe an entity.
  204. Distinguished names are used to provide a minimal amount of identifying
  205. information about a certificate issuer or subject. They are commonly
  206. created with one or more of the following fields::
  207. commonName (CN)
  208. organizationName (O)
  209. organizationalUnitName (OU)
  210. localityName (L)
  211. stateOrProvinceName (ST)
  212. countryName (C)
  213. emailAddress
  214. A L{DistinguishedName} should be constructed using keyword arguments whose
  215. keys can be any of the field names above (as a native string), and the
  216. values are either Unicode text which is encodable to ASCII, or L{bytes}
  217. limited to the ASCII subset. Any fields passed to the constructor will be
  218. set as attributes, accessible using both their extended name and their
  219. shortened acronym. The attribute values will be the ASCII-encoded
  220. bytes. For example::
  221. >>> dn = DistinguishedName(commonName=b'www.example.com',
  222. ... C='US')
  223. >>> dn.C
  224. b'US'
  225. >>> dn.countryName
  226. b'US'
  227. >>> hasattr(dn, "organizationName")
  228. False
  229. L{DistinguishedName} instances can also be used as dictionaries; the keys
  230. are extended name of the fields::
  231. >>> dn.keys()
  232. ['countryName', 'commonName']
  233. >>> dn['countryName']
  234. b'US'
  235. """
  236. __slots__ = ()
  237. def __init__(self, **kw):
  238. for k, v in kw.items():
  239. setattr(self, k, v)
  240. def _copyFrom(self, x509name):
  241. for name in _x509names:
  242. value = getattr(x509name, name, None)
  243. if value is not None:
  244. setattr(self, name, value)
  245. def _copyInto(self, x509name):
  246. for k, v in self.items():
  247. setattr(x509name, k, nativeString(v))
  248. def __repr__(self) -> str:
  249. return "<DN %s>" % (dict.__repr__(self)[1:-1])
  250. def __getattr__(self, attr):
  251. try:
  252. return self[_x509names[attr]]
  253. except KeyError:
  254. raise AttributeError(attr)
  255. def __setattr__(self, attr, value):
  256. if attr not in _x509names:
  257. raise AttributeError(f"{attr} is not a valid OpenSSL X509 name field")
  258. realAttr = _x509names[attr]
  259. if not isinstance(value, bytes):
  260. value = value.encode("ascii")
  261. self[realAttr] = value
  262. def inspect(self):
  263. """
  264. Return a multi-line, human-readable representation of this DN.
  265. @rtype: L{str}
  266. """
  267. l = []
  268. lablen = 0
  269. def uniqueValues(mapping):
  270. return set(mapping.values())
  271. for k in sorted(uniqueValues(_x509names)):
  272. label = nameToLabel(k)
  273. lablen = max(len(label), lablen)
  274. v = getattr(self, k, None)
  275. if v is not None:
  276. l.append((label, nativeString(v)))
  277. lablen += 2
  278. for n, (label, attrib) in enumerate(l):
  279. l[n] = label.rjust(lablen) + ": " + attrib
  280. return "\n".join(l)
  281. DN = DistinguishedName
  282. class CertBase:
  283. """
  284. Base class for public (certificate only) and private (certificate + key
  285. pair) certificates.
  286. @ivar original: The underlying OpenSSL certificate object.
  287. @type original: L{OpenSSL.crypto.X509}
  288. """
  289. def __init__(self, original):
  290. self.original = original
  291. def _copyName(self, suffix):
  292. dn = DistinguishedName()
  293. dn._copyFrom(getattr(self.original, "get_" + suffix)())
  294. return dn
  295. def getSubject(self):
  296. """
  297. Retrieve the subject of this certificate.
  298. @return: A copy of the subject of this certificate.
  299. @rtype: L{DistinguishedName}
  300. """
  301. return self._copyName("subject")
  302. def __conform__(self, interface):
  303. """
  304. Convert this L{CertBase} into a provider of the given interface.
  305. @param interface: The interface to conform to.
  306. @type interface: L{zope.interface.interfaces.IInterface}
  307. @return: an L{IOpenSSLTrustRoot} provider or L{NotImplemented}
  308. @rtype: L{IOpenSSLTrustRoot} or L{NotImplemented}
  309. """
  310. if interface is IOpenSSLTrustRoot:
  311. return OpenSSLCertificateAuthorities([self.original])
  312. return NotImplemented
  313. def _handleattrhelper(Class, transport, methodName):
  314. """
  315. (private) Helper for L{Certificate.peerFromTransport} and
  316. L{Certificate.hostFromTransport} which checks for incompatible handle types
  317. and null certificates and raises the appropriate exception or returns the
  318. appropriate certificate object.
  319. """
  320. method = getattr(transport.getHandle(), f"get_{methodName}_certificate", None)
  321. if method is None:
  322. raise CertificateError(
  323. "non-TLS transport {!r} did not have {} certificate".format(
  324. transport, methodName
  325. )
  326. )
  327. cert = method()
  328. if cert is None:
  329. raise CertificateError(
  330. "TLS transport {!r} did not have {} certificate".format(
  331. transport, methodName
  332. )
  333. )
  334. return Class(cert)
  335. class Certificate(CertBase):
  336. """
  337. An x509 certificate.
  338. """
  339. def __repr__(self) -> str:
  340. return "<{} Subject={} Issuer={}>".format(
  341. self.__class__.__name__,
  342. self.getSubject().get("commonName", ""),
  343. self.getIssuer().get("commonName", ""),
  344. )
  345. def __eq__(self, other: object) -> bool:
  346. if isinstance(other, Certificate):
  347. return self.dump() == other.dump()
  348. return NotImplemented
  349. @classmethod
  350. def load(Class, requestData, format=crypto.FILETYPE_ASN1, args=()):
  351. """
  352. Load a certificate from an ASN.1- or PEM-format string.
  353. @rtype: C{Class}
  354. """
  355. return Class(crypto.load_certificate(format, requestData), *args)
  356. # We can't use super() because it is old style still, so we have to hack
  357. # around things wanting to call the parent function
  358. _load = load
  359. def dumpPEM(self):
  360. """
  361. Dump this certificate to a PEM-format data string.
  362. @rtype: L{str}
  363. """
  364. return self.dump(crypto.FILETYPE_PEM)
  365. @classmethod
  366. def loadPEM(Class, data):
  367. """
  368. Load a certificate from a PEM-format data string.
  369. @rtype: C{Class}
  370. """
  371. return Class.load(data, crypto.FILETYPE_PEM)
  372. @classmethod
  373. def peerFromTransport(Class, transport):
  374. """
  375. Get the certificate for the remote end of the given transport.
  376. @param transport: an L{ISystemHandle} provider
  377. @rtype: C{Class}
  378. @raise CertificateError: if the given transport does not have a peer
  379. certificate.
  380. """
  381. return _handleattrhelper(Class, transport, "peer")
  382. @classmethod
  383. def hostFromTransport(Class, transport):
  384. """
  385. Get the certificate for the local end of the given transport.
  386. @param transport: an L{ISystemHandle} provider; the transport we will
  387. @rtype: C{Class}
  388. @raise CertificateError: if the given transport does not have a host
  389. certificate.
  390. """
  391. return _handleattrhelper(Class, transport, "host")
  392. def getPublicKey(self):
  393. """
  394. Get the public key for this certificate.
  395. @rtype: L{PublicKey}
  396. """
  397. return PublicKey(self.original.get_pubkey())
  398. def dump(self, format: int = crypto.FILETYPE_ASN1) -> bytes:
  399. return crypto.dump_certificate(format, self.original)
  400. def serialNumber(self):
  401. """
  402. Retrieve the serial number of this certificate.
  403. @rtype: L{int}
  404. """
  405. return self.original.get_serial_number()
  406. def digest(self, method="md5"):
  407. """
  408. Return a digest hash of this certificate using the specified hash
  409. algorithm.
  410. @param method: One of C{'md5'} or C{'sha'}.
  411. @return: The digest of the object, formatted as b":"-delimited hex
  412. pairs
  413. @rtype: L{bytes}
  414. """
  415. return self.original.digest(method)
  416. def _inspect(self):
  417. return "\n".join(
  418. [
  419. "Certificate For Subject:",
  420. self.getSubject().inspect(),
  421. "\nIssuer:",
  422. self.getIssuer().inspect(),
  423. "\nSerial Number: %d" % self.serialNumber(),
  424. "Digest: %s" % nativeString(self.digest()),
  425. ]
  426. )
  427. def inspect(self):
  428. """
  429. Return a multi-line, human-readable representation of this
  430. Certificate, including information about the subject, issuer, and
  431. public key.
  432. """
  433. return "\n".join((self._inspect(), self.getPublicKey().inspect()))
  434. def getIssuer(self):
  435. """
  436. Retrieve the issuer of this certificate.
  437. @rtype: L{DistinguishedName}
  438. @return: A copy of the issuer of this certificate.
  439. """
  440. return self._copyName("issuer")
  441. def options(self, *authorities):
  442. raise NotImplementedError("Possible, but doubtful we need this yet")
  443. class CertificateRequest(CertBase):
  444. """
  445. An x509 certificate request.
  446. Certificate requests are given to certificate authorities to be signed and
  447. returned resulting in an actual certificate.
  448. """
  449. @classmethod
  450. def load(Class, requestData, requestFormat=crypto.FILETYPE_ASN1):
  451. req = crypto.load_certificate_request(requestFormat, requestData)
  452. dn = DistinguishedName()
  453. dn._copyFrom(req.get_subject())
  454. if not req.verify(req.get_pubkey()):
  455. raise VerifyError(f"Can't verify that request for {dn!r} is self-signed.")
  456. return Class(req)
  457. def dump(self, format=crypto.FILETYPE_ASN1):
  458. return crypto.dump_certificate_request(format, self.original)
  459. class PrivateCertificate(Certificate):
  460. """
  461. An x509 certificate and private key.
  462. """
  463. def __repr__(self) -> str:
  464. return Certificate.__repr__(self) + " with " + repr(self.privateKey)
  465. def _setPrivateKey(self, privateKey):
  466. if not privateKey.matches(self.getPublicKey()):
  467. raise VerifyError("Certificate public and private keys do not match.")
  468. self.privateKey = privateKey
  469. return self
  470. def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
  471. """
  472. Create a new L{PrivateCertificate} from the given certificate data and
  473. this instance's private key.
  474. """
  475. return self.load(newCertData, self.privateKey, format)
  476. @classmethod
  477. def load(Class, data, privateKey, format=crypto.FILETYPE_ASN1):
  478. return Class._load(data, format)._setPrivateKey(privateKey)
  479. def inspect(self):
  480. return "\n".join([Certificate._inspect(self), self.privateKey.inspect()])
  481. def dumpPEM(self):
  482. """
  483. Dump both public and private parts of a private certificate to
  484. PEM-format data.
  485. """
  486. return self.dump(crypto.FILETYPE_PEM) + self.privateKey.dump(
  487. crypto.FILETYPE_PEM
  488. )
  489. @classmethod
  490. def loadPEM(Class, data):
  491. """
  492. Load both private and public parts of a private certificate from a
  493. chunk of PEM-format data.
  494. """
  495. return Class.load(
  496. data, KeyPair.load(data, crypto.FILETYPE_PEM), crypto.FILETYPE_PEM
  497. )
  498. @classmethod
  499. def fromCertificateAndKeyPair(Class, certificateInstance, privateKey):
  500. privcert = Class(certificateInstance.original)
  501. return privcert._setPrivateKey(privateKey)
  502. def options(self, *authorities):
  503. """
  504. Create a context factory using this L{PrivateCertificate}'s certificate
  505. and private key.
  506. @param authorities: A list of L{Certificate} object
  507. @return: A context factory.
  508. @rtype: L{CertificateOptions <twisted.internet.ssl.CertificateOptions>}
  509. """
  510. options = dict(privateKey=self.privateKey.original, certificate=self.original)
  511. if authorities:
  512. options.update(
  513. dict(
  514. trustRoot=OpenSSLCertificateAuthorities(
  515. [auth.original for auth in authorities]
  516. )
  517. )
  518. )
  519. return OpenSSLCertificateOptions(**options)
  520. def certificateRequest(self, format=crypto.FILETYPE_ASN1, digestAlgorithm="sha256"):
  521. return self.privateKey.certificateRequest(
  522. self.getSubject(), format, digestAlgorithm
  523. )
  524. def signCertificateRequest(
  525. self,
  526. requestData,
  527. verifyDNCallback,
  528. serialNumber,
  529. requestFormat=crypto.FILETYPE_ASN1,
  530. certificateFormat=crypto.FILETYPE_ASN1,
  531. ):
  532. issuer = self.getSubject()
  533. return self.privateKey.signCertificateRequest(
  534. issuer,
  535. requestData,
  536. verifyDNCallback,
  537. serialNumber,
  538. requestFormat,
  539. certificateFormat,
  540. )
  541. def signRequestObject(
  542. self,
  543. certificateRequest,
  544. serialNumber,
  545. secondsToExpiry=60 * 60 * 24 * 365, # One year
  546. digestAlgorithm="sha256",
  547. ):
  548. return self.privateKey.signRequestObject(
  549. self.getSubject(),
  550. certificateRequest,
  551. serialNumber,
  552. secondsToExpiry,
  553. digestAlgorithm,
  554. )
  555. class PublicKey:
  556. """
  557. A L{PublicKey} is a representation of the public part of a key pair.
  558. You can't do a whole lot with it aside from comparing it to other
  559. L{PublicKey} objects.
  560. @note: If constructing a L{PublicKey} manually, be sure to pass only a
  561. L{OpenSSL.crypto.PKey} that does not contain a private key!
  562. @ivar original: The original private key.
  563. """
  564. def __init__(self, osslpkey):
  565. """
  566. @param osslpkey: The underlying pyOpenSSL key object.
  567. @type osslpkey: L{OpenSSL.crypto.PKey}
  568. """
  569. self.original = osslpkey
  570. def matches(self, otherKey):
  571. """
  572. Does this L{PublicKey} contain the same value as another L{PublicKey}?
  573. @param otherKey: The key to compare C{self} to.
  574. @type otherKey: L{PublicKey}
  575. @return: L{True} if these keys match, L{False} if not.
  576. @rtype: L{bool}
  577. """
  578. return self.keyHash() == otherKey.keyHash()
  579. def __repr__(self) -> str:
  580. return f"<{self.__class__.__name__} {self.keyHash()}>"
  581. def keyHash(self):
  582. """
  583. Compute a hash of the underlying PKey object.
  584. The purpose of this method is to allow you to determine if two
  585. certificates share the same public key; it is not really useful for
  586. anything else.
  587. In versions of Twisted prior to 15.0, C{keyHash} used a technique
  588. involving certificate requests for computing the hash that was not
  589. stable in the face of changes to the underlying OpenSSL library.
  590. @return: Return a 32-character hexadecimal string uniquely identifying
  591. this public key, I{for this version of Twisted}.
  592. @rtype: native L{str}
  593. """
  594. raw = crypto.dump_publickey(crypto.FILETYPE_ASN1, self.original)
  595. h = md5()
  596. h.update(raw)
  597. return h.hexdigest()
  598. def inspect(self):
  599. return f"Public Key with Hash: {self.keyHash()}"
  600. class KeyPair(PublicKey):
  601. @classmethod
  602. def load(Class, data, format=crypto.FILETYPE_ASN1):
  603. return Class(crypto.load_privatekey(format, data))
  604. def dump(self, format=crypto.FILETYPE_ASN1):
  605. return crypto.dump_privatekey(format, self.original)
  606. @deprecated(Version("Twisted", 15, 0, 0), "a real persistence system")
  607. def __getstate__(self):
  608. return self.dump()
  609. @deprecated(Version("Twisted", 15, 0, 0), "a real persistence system")
  610. def __setstate__(self, state):
  611. self.__init__(crypto.load_privatekey(crypto.FILETYPE_ASN1, state))
  612. def inspect(self):
  613. t = self.original.type()
  614. if t == crypto.TYPE_RSA:
  615. ts = "RSA"
  616. elif t == crypto.TYPE_DSA:
  617. ts = "DSA"
  618. else:
  619. ts = "(Unknown Type!)"
  620. L = (self.original.bits(), ts, self.keyHash())
  621. return "%s-bit %s Key Pair with Hash: %s" % L
  622. @classmethod
  623. def generate(Class, kind=crypto.TYPE_RSA, size=2048):
  624. pkey = crypto.PKey()
  625. pkey.generate_key(kind, size)
  626. return Class(pkey)
  627. def newCertificate(self, newCertData, format=crypto.FILETYPE_ASN1):
  628. return PrivateCertificate.load(newCertData, self, format)
  629. def requestObject(self, distinguishedName, digestAlgorithm="sha256"):
  630. req = crypto.X509Req()
  631. req.set_pubkey(self.original)
  632. distinguishedName._copyInto(req.get_subject())
  633. req.sign(self.original, digestAlgorithm)
  634. return CertificateRequest(req)
  635. def certificateRequest(
  636. self, distinguishedName, format=crypto.FILETYPE_ASN1, digestAlgorithm="sha256"
  637. ):
  638. """
  639. Create a certificate request signed with this key.
  640. @return: a string, formatted according to the 'format' argument.
  641. """
  642. return self.requestObject(distinguishedName, digestAlgorithm).dump(format)
  643. def signCertificateRequest(
  644. self,
  645. issuerDistinguishedName,
  646. requestData,
  647. verifyDNCallback,
  648. serialNumber,
  649. requestFormat=crypto.FILETYPE_ASN1,
  650. certificateFormat=crypto.FILETYPE_ASN1,
  651. secondsToExpiry=60 * 60 * 24 * 365, # One year
  652. digestAlgorithm="sha256",
  653. ):
  654. """
  655. Given a blob of certificate request data and a certificate authority's
  656. DistinguishedName, return a blob of signed certificate data.
  657. If verifyDNCallback returns a Deferred, I will return a Deferred which
  658. fires the data when that Deferred has completed.
  659. """
  660. hlreq = CertificateRequest.load(requestData, requestFormat)
  661. dn = hlreq.getSubject()
  662. vval = verifyDNCallback(dn)
  663. def verified(value):
  664. if not value:
  665. raise VerifyError(
  666. "DN callback {!r} rejected request DN {!r}".format(
  667. verifyDNCallback, dn
  668. )
  669. )
  670. return self.signRequestObject(
  671. issuerDistinguishedName,
  672. hlreq,
  673. serialNumber,
  674. secondsToExpiry,
  675. digestAlgorithm,
  676. ).dump(certificateFormat)
  677. if isinstance(vval, Deferred):
  678. return vval.addCallback(verified)
  679. else:
  680. return verified(vval)
  681. def signRequestObject(
  682. self,
  683. issuerDistinguishedName,
  684. requestObject,
  685. serialNumber,
  686. secondsToExpiry=60 * 60 * 24 * 365, # One year
  687. digestAlgorithm="sha256",
  688. ):
  689. """
  690. Sign a CertificateRequest instance, returning a Certificate instance.
  691. """
  692. req = requestObject.original
  693. cert = crypto.X509()
  694. issuerDistinguishedName._copyInto(cert.get_issuer())
  695. cert.set_subject(req.get_subject())
  696. cert.set_pubkey(req.get_pubkey())
  697. cert.gmtime_adj_notBefore(0)
  698. cert.gmtime_adj_notAfter(secondsToExpiry)
  699. cert.set_serial_number(serialNumber)
  700. cert.sign(self.original, digestAlgorithm)
  701. return Certificate(cert)
  702. def selfSignedCert(self, serialNumber, **kw):
  703. dn = DN(**kw)
  704. return PrivateCertificate.fromCertificateAndKeyPair(
  705. self.signRequestObject(dn, self.requestObject(dn), serialNumber), self
  706. )
  707. class IOpenSSLTrustRoot(Interface):
  708. """
  709. Trust settings for an OpenSSL context.
  710. Note that this interface's methods are private, so things outside of
  711. Twisted shouldn't implement it.
  712. """
  713. def _addCACertsToContext(context):
  714. """
  715. Add certificate-authority certificates to an SSL context whose
  716. connections should trust those authorities.
  717. @param context: An SSL context for a connection which should be
  718. verified by some certificate authority.
  719. @type context: L{OpenSSL.SSL.Context}
  720. @return: L{None}
  721. """
  722. @implementer(IOpenSSLTrustRoot)
  723. class OpenSSLCertificateAuthorities:
  724. """
  725. Trust an explicitly specified set of certificates, represented by a list of
  726. L{OpenSSL.crypto.X509} objects.
  727. """
  728. def __init__(self, caCerts):
  729. """
  730. @param caCerts: The certificate authorities to trust when using this
  731. object as a C{trustRoot} for L{OpenSSLCertificateOptions}.
  732. @type caCerts: L{list} of L{OpenSSL.crypto.X509}
  733. """
  734. self._caCerts = caCerts
  735. def _addCACertsToContext(self, context):
  736. store = context.get_cert_store()
  737. for cert in self._caCerts:
  738. store.add_cert(cert)
  739. def trustRootFromCertificates(certificates):
  740. """
  741. Builds an object that trusts multiple root L{Certificate}s.
  742. When passed to L{optionsForClientTLS}, connections using those options will
  743. reject any server certificate not signed by at least one of the
  744. certificates in the `certificates` list.
  745. @since: 16.0
  746. @param certificates: All certificates which will be trusted.
  747. @type certificates: C{iterable} of L{CertBase}
  748. @rtype: L{IOpenSSLTrustRoot}
  749. @return: an object suitable for use as the trustRoot= keyword argument to
  750. L{optionsForClientTLS}
  751. """
  752. certs = []
  753. for cert in certificates:
  754. # PrivateCertificate or Certificate are both okay
  755. if isinstance(cert, CertBase):
  756. cert = cert.original
  757. else:
  758. raise TypeError(
  759. "certificates items must be twisted.internet.ssl.CertBase" " instances"
  760. )
  761. certs.append(cert)
  762. return OpenSSLCertificateAuthorities(certs)
  763. @implementer(IOpenSSLTrustRoot)
  764. class OpenSSLDefaultPaths:
  765. """
  766. Trust the set of default verify paths that OpenSSL was built with, as
  767. specified by U{SSL_CTX_set_default_verify_paths
  768. <https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_load_verify_locations.html>}.
  769. """
  770. def _addCACertsToContext(self, context):
  771. context.set_default_verify_paths()
  772. def platformTrust():
  773. """
  774. Attempt to discover a set of trusted certificate authority certificates
  775. (or, in other words: trust roots, or root certificates) whose trust is
  776. managed and updated by tools outside of Twisted.
  777. If you are writing any client-side TLS code with Twisted, you should use
  778. this as the C{trustRoot} argument to L{CertificateOptions
  779. <twisted.internet.ssl.CertificateOptions>}.
  780. The result of this function should be like the up-to-date list of
  781. certificates in a web browser. When developing code that uses
  782. C{platformTrust}, you can think of it that way. However, the choice of
  783. which certificate authorities to trust is never Twisted's responsibility.
  784. Unless you're writing a very unusual application or library, it's not your
  785. code's responsibility either. The user may use platform-specific tools for
  786. defining which server certificates should be trusted by programs using TLS.
  787. The purpose of using this API is to respect that decision as much as
  788. possible.
  789. This should be a set of trust settings most appropriate for I{client} TLS
  790. connections; i.e. those which need to verify a server's authenticity. You
  791. should probably use this by default for any client TLS connection that you
  792. create. For servers, however, client certificates are typically not
  793. verified; or, if they are, their verification will depend on a custom,
  794. application-specific certificate authority.
  795. @since: 14.0
  796. @note: Currently, L{platformTrust} depends entirely upon your OpenSSL build
  797. supporting a set of "L{default verify paths <OpenSSLDefaultPaths>}"
  798. which correspond to certificate authority trust roots. Unfortunately,
  799. whether this is true of your system is both outside of Twisted's
  800. control and difficult (if not impossible) for Twisted to detect
  801. automatically.
  802. Nevertheless, this ought to work as desired by default on:
  803. - Ubuntu Linux machines with the U{ca-certificates
  804. <https://launchpad.net/ubuntu/+source/ca-certificates>} package
  805. installed,
  806. - macOS when using the system-installed version of OpenSSL (i.e.
  807. I{not} one installed via MacPorts or Homebrew),
  808. - any build of OpenSSL which has had certificate authority
  809. certificates installed into its default verify paths (by default,
  810. C{/usr/local/ssl/certs} if you've built your own OpenSSL), or
  811. - any process where the C{SSL_CERT_FILE} environment variable is
  812. set to the path of a file containing your desired CA certificates
  813. bundle.
  814. Hopefully soon, this API will be updated to use more sophisticated
  815. trust-root discovery mechanisms. Until then, you can follow tickets in
  816. the Twisted tracker for progress on this implementation on U{Microsoft
  817. Windows <https://twistedmatrix.com/trac/ticket/6371>}, U{macOS
  818. <https://twistedmatrix.com/trac/ticket/6372>}, and U{a fallback for
  819. other platforms which do not have native trust management tools
  820. <https://twistedmatrix.com/trac/ticket/6934>}.
  821. @return: an appropriate trust settings object for your platform.
  822. @rtype: L{IOpenSSLTrustRoot}
  823. @raise NotImplementedError: if this platform is not yet supported by
  824. Twisted. At present, only OpenSSL is supported.
  825. """
  826. return OpenSSLDefaultPaths()
  827. def _tolerateErrors(wrapped):
  828. """
  829. Wrap up an C{info_callback} for pyOpenSSL so that if something goes wrong
  830. the error is immediately logged and the connection is dropped if possible.
  831. This wrapper exists because some versions of pyOpenSSL don't handle errors
  832. from callbacks at I{all}, and those which do write tracebacks directly to
  833. stderr rather than to a supplied logging system. This reports unexpected
  834. errors to the Twisted logging system.
  835. Also, this terminates the connection immediately if possible because if
  836. you've got bugs in your verification logic it's much safer to just give up.
  837. @param wrapped: A valid C{info_callback} for pyOpenSSL.
  838. @type wrapped: L{callable}
  839. @return: A valid C{info_callback} for pyOpenSSL that handles any errors in
  840. C{wrapped}.
  841. @rtype: L{callable}
  842. """
  843. def infoCallback(connection: SSL.Connection, where: int, ret: int) -> object:
  844. result = None
  845. with _log.failuresHandled("Error during info_callback") as op:
  846. result = wrapped(connection, where, ret)
  847. if (f := op.failure) is not None:
  848. connection.get_app_data().failVerification(f)
  849. return result
  850. return infoCallback
  851. @implementer(IOpenSSLClientConnectionCreator)
  852. class ClientTLSOptions:
  853. """
  854. Client creator for TLS.
  855. Private implementation type (not exposed to applications) for public
  856. L{optionsForClientTLS} API.
  857. @ivar _ctx: The context to use for new connections.
  858. @type _ctx: L{OpenSSL.SSL.Context}
  859. @ivar _hostname: The hostname to verify, as specified by the application,
  860. as some human-readable text.
  861. @type _hostname: L{unicode}
  862. @ivar _hostnameBytes: The hostname to verify, decoded into IDNA-encoded
  863. bytes. This is passed to APIs which think that hostnames are bytes,
  864. such as OpenSSL's SNI implementation.
  865. @type _hostnameBytes: L{bytes}
  866. @ivar _hostnameASCII: The hostname, as transcoded into IDNA ASCII-range
  867. unicode code points. This is pre-transcoded because the
  868. C{service_identity} package is rather strict about requiring the
  869. C{idna} package from PyPI for internationalized domain names, rather
  870. than working with Python's built-in (but sometimes broken) IDNA
  871. encoding. ASCII values, however, will always work.
  872. @type _hostnameASCII: L{unicode}
  873. @ivar _hostnameIsDnsName: Whether or not the C{_hostname} is a DNSName.
  874. Will be L{False} if C{_hostname} is an IP address or L{True} if
  875. C{_hostname} is a DNSName
  876. @type _hostnameIsDnsName: L{bool}
  877. """
  878. def __init__(self, hostname, ctx):
  879. """
  880. Initialize L{ClientTLSOptions}.
  881. @param hostname: The hostname to verify as input by a human.
  882. @type hostname: L{unicode}
  883. @param ctx: an L{OpenSSL.SSL.Context} to use for new connections.
  884. @type ctx: L{OpenSSL.SSL.Context}.
  885. """
  886. self._ctx = ctx
  887. self._hostname = hostname
  888. if isIPAddress(hostname) or isIPv6Address(hostname):
  889. self._hostnameBytes = hostname.encode("ascii")
  890. self._hostnameIsDnsName = False
  891. else:
  892. self._hostnameBytes = _idnaBytes(hostname)
  893. self._hostnameIsDnsName = True
  894. self._hostnameASCII = self._hostnameBytes.decode("ascii")
  895. ctx.set_info_callback(_tolerateErrors(self._identityVerifyingInfoCallback))
  896. def clientConnectionForTLS(self, tlsProtocol):
  897. """
  898. Create a TLS connection for a client.
  899. @note: This will call C{set_app_data} on its connection. If you're
  900. delegating to this implementation of this method, don't ever call
  901. C{set_app_data} or C{set_info_callback} on the returned connection,
  902. or you'll break the implementation of various features of this
  903. class.
  904. @param tlsProtocol: the TLS protocol initiating the connection.
  905. @type tlsProtocol: L{twisted.protocols.tls.TLSMemoryBIOProtocol}
  906. @return: the configured client connection.
  907. @rtype: L{OpenSSL.SSL.Connection}
  908. """
  909. context = self._ctx
  910. connection = SSL.Connection(context, None)
  911. connection.set_app_data(tlsProtocol)
  912. return connection
  913. def _identityVerifyingInfoCallback(self, connection, where, ret):
  914. """
  915. U{info_callback
  916. <http://pythonhosted.org/pyOpenSSL/api/ssl.html#OpenSSL.SSL.Context.set_info_callback>
  917. } for pyOpenSSL that verifies the hostname in the presented certificate
  918. matches the one passed to this L{ClientTLSOptions}.
  919. @param connection: the connection which is handshaking.
  920. @type connection: L{OpenSSL.SSL.Connection}
  921. @param where: flags indicating progress through a TLS handshake.
  922. @type where: L{int}
  923. @param ret: ignored
  924. @type ret: ignored
  925. """
  926. # Literal IPv4 and IPv6 addresses are not permitted
  927. # as host names according to the RFCs
  928. if where & SSL.SSL_CB_HANDSHAKE_START and self._hostnameIsDnsName:
  929. connection.set_tlsext_host_name(self._hostnameBytes)
  930. elif where & SSL.SSL_CB_HANDSHAKE_DONE:
  931. try:
  932. if self._hostnameIsDnsName:
  933. verifyHostname(connection, self._hostnameASCII)
  934. else:
  935. verifyIPAddress(connection, self._hostnameASCII)
  936. except VerificationError:
  937. f = Failure()
  938. transport = connection.get_app_data()
  939. transport.failVerification(f)
  940. def optionsForClientTLS(
  941. hostname,
  942. trustRoot=None,
  943. clientCertificate=None,
  944. acceptableProtocols=None,
  945. *,
  946. extraCertificateOptions=None,
  947. ):
  948. """
  949. Create a L{client connection creator <IOpenSSLClientConnectionCreator>} for
  950. use with APIs such as L{SSL4ClientEndpoint
  951. <twisted.internet.endpoints.SSL4ClientEndpoint>}, L{connectSSL
  952. <twisted.internet.interfaces.IReactorSSL.connectSSL>}, and L{startTLS
  953. <twisted.internet.interfaces.ITLSTransport.startTLS>}.
  954. @since: 14.0
  955. @param hostname: The expected name of the remote host. This serves two
  956. purposes: first, and most importantly, it verifies that the certificate
  957. received from the server correctly identifies the specified hostname.
  958. The second purpose is to use the U{Server Name Indication extension
  959. <https://en.wikipedia.org/wiki/Server_Name_Indication>} to indicate to
  960. the server which certificate should be used.
  961. @type hostname: L{unicode}
  962. @param trustRoot: Specification of trust requirements of peers. This may be
  963. a L{Certificate} or the result of L{platformTrust}. By default it is
  964. L{platformTrust} and you probably shouldn't adjust it unless you really
  965. know what you're doing. Be aware that clients using this interface
  966. I{must} verify the server; you cannot explicitly pass L{None} since
  967. that just means to use L{platformTrust}.
  968. @type trustRoot: L{IOpenSSLTrustRoot}
  969. @param clientCertificate: The certificate and private key that the client
  970. will use to authenticate to the server. If unspecified, the client will
  971. not authenticate.
  972. @type clientCertificate: L{PrivateCertificate}
  973. @param acceptableProtocols: The protocols this peer is willing to speak
  974. after the TLS negotiation has completed, advertised over both ALPN and
  975. NPN. If this argument is specified, and no overlap can be found with
  976. the other peer, the connection will fail to be established. If the
  977. remote peer does not offer NPN or ALPN, the connection will be
  978. established, but no protocol wil be negotiated. Protocols earlier in
  979. the list are preferred over those later in the list.
  980. @type acceptableProtocols: L{list} of L{bytes}
  981. @param extraCertificateOptions: A dictionary of additional keyword arguments
  982. to be presented to L{CertificateOptions}. Please avoid using this unless
  983. you absolutely need to; any time you need to pass an option here that is
  984. a bug in this interface.
  985. @type extraCertificateOptions: L{dict}
  986. @return: A client connection creator.
  987. @rtype: L{IOpenSSLClientConnectionCreator}
  988. """
  989. if extraCertificateOptions is None:
  990. extraCertificateOptions = {}
  991. if trustRoot is None:
  992. trustRoot = platformTrust()
  993. if not isinstance(hostname, str):
  994. raise TypeError(
  995. "optionsForClientTLS requires text for host names, not "
  996. + hostname.__class__.__name__
  997. )
  998. if clientCertificate:
  999. extraCertificateOptions.update(
  1000. privateKey=clientCertificate.privateKey.original,
  1001. certificate=clientCertificate.original,
  1002. )
  1003. certificateOptions = OpenSSLCertificateOptions(
  1004. trustRoot=trustRoot,
  1005. acceptableProtocols=acceptableProtocols,
  1006. **extraCertificateOptions,
  1007. )
  1008. return ClientTLSOptions(hostname, certificateOptions.getContext())
  1009. @implementer(IOpenSSLContextFactory)
  1010. class OpenSSLCertificateOptions:
  1011. """
  1012. A L{CertificateOptions <twisted.internet.ssl.CertificateOptions>} specifies
  1013. the security properties for a client or server TLS connection used with
  1014. OpenSSL.
  1015. @ivar _options: Any option flags to set on the L{OpenSSL.SSL.Context}
  1016. object that will be created.
  1017. @type _options: L{int}
  1018. @ivar _cipherString: An OpenSSL-specific cipher string.
  1019. @type _cipherString: L{unicode}
  1020. @ivar _defaultMinimumTLSVersion: The default TLS version that will be
  1021. negotiated. This should be a "safe default", with wide client and
  1022. server support, vs an optimally secure one that excludes a large number
  1023. of users. As of May 2022, TLSv1.2 is that safe default.
  1024. @type _defaultMinimumTLSVersion: L{TLSVersion} constant
  1025. """
  1026. # Factory for creating contexts. Configurable for testability.
  1027. _contextFactory = SSL.Context
  1028. _context = None
  1029. _OP_NO_TLSv1_3 = _tlsDisableFlags[TLSVersion.TLSv1_3]
  1030. _defaultMinimumTLSVersion = TLSVersion.TLSv1_2
  1031. @_mutuallyExclusiveArguments(
  1032. [
  1033. ["trustRoot", "requireCertificate"],
  1034. ["trustRoot", "verify"],
  1035. ["trustRoot", "caCerts"],
  1036. ["method", "insecurelyLowerMinimumTo"],
  1037. ["method", "raiseMinimumTo"],
  1038. ["raiseMinimumTo", "insecurelyLowerMinimumTo"],
  1039. ["method", "lowerMaximumSecurityTo"],
  1040. ]
  1041. )
  1042. def __init__(
  1043. self,
  1044. privateKey=None,
  1045. certificate=None,
  1046. method=None,
  1047. verify=False,
  1048. caCerts=None,
  1049. verifyDepth=9,
  1050. requireCertificate=True,
  1051. verifyOnce=True,
  1052. enableSingleUseKeys=True,
  1053. enableSessions=False,
  1054. fixBrokenPeers=False,
  1055. enableSessionTickets=False,
  1056. extraCertChain=None,
  1057. acceptableCiphers=None,
  1058. dhParameters=None,
  1059. trustRoot=None,
  1060. acceptableProtocols=None,
  1061. raiseMinimumTo=None,
  1062. insecurelyLowerMinimumTo=None,
  1063. lowerMaximumSecurityTo=None,
  1064. ):
  1065. """
  1066. Create an OpenSSL context SSL connection context factory.
  1067. @param privateKey: A PKey object holding the private key.
  1068. @param certificate: An X509 object holding the certificate.
  1069. @param method: Deprecated, use a combination of
  1070. C{insecurelyLowerMinimumTo}, C{raiseMinimumTo}, or
  1071. C{lowerMaximumSecurityTo} instead. The SSL protocol to use, one of
  1072. C{TLS_METHOD}, C{TLSv1_2_METHOD}, or C{TLSv1_2_METHOD} (or any
  1073. future method constants provided by pyOpenSSL). By default, a
  1074. setting will be used which allows TLSv1.2 and TLSv1.3. Can not be
  1075. used with C{insecurelyLowerMinimumTo}, C{raiseMinimumTo}, or
  1076. C{lowerMaximumSecurityTo}.
  1077. @param verify: Please use a C{trustRoot} keyword argument instead,
  1078. since it provides the same functionality in a less error-prone way.
  1079. By default this is L{False}.
  1080. If L{True}, verify certificates received from the peer and fail the
  1081. handshake if verification fails. Otherwise, allow anonymous
  1082. sessions and sessions with certificates which fail validation.
  1083. @param caCerts: Please use a C{trustRoot} keyword argument instead,
  1084. since it provides the same functionality in a less error-prone way.
  1085. List of certificate authority certificate objects to use to verify
  1086. the peer's certificate. Only used if verify is L{True} and will be
  1087. ignored otherwise. Since verify is L{False} by default, this is
  1088. L{None} by default.
  1089. @type caCerts: L{list} of L{OpenSSL.crypto.X509}
  1090. @param verifyDepth: Depth in certificate chain down to which to verify.
  1091. If unspecified, use the underlying default (9).
  1092. @param requireCertificate: Please use a C{trustRoot} keyword argument
  1093. instead, since it provides the same functionality in a less
  1094. error-prone way.
  1095. If L{True}, do not allow anonymous sessions; defaults to L{True}.
  1096. @param verifyOnce: If True, do not re-verify the certificate on session
  1097. resumption.
  1098. @param enableSingleUseKeys: If L{True}, generate a new key whenever
  1099. ephemeral DH and ECDH parameters are used to prevent small subgroup
  1100. attacks and to ensure perfect forward secrecy.
  1101. @param enableSessions: This allows a shortened handshake to be used
  1102. when a known client reconnects to the same process. If True,
  1103. enable OpenSSL's session caching. Note that session caching only
  1104. works on a single Twisted node at once. Also, it is currently
  1105. somewhat risky due to U{a crashing bug when using OpenSSL 1.1.1
  1106. <https://twistedmatrix.com/trac/ticket/9764>}.
  1107. @param fixBrokenPeers: If True, enable various non-spec protocol fixes
  1108. for broken SSL implementations. This should be entirely safe,
  1109. according to the OpenSSL documentation, but YMMV. This option is
  1110. now off by default, because it causes problems with connections
  1111. between peers using OpenSSL 0.9.8a.
  1112. @param enableSessionTickets: If L{True}, enable session ticket
  1113. extension for session resumption per RFC 5077. Note there is no
  1114. support for controlling session tickets. This option is off by
  1115. default, as some server implementations don't correctly process
  1116. incoming empty session ticket extensions in the hello.
  1117. @param extraCertChain: List of certificates that I{complete} your
  1118. verification chain if the certificate authority that signed your
  1119. C{certificate} isn't widely supported. Do I{not} add
  1120. C{certificate} to it.
  1121. @type extraCertChain: C{list} of L{OpenSSL.crypto.X509}
  1122. @param acceptableCiphers: Ciphers that are acceptable for connections.
  1123. Uses a secure default if left L{None}.
  1124. @type acceptableCiphers: L{IAcceptableCiphers}
  1125. @param dhParameters: Key generation parameters that are required for
  1126. Diffie-Hellman key exchange. If this argument is left L{None},
  1127. C{EDH} ciphers are I{disabled} regardless of C{acceptableCiphers}.
  1128. @type dhParameters: L{DiffieHellmanParameters
  1129. <twisted.internet.ssl.DiffieHellmanParameters>}
  1130. @param trustRoot: Specification of trust requirements of peers. If
  1131. this argument is specified, the peer is verified. It requires a
  1132. certificate, and that certificate must be signed by one of the
  1133. certificate authorities specified by this object.
  1134. Note that since this option specifies the same information as
  1135. C{caCerts}, C{verify}, and C{requireCertificate}, specifying any of
  1136. those options in combination with this one will raise a
  1137. L{TypeError}.
  1138. @type trustRoot: L{IOpenSSLTrustRoot}
  1139. @param acceptableProtocols: The protocols this peer is willing to speak
  1140. after the TLS negotiation has completed, advertised over both ALPN
  1141. and NPN. If this argument is specified, and no overlap can be
  1142. found with the other peer, the connection will fail to be
  1143. established. If the remote peer does not offer NPN or ALPN, the
  1144. connection will be established, but no protocol wil be negotiated.
  1145. Protocols earlier in the list are preferred over those later in the
  1146. list.
  1147. @type acceptableProtocols: L{list} of L{bytes}
  1148. @param raiseMinimumTo: The minimum TLS version that you want to use, or
  1149. Twisted's default if it is higher. Use this if you want to make
  1150. your client/server more secure than Twisted's default, but will
  1151. accept Twisted's default instead if it moves higher than this
  1152. value. You probably want to use this over
  1153. C{insecurelyLowerMinimumTo}.
  1154. @type raiseMinimumTo: L{TLSVersion} constant
  1155. @param insecurelyLowerMinimumTo: The minimum TLS version to use,
  1156. possibly lower than Twisted's default. If not specified, it is a
  1157. generally considered safe default (TLSv1.0). If you want to raise
  1158. your minimum TLS version to above that of this default, use
  1159. C{raiseMinimumTo}. DO NOT use this argument unless you are
  1160. absolutely sure this is what you want.
  1161. @type insecurelyLowerMinimumTo: L{TLSVersion} constant
  1162. @param lowerMaximumSecurityTo: The maximum TLS version to use. If not
  1163. specified, it is the most recent your OpenSSL supports. You only
  1164. want to set this if the peer that you are communicating with has
  1165. problems with more recent TLS versions, it lowers your security
  1166. when communicating with newer peers. DO NOT use this argument
  1167. unless you are absolutely sure this is what you want.
  1168. @type lowerMaximumSecurityTo: L{TLSVersion} constant
  1169. @raise ValueError: when C{privateKey} or C{certificate} are set without
  1170. setting the respective other.
  1171. @raise ValueError: when C{verify} is L{True} but C{caCerts} doesn't
  1172. specify any CA certificates.
  1173. @raise ValueError: when C{extraCertChain} is passed without specifying
  1174. C{privateKey} or C{certificate}.
  1175. @raise ValueError: when C{acceptableCiphers} doesn't yield any usable
  1176. ciphers for the current platform.
  1177. @raise TypeError: if C{trustRoot} is passed in combination with
  1178. C{caCert}, C{verify}, or C{requireCertificate}. Please prefer
  1179. C{trustRoot} in new code, as its semantics are less tricky.
  1180. @raise TypeError: if C{method} is passed in combination with
  1181. C{tlsProtocols}. Please prefer the more explicit C{tlsProtocols}
  1182. in new code.
  1183. @raises NotImplementedError: If acceptableProtocols were provided but
  1184. no negotiation mechanism is available.
  1185. """
  1186. if (privateKey is None) != (certificate is None):
  1187. raise ValueError("Specify neither or both of privateKey and certificate")
  1188. self.privateKey = privateKey
  1189. self.certificate = certificate
  1190. # Set basic security options: disallow insecure SSLv2, disallow TLS
  1191. # compression to avoid CRIME attack, make the server choose the
  1192. # ciphers.
  1193. self._options = (
  1194. SSL.OP_NO_SSLv2 | SSL.OP_NO_COMPRESSION | SSL.OP_CIPHER_SERVER_PREFERENCE
  1195. )
  1196. # Set the mode to Release Buffers, which demallocs send/recv buffers on
  1197. # idle TLS connections to save memory
  1198. self._mode = SSL.MODE_RELEASE_BUFFERS
  1199. if method is None:
  1200. self.method = SSL.TLS_METHOD
  1201. if raiseMinimumTo:
  1202. if lowerMaximumSecurityTo and raiseMinimumTo > lowerMaximumSecurityTo:
  1203. raise ValueError(
  1204. "raiseMinimumTo needs to be lower than "
  1205. "lowerMaximumSecurityTo"
  1206. )
  1207. if raiseMinimumTo > self._defaultMinimumTLSVersion:
  1208. insecurelyLowerMinimumTo = raiseMinimumTo
  1209. if insecurelyLowerMinimumTo is None:
  1210. insecurelyLowerMinimumTo = self._defaultMinimumTLSVersion
  1211. # If you set the max lower than the default, but don't set the
  1212. # minimum, pull it down to that
  1213. if (
  1214. lowerMaximumSecurityTo
  1215. and insecurelyLowerMinimumTo > lowerMaximumSecurityTo
  1216. ):
  1217. insecurelyLowerMinimumTo = lowerMaximumSecurityTo
  1218. if (
  1219. lowerMaximumSecurityTo
  1220. and insecurelyLowerMinimumTo > lowerMaximumSecurityTo
  1221. ):
  1222. raise ValueError(
  1223. "insecurelyLowerMinimumTo needs to be lower than "
  1224. "lowerMaximumSecurityTo"
  1225. )
  1226. excludedVersions = _getExcludedTLSProtocols(
  1227. insecurelyLowerMinimumTo, lowerMaximumSecurityTo
  1228. )
  1229. for version in excludedVersions:
  1230. self._options |= _tlsDisableFlags[version]
  1231. else:
  1232. warnings.warn(
  1233. (
  1234. "Passing method to twisted.internet.ssl.CertificateOptions "
  1235. "was deprecated in Twisted 17.1.0. Please use a combination "
  1236. "of insecurelyLowerMinimumTo, raiseMinimumTo, and "
  1237. "lowerMaximumSecurityTo instead, as Twisted will correctly "
  1238. "configure the method."
  1239. ),
  1240. DeprecationWarning,
  1241. stacklevel=3,
  1242. )
  1243. # Otherwise respect the application decision.
  1244. self.method = method
  1245. if verify and not caCerts:
  1246. raise ValueError(
  1247. "Specify client CA certificate information if and"
  1248. " only if enabling certificate verification"
  1249. )
  1250. self.verify = verify
  1251. if extraCertChain is not None and None in (privateKey, certificate):
  1252. raise ValueError(
  1253. "A private key and a certificate are required "
  1254. "when adding a supplemental certificate chain."
  1255. )
  1256. if extraCertChain is not None:
  1257. self.extraCertChain = extraCertChain
  1258. else:
  1259. self.extraCertChain = []
  1260. self.caCerts = caCerts
  1261. self.verifyDepth = verifyDepth
  1262. self.requireCertificate = requireCertificate
  1263. self.verifyOnce = verifyOnce
  1264. self.enableSingleUseKeys = enableSingleUseKeys
  1265. if enableSingleUseKeys:
  1266. self._options |= SSL.OP_SINGLE_DH_USE | SSL.OP_SINGLE_ECDH_USE
  1267. self.enableSessions = enableSessions
  1268. self.fixBrokenPeers = fixBrokenPeers
  1269. if fixBrokenPeers:
  1270. self._options |= SSL.OP_ALL
  1271. self.enableSessionTickets = enableSessionTickets
  1272. if not enableSessionTickets:
  1273. self._options |= SSL.OP_NO_TICKET
  1274. self.dhParameters = dhParameters
  1275. self._ecChooser = _ChooseDiffieHellmanEllipticCurve(
  1276. SSL.OPENSSL_VERSION_NUMBER,
  1277. openSSLlib=pyOpenSSLlib,
  1278. openSSLcrypto=crypto,
  1279. )
  1280. if acceptableCiphers is None:
  1281. acceptableCiphers = defaultCiphers
  1282. # This needs to run when method and _options are finalized.
  1283. self._cipherString = ":".join(
  1284. c.fullName
  1285. for c in acceptableCiphers.selectCiphers(
  1286. _expandCipherString("ALL", self.method, self._options)
  1287. )
  1288. )
  1289. if self._cipherString == "":
  1290. raise ValueError(
  1291. "Supplied IAcceptableCiphers yielded no usable ciphers "
  1292. "on this platform."
  1293. )
  1294. if trustRoot is None:
  1295. if self.verify:
  1296. trustRoot = OpenSSLCertificateAuthorities(caCerts)
  1297. else:
  1298. self.verify = True
  1299. self.requireCertificate = True
  1300. trustRoot = IOpenSSLTrustRoot(trustRoot)
  1301. self.trustRoot = trustRoot
  1302. if acceptableProtocols is not None and not protocolNegotiationMechanisms():
  1303. raise NotImplementedError(
  1304. "No support for protocol negotiation on this platform."
  1305. )
  1306. self._acceptableProtocols = acceptableProtocols
  1307. def __getstate__(self):
  1308. d = self.__dict__.copy()
  1309. try:
  1310. del d["_context"]
  1311. except KeyError:
  1312. pass
  1313. return d
  1314. def __setstate__(self, state):
  1315. self.__dict__ = state
  1316. def getContext(self):
  1317. """
  1318. Return an L{OpenSSL.SSL.Context} object.
  1319. """
  1320. if self._context is None:
  1321. self._context = self._makeContext()
  1322. return self._context
  1323. def _makeContext(self):
  1324. ctx = self._contextFactory(self.method)
  1325. ctx.set_options(self._options)
  1326. ctx.set_mode(self._mode)
  1327. if self.certificate is not None and self.privateKey is not None:
  1328. ctx.use_certificate(self.certificate)
  1329. ctx.use_privatekey(self.privateKey)
  1330. for extraCert in self.extraCertChain:
  1331. ctx.add_extra_chain_cert(extraCert)
  1332. # Sanity check
  1333. ctx.check_privatekey()
  1334. verifyFlags = SSL.VERIFY_NONE
  1335. if self.verify:
  1336. verifyFlags = SSL.VERIFY_PEER
  1337. if self.requireCertificate:
  1338. verifyFlags |= SSL.VERIFY_FAIL_IF_NO_PEER_CERT
  1339. if self.verifyOnce:
  1340. verifyFlags |= SSL.VERIFY_CLIENT_ONCE
  1341. self.trustRoot._addCACertsToContext(ctx)
  1342. ctx.set_verify(verifyFlags)
  1343. if self.verifyDepth is not None:
  1344. ctx.set_verify_depth(self.verifyDepth)
  1345. # Until we know what's going on with
  1346. # https://twistedmatrix.com/trac/ticket/9764 let's be conservative
  1347. # in naming this; ASCII-only, short, as the recommended value (a
  1348. # hostname) might be:
  1349. sessionIDContext = hexlify(secureRandom(7))
  1350. # Note that this doesn't actually set the session ID (which had
  1351. # better be per-connection anyway!):
  1352. # https://github.com/pyca/pyopenssl/issues/845
  1353. # This is set unconditionally because it's apparently required for
  1354. # client certificates to work:
  1355. # https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_session_id_context.html
  1356. ctx.set_session_id(sessionIDContext)
  1357. if self.enableSessions:
  1358. ctx.set_session_cache_mode(SSL.SESS_CACHE_SERVER)
  1359. else:
  1360. ctx.set_session_cache_mode(SSL.SESS_CACHE_OFF)
  1361. if self.dhParameters:
  1362. ctx.load_tmp_dh(self.dhParameters._dhFile.path)
  1363. ctx.set_cipher_list(self._cipherString.encode("ascii"))
  1364. self._ecChooser.configureECDHCurve(ctx)
  1365. if self._acceptableProtocols:
  1366. # Try to set NPN and ALPN. _acceptableProtocols cannot be set by
  1367. # the constructor unless at least one mechanism is supported.
  1368. _setAcceptableProtocols(ctx, self._acceptableProtocols)
  1369. return ctx
  1370. OpenSSLCertificateOptions.__getstate__ = deprecated(
  1371. Version("Twisted", 15, 0, 0), "a real persistence system"
  1372. )(OpenSSLCertificateOptions.__getstate__)
  1373. OpenSSLCertificateOptions.__setstate__ = deprecated(
  1374. Version("Twisted", 15, 0, 0), "a real persistence system"
  1375. )(OpenSSLCertificateOptions.__setstate__)
  1376. @implementer(ICipher)
  1377. @attr.s(frozen=True, auto_attribs=True)
  1378. class OpenSSLCipher:
  1379. """
  1380. A representation of an OpenSSL cipher.
  1381. @ivar fullName: The full name of the cipher. For example
  1382. C{u"ECDHE-RSA-AES256-GCM-SHA384"}.
  1383. @type fullName: L{unicode}
  1384. """
  1385. fullName: str
  1386. @lru_cache(maxsize=32)
  1387. def _expandCipherString(cipherString, method, options):
  1388. """
  1389. Expand C{cipherString} according to C{method} and C{options} to a tuple of
  1390. explicit ciphers that are supported by the current platform.
  1391. @param cipherString: An OpenSSL cipher string to expand.
  1392. @type cipherString: L{unicode}
  1393. @param method: An OpenSSL method like C{SSL.TLS_METHOD} used for
  1394. determining the effective ciphers.
  1395. @param options: OpenSSL options like C{SSL.OP_NO_SSLv3} ORed together.
  1396. @type options: L{int}
  1397. @return: The effective list of explicit ciphers that results from the
  1398. arguments on the current platform.
  1399. @rtype: L{tuple} of L{ICipher}
  1400. """
  1401. ctx = SSL.Context(method)
  1402. ctx.set_options(options)
  1403. try:
  1404. ctx.set_cipher_list(cipherString.encode("ascii"))
  1405. except SSL.Error as e:
  1406. # OpenSSL 1.1.1 turns an invalid cipher list into TLS 1.3
  1407. # ciphers, so pyOpenSSL >= 19.0.0 raises an artificial Error
  1408. # that lacks a corresponding OpenSSL error if the cipher list
  1409. # consists only of these after a call to set_cipher_list.
  1410. if not e.args[0]:
  1411. return tuple()
  1412. if e.args[0][0][2] == "no cipher match":
  1413. return tuple()
  1414. else:
  1415. raise
  1416. conn = SSL.Connection(ctx, None)
  1417. ciphers = conn.get_cipher_list()
  1418. if isinstance(ciphers[0], str):
  1419. return tuple(OpenSSLCipher(cipher) for cipher in ciphers)
  1420. else:
  1421. return tuple(OpenSSLCipher(cipher.decode("ascii")) for cipher in ciphers)
  1422. @lru_cache(maxsize=128)
  1423. def _selectCiphers(wantedCiphers, availableCiphers):
  1424. """
  1425. Caclulate the acceptable list of ciphers from the ciphers we want and the
  1426. ciphers we have support for.
  1427. @param wantedCiphers: The ciphers we want to use.
  1428. @type wantedCiphers: L{tuple} of L{OpenSSLCipher}
  1429. @param availableCiphers: The ciphers we have available to use.
  1430. @type availableCiphers: L{tuple} of L{OpenSSLCipher}
  1431. @rtype: L{tuple} of L{OpenSSLCipher}
  1432. """
  1433. return tuple(cipher for cipher in wantedCiphers if cipher in availableCiphers)
  1434. @implementer(IAcceptableCiphers)
  1435. class OpenSSLAcceptableCiphers:
  1436. """
  1437. A representation of ciphers that are acceptable for TLS connections.
  1438. """
  1439. def __init__(self, ciphers):
  1440. self._ciphers = tuple(ciphers)
  1441. def selectCiphers(self, availableCiphers):
  1442. return _selectCiphers(self._ciphers, tuple(availableCiphers))
  1443. @classmethod
  1444. def fromOpenSSLCipherString(cls, cipherString):
  1445. """
  1446. Create a new instance using an OpenSSL cipher string.
  1447. @param cipherString: An OpenSSL cipher string that describes what
  1448. cipher suites are acceptable.
  1449. See the documentation of U{OpenSSL
  1450. <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_STRINGS>} or
  1451. U{Apache
  1452. <http://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslciphersuite>}
  1453. for details.
  1454. @type cipherString: L{unicode}
  1455. @return: Instance representing C{cipherString}.
  1456. @rtype: L{twisted.internet.ssl.AcceptableCiphers}
  1457. """
  1458. return cls(
  1459. _expandCipherString(
  1460. nativeString(cipherString),
  1461. SSL.TLS_METHOD,
  1462. SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3,
  1463. )
  1464. )
  1465. # A secure default.
  1466. # Sources for more information on TLS ciphers:
  1467. #
  1468. # - https://wiki.mozilla.org/Security/Server_Side_TLS
  1469. # - https://www.ssllabs.com/projects/best-practices/index.html
  1470. # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
  1471. #
  1472. # The general intent is:
  1473. # - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
  1474. # - prefer ECDHE over DHE for better performance,
  1475. # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
  1476. # security,
  1477. # - prefer AES-GCM to ChaCha20 because AES hardware support is common,
  1478. # - disable NULL authentication, MD5 MACs and DSS for security reasons.
  1479. #
  1480. defaultCiphers = OpenSSLAcceptableCiphers.fromOpenSSLCipherString(
  1481. "TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:"
  1482. "TLS13-AES-128-GCM-SHA256:"
  1483. "ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:"
  1484. "ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:"
  1485. "!aNULL:!MD5:!DSS"
  1486. )
  1487. _defaultCurveName = "prime256v1"
  1488. class _ChooseDiffieHellmanEllipticCurve:
  1489. """
  1490. Chooses the best elliptic curve for Elliptic Curve Diffie-Hellman
  1491. key exchange, and provides a C{configureECDHCurve} method to set
  1492. the curve, when appropriate, on a new L{OpenSSL.SSL.Context}.
  1493. The C{configureECDHCurve} method will be set to one of the
  1494. following based on the provided OpenSSL version and configuration:
  1495. - L{_configureOpenSSL110}
  1496. - L{_configureOpenSSL102}
  1497. - L{_configureOpenSSL101}
  1498. - L{_configureOpenSSL101NoCurves}.
  1499. @param openSSLVersion: The OpenSSL version number.
  1500. @type openSSLVersion: L{int}
  1501. @see: L{OpenSSL.SSL.OPENSSL_VERSION_NUMBER}
  1502. @param openSSLlib: The OpenSSL C{cffi} library module.
  1503. @param openSSLcrypto: The OpenSSL L{crypto} module.
  1504. @see: L{crypto}
  1505. """
  1506. def __init__(self, openSSLVersion, openSSLlib, openSSLcrypto):
  1507. self._openSSLlib = openSSLlib
  1508. self._openSSLcrypto = openSSLcrypto
  1509. if openSSLVersion >= 0x10100000:
  1510. self.configureECDHCurve = self._configureOpenSSL110
  1511. elif openSSLVersion >= 0x10002000:
  1512. self.configureECDHCurve = self._configureOpenSSL102
  1513. else:
  1514. try:
  1515. self._ecCurve = openSSLcrypto.get_elliptic_curve(_defaultCurveName)
  1516. except ValueError:
  1517. # The get_elliptic_curve method raises a ValueError
  1518. # when the curve does not exist.
  1519. self.configureECDHCurve = self._configureOpenSSL101NoCurves
  1520. else:
  1521. self.configureECDHCurve = self._configureOpenSSL101
  1522. def _configureOpenSSL110(self, ctx):
  1523. """
  1524. OpenSSL 1.1.0 Contexts are preconfigured with an optimal set
  1525. of ECDH curves. This method does nothing.
  1526. @param ctx: L{OpenSSL.SSL.Context}
  1527. """
  1528. def _configureOpenSSL102(self, ctx):
  1529. """
  1530. Have the context automatically choose elliptic curves for
  1531. ECDH. Run on OpenSSL 1.0.2 and OpenSSL 1.1.0+, but only has
  1532. an effect on OpenSSL 1.0.2.
  1533. @param ctx: The context which .
  1534. @type ctx: L{OpenSSL.SSL.Context}
  1535. """
  1536. ctxPtr = ctx._context
  1537. try:
  1538. self._openSSLlib.SSL_CTX_set_ecdh_auto(ctxPtr, True)
  1539. except BaseException:
  1540. pass
  1541. def _configureOpenSSL101(self, ctx):
  1542. """
  1543. Set the default elliptic curve for ECDH on the context. Only
  1544. run on OpenSSL 1.0.1.
  1545. @param ctx: The context on which to set the ECDH curve.
  1546. @type ctx: L{OpenSSL.SSL.Context}
  1547. """
  1548. try:
  1549. ctx.set_tmp_ecdh(self._ecCurve)
  1550. except BaseException:
  1551. pass
  1552. def _configureOpenSSL101NoCurves(self, ctx):
  1553. """
  1554. No elliptic curves are available on OpenSSL 1.0.1. We can't
  1555. set anything, so do nothing.
  1556. @param ctx: The context on which to set the ECDH curve.
  1557. @type ctx: L{OpenSSL.SSL.Context}
  1558. """
  1559. class OpenSSLDiffieHellmanParameters:
  1560. """
  1561. A representation of key generation parameters that are required for
  1562. Diffie-Hellman key exchange.
  1563. """
  1564. def __init__(self, parameters):
  1565. self._dhFile = parameters
  1566. @classmethod
  1567. def fromFile(cls, filePath):
  1568. """
  1569. Load parameters from a file.
  1570. Such a file can be generated using the C{openssl} command line tool as
  1571. following:
  1572. C{openssl dhparam -out dh_param_2048.pem -2 2048}
  1573. Please refer to U{OpenSSL's C{dhparam} documentation
  1574. <http://www.openssl.org/docs/apps/dhparam.html>} for further details.
  1575. @param filePath: A file containing parameters for Diffie-Hellman key
  1576. exchange.
  1577. @type filePath: L{FilePath <twisted.python.filepath.FilePath>}
  1578. @return: An instance that loads its parameters from C{filePath}.
  1579. @rtype: L{DiffieHellmanParameters
  1580. <twisted.internet.ssl.DiffieHellmanParameters>}
  1581. """
  1582. return cls(filePath)
  1583. def _setAcceptableProtocols(context, acceptableProtocols):
  1584. """
  1585. Called to set up the L{OpenSSL.SSL.Context} for doing NPN and/or ALPN
  1586. negotiation.
  1587. @param context: The context which is set up.
  1588. @type context: L{OpenSSL.SSL.Context}
  1589. @param acceptableProtocols: The protocols this peer is willing to speak
  1590. after the TLS negotiation has completed, advertised over both ALPN and
  1591. NPN. If this argument is specified, and no overlap can be found with
  1592. the other peer, the connection will fail to be established. If the
  1593. remote peer does not offer NPN or ALPN, the connection will be
  1594. established, but no protocol wil be negotiated. Protocols earlier in
  1595. the list are preferred over those later in the list.
  1596. @type acceptableProtocols: L{list} of L{bytes}
  1597. """
  1598. def protoSelectCallback(conn, protocols):
  1599. """
  1600. NPN client-side and ALPN server-side callback used to select
  1601. the next protocol. Prefers protocols found earlier in
  1602. C{_acceptableProtocols}.
  1603. @param conn: The context which is set up.
  1604. @type conn: L{OpenSSL.SSL.Connection}
  1605. @param conn: Protocols advertised by the other side.
  1606. @type conn: L{list} of L{bytes}
  1607. """
  1608. overlap = set(protocols) & set(acceptableProtocols)
  1609. for p in acceptableProtocols:
  1610. if p in overlap:
  1611. return p
  1612. else:
  1613. return b""
  1614. # If we don't actually have protocols to negotiate, don't set anything up.
  1615. # Depending on OpenSSL version, failing some of the selection callbacks can
  1616. # cause the handshake to fail, which is presumably not what was intended
  1617. # here.
  1618. if not acceptableProtocols:
  1619. return
  1620. supported = protocolNegotiationMechanisms()
  1621. if supported & ProtocolNegotiationSupport.NPN:
  1622. def npnAdvertiseCallback(conn):
  1623. return acceptableProtocols
  1624. context.set_npn_advertise_callback(npnAdvertiseCallback)
  1625. context.set_npn_select_callback(protoSelectCallback)
  1626. if supported & ProtocolNegotiationSupport.ALPN:
  1627. context.set_alpn_select_callback(protoSelectCallback)
  1628. context.set_alpn_protos(acceptableProtocols)