Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_sslverify.py 71KB

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