_sslverify.py 69 KB

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