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.

test_ssl.py 23KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for twisted SSL support.
  5. """
  6. import os
  7. import hamcrest
  8. from twisted.internet import defer, interfaces, protocol, reactor
  9. from twisted.internet.error import ConnectionDone
  10. from twisted.protocols import basic
  11. from twisted.python.filepath import FilePath
  12. from twisted.python.runtime import platform
  13. from twisted.test.proto_helpers import waitUntilAllDisconnected
  14. from twisted.test.test_tcp import ProperlyCloseFilesMixin
  15. from twisted.trial.unittest import TestCase
  16. try:
  17. from OpenSSL import SSL, crypto
  18. from twisted.internet import ssl
  19. from twisted.test.ssl_helpers import ClientTLSContext, certPath
  20. except ImportError:
  21. def _noSSL():
  22. # ugh, make pyflakes happy.
  23. global SSL
  24. global ssl
  25. SSL = ssl = None
  26. _noSSL()
  27. from zope.interface import implementer
  28. class UnintelligentProtocol(basic.LineReceiver):
  29. """
  30. @ivar deferred: a deferred that will fire at connection lost.
  31. @type deferred: L{defer.Deferred}
  32. @cvar pretext: text sent before TLS is set up.
  33. @type pretext: C{bytes}
  34. @cvar posttext: text sent after TLS is set up.
  35. @type posttext: C{bytes}
  36. """
  37. pretext = [b"first line", b"last thing before tls starts", b"STARTTLS"]
  38. posttext = [b"first thing after tls started", b"last thing ever"]
  39. def __init__(self):
  40. self.deferred = defer.Deferred()
  41. def connectionMade(self):
  42. for l in self.pretext:
  43. self.sendLine(l)
  44. def lineReceived(self, line):
  45. if line == b"READY":
  46. self.transport.startTLS(ClientTLSContext(), self.factory.client)
  47. for l in self.posttext:
  48. self.sendLine(l)
  49. self.transport.loseConnection()
  50. def connectionLost(self, reason):
  51. self.deferred.callback(None)
  52. class LineCollector(basic.LineReceiver):
  53. """
  54. @ivar deferred: a deferred that will fire at connection lost.
  55. @type deferred: L{defer.Deferred}
  56. @ivar doTLS: whether the protocol is initiate TLS or not.
  57. @type doTLS: C{bool}
  58. @ivar fillBuffer: if set to True, it will send lots of data once
  59. C{STARTTLS} is received.
  60. @type fillBuffer: C{bool}
  61. """
  62. def __init__(self, doTLS, fillBuffer=False):
  63. self.doTLS = doTLS
  64. self.fillBuffer = fillBuffer
  65. self.deferred = defer.Deferred()
  66. def connectionMade(self):
  67. self.factory.rawdata = b""
  68. self.factory.lines = []
  69. def lineReceived(self, line):
  70. self.factory.lines.append(line)
  71. if line == b"STARTTLS":
  72. if self.fillBuffer:
  73. for x in range(500):
  74. self.sendLine(b"X" * 1000)
  75. self.sendLine(b"READY")
  76. if self.doTLS:
  77. ctx = ServerTLSContext(
  78. privateKeyFileName=certPath,
  79. certificateFileName=certPath,
  80. )
  81. self.transport.startTLS(ctx, self.factory.server)
  82. else:
  83. self.setRawMode()
  84. def rawDataReceived(self, data):
  85. self.factory.rawdata += data
  86. self.transport.loseConnection()
  87. def connectionLost(self, reason):
  88. self.deferred.callback(None)
  89. class SingleLineServerProtocol(protocol.Protocol):
  90. """
  91. A protocol that sends a single line of data at C{connectionMade}.
  92. """
  93. def connectionMade(self):
  94. self.transport.write(b"+OK <some crap>\r\n")
  95. self.transport.getPeerCertificate()
  96. class RecordingClientProtocol(protocol.Protocol):
  97. """
  98. @ivar deferred: a deferred that will fire with first received content.
  99. @type deferred: L{defer.Deferred}
  100. """
  101. def __init__(self):
  102. self.deferred = defer.Deferred()
  103. def connectionMade(self):
  104. self.transport.getPeerCertificate()
  105. def dataReceived(self, data):
  106. self.deferred.callback(data)
  107. @implementer(interfaces.IHandshakeListener)
  108. class ImmediatelyDisconnectingProtocol(protocol.Protocol):
  109. """
  110. A protocol that disconnect immediately on connection. It fires the
  111. C{connectionDisconnected} deferred of its factory on connetion lost.
  112. """
  113. def handshakeCompleted(self):
  114. self.transport.loseConnection()
  115. def connectionLost(self, reason):
  116. self.factory.connectionDisconnected.callback(None)
  117. def generateCertificateObjects(organization, organizationalUnit):
  118. """
  119. Create a certificate for given C{organization} and C{organizationalUnit}.
  120. @return: a tuple of (key, request, certificate) objects.
  121. """
  122. pkey = crypto.PKey()
  123. pkey.generate_key(crypto.TYPE_RSA, 2048)
  124. req = crypto.X509Req()
  125. subject = req.get_subject()
  126. subject.O = organization
  127. subject.OU = organizationalUnit
  128. req.set_pubkey(pkey)
  129. req.sign(pkey, "md5")
  130. # Here comes the actual certificate
  131. cert = crypto.X509()
  132. cert.set_serial_number(1)
  133. cert.gmtime_adj_notBefore(0)
  134. cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
  135. cert.set_issuer(req.get_subject())
  136. cert.set_subject(req.get_subject())
  137. cert.set_pubkey(req.get_pubkey())
  138. cert.sign(pkey, "md5")
  139. return pkey, req, cert
  140. def generateCertificateFiles(basename, organization, organizationalUnit):
  141. """
  142. Create certificate files key, req and cert prefixed by C{basename} for
  143. given C{organization} and C{organizationalUnit}.
  144. """
  145. pkey, req, cert = generateCertificateObjects(organization, organizationalUnit)
  146. for ext, obj, dumpFunc in [
  147. ("key", pkey, crypto.dump_privatekey),
  148. ("req", req, crypto.dump_certificate_request),
  149. ("cert", cert, crypto.dump_certificate),
  150. ]:
  151. fName = os.extsep.join((basename, ext)).encode("utf-8")
  152. FilePath(fName).setContent(dumpFunc(crypto.FILETYPE_PEM, obj))
  153. class ContextGeneratingMixin:
  154. """
  155. Offer methods to create L{ssl.DefaultOpenSSLContextFactory} for both client
  156. and server.
  157. @ivar clientBase: prefix of client certificate files.
  158. @type clientBase: C{str}
  159. @ivar serverBase: prefix of server certificate files.
  160. @type serverBase: C{str}
  161. @ivar clientCtxFactory: a generated context factory to be used in
  162. L{IReactorSSL.connectSSL}.
  163. @type clientCtxFactory: L{ssl.DefaultOpenSSLContextFactory}
  164. @ivar serverCtxFactory: a generated context factory to be used in
  165. L{IReactorSSL.listenSSL}.
  166. @type serverCtxFactory: L{ssl.DefaultOpenSSLContextFactory}
  167. """
  168. def makeContextFactory(self, org, orgUnit, *args, **kwArgs):
  169. base = self.mktemp()
  170. generateCertificateFiles(base, org, orgUnit)
  171. serverCtxFactory = ssl.DefaultOpenSSLContextFactory(
  172. os.extsep.join((base, "key")),
  173. os.extsep.join((base, "cert")),
  174. *args,
  175. **kwArgs,
  176. )
  177. return base, serverCtxFactory
  178. def setupServerAndClient(self, clientArgs, clientKwArgs, serverArgs, serverKwArgs):
  179. self.clientBase, self.clientCtxFactory = self.makeContextFactory(
  180. *clientArgs, **clientKwArgs
  181. )
  182. self.serverBase, self.serverCtxFactory = self.makeContextFactory(
  183. *serverArgs, **serverKwArgs
  184. )
  185. if SSL is not None:
  186. class ServerTLSContext(ssl.DefaultOpenSSLContextFactory):
  187. """
  188. A context factory with a default method set to
  189. L{OpenSSL.SSL.SSLv23_METHOD}.
  190. """
  191. isClient = False
  192. def __init__(self, *args, **kw):
  193. kw["sslmethod"] = SSL.SSLv23_METHOD
  194. ssl.DefaultOpenSSLContextFactory.__init__(self, *args, **kw)
  195. class StolenTCPTests(ProperlyCloseFilesMixin, TestCase):
  196. """
  197. For SSL transports, test many of the same things which are tested for
  198. TCP transports.
  199. """
  200. if interfaces.IReactorSSL(reactor, None) is None:
  201. skip = "Reactor does not support SSL, cannot run SSL tests"
  202. def createServer(self, address, portNumber, factory):
  203. """
  204. Create an SSL server with a certificate using L{IReactorSSL.listenSSL}.
  205. """
  206. cert = ssl.PrivateCertificate.loadPEM(FilePath(certPath).getContent())
  207. contextFactory = cert.options()
  208. return reactor.listenSSL(portNumber, factory, contextFactory, interface=address)
  209. def connectClient(self, address, portNumber, clientCreator):
  210. """
  211. Create an SSL client using L{IReactorSSL.connectSSL}.
  212. """
  213. contextFactory = ssl.CertificateOptions()
  214. return clientCreator.connectSSL(address, portNumber, contextFactory)
  215. def getHandleExceptionType(self):
  216. """
  217. Return L{OpenSSL.SSL.Error} as the expected error type which will be
  218. raised by a write to the L{OpenSSL.SSL.Connection} object after it has
  219. been closed.
  220. """
  221. return SSL.Error
  222. def getHandleErrorCodeMatcher(self):
  223. """
  224. Return a L{hamcrest.core.matcher.Matcher} for the argument
  225. L{OpenSSL.SSL.Error} will be constructed with for this case.
  226. This is basically just a random OpenSSL implementation detail.
  227. It would be better if this test worked in a way which did not
  228. require this.
  229. """
  230. # We expect an error about how we tried to write to a shutdown
  231. # connection. This is terribly implementation-specific.
  232. return hamcrest.contains(
  233. hamcrest.contains(
  234. hamcrest.equal_to("SSL routines"),
  235. hamcrest.any_of(
  236. hamcrest.equal_to("SSL_write"),
  237. hamcrest.equal_to("ssl_write_internal"),
  238. hamcrest.equal_to(""),
  239. ),
  240. hamcrest.equal_to("protocol is shutdown"),
  241. ),
  242. )
  243. class TLSTests(TestCase):
  244. """
  245. Tests for startTLS support.
  246. @ivar fillBuffer: forwarded to L{LineCollector.fillBuffer}
  247. @type fillBuffer: C{bool}
  248. """
  249. if interfaces.IReactorSSL(reactor, None) is None:
  250. skip = "Reactor does not support SSL, cannot run SSL tests"
  251. fillBuffer = False
  252. clientProto = None
  253. serverProto = None
  254. def tearDown(self):
  255. if self.clientProto.transport is not None:
  256. self.clientProto.transport.loseConnection()
  257. if self.serverProto.transport is not None:
  258. self.serverProto.transport.loseConnection()
  259. def _runTest(self, clientProto, serverProto, clientIsServer=False):
  260. """
  261. Helper method to run TLS tests.
  262. @param clientProto: protocol instance attached to the client
  263. connection.
  264. @param serverProto: protocol instance attached to the server
  265. connection.
  266. @param clientIsServer: flag indicated if client should initiate
  267. startTLS instead of server.
  268. @return: a L{defer.Deferred} that will fire when both connections are
  269. lost.
  270. """
  271. self.clientProto = clientProto
  272. cf = self.clientFactory = protocol.ClientFactory()
  273. cf.protocol = lambda: clientProto
  274. if clientIsServer:
  275. cf.server = False
  276. else:
  277. cf.client = True
  278. self.serverProto = serverProto
  279. sf = self.serverFactory = protocol.ServerFactory()
  280. sf.protocol = lambda: serverProto
  281. if clientIsServer:
  282. sf.client = False
  283. else:
  284. sf.server = True
  285. port = reactor.listenTCP(0, sf, interface="127.0.0.1")
  286. self.addCleanup(port.stopListening)
  287. reactor.connectTCP("127.0.0.1", port.getHost().port, cf)
  288. return defer.gatherResults([clientProto.deferred, serverProto.deferred])
  289. def test_TLS(self):
  290. """
  291. Test for server and client startTLS: client should received data both
  292. before and after the startTLS.
  293. """
  294. def check(ignore):
  295. self.assertEqual(
  296. self.serverFactory.lines,
  297. UnintelligentProtocol.pretext + UnintelligentProtocol.posttext,
  298. )
  299. d = self._runTest(UnintelligentProtocol(), LineCollector(True, self.fillBuffer))
  300. return d.addCallback(check)
  301. def test_unTLS(self):
  302. """
  303. Test for server startTLS not followed by a startTLS in client: the data
  304. received after server startTLS should be received as raw.
  305. """
  306. def check(ignored):
  307. self.assertEqual(self.serverFactory.lines, UnintelligentProtocol.pretext)
  308. self.assertTrue(self.serverFactory.rawdata, "No encrypted bytes received")
  309. d = self._runTest(
  310. UnintelligentProtocol(), LineCollector(False, self.fillBuffer)
  311. )
  312. return d.addCallback(check)
  313. def test_backwardsTLS(self):
  314. """
  315. Test startTLS first initiated by client.
  316. """
  317. def check(ignored):
  318. self.assertEqual(
  319. self.clientFactory.lines,
  320. UnintelligentProtocol.pretext + UnintelligentProtocol.posttext,
  321. )
  322. d = self._runTest(
  323. LineCollector(True, self.fillBuffer), UnintelligentProtocol(), True
  324. )
  325. return d.addCallback(check)
  326. class SpammyTLSTests(TLSTests):
  327. """
  328. Test TLS features with bytes sitting in the out buffer.
  329. """
  330. if interfaces.IReactorSSL(reactor, None) is None:
  331. skip = "Reactor does not support SSL, cannot run SSL tests"
  332. fillBuffer = True
  333. class BufferingTests(TestCase):
  334. if interfaces.IReactorSSL(reactor, None) is None:
  335. skip = "Reactor does not support SSL, cannot run SSL tests"
  336. serverProto = None
  337. clientProto = None
  338. def tearDown(self):
  339. if self.serverProto.transport is not None:
  340. self.serverProto.transport.loseConnection()
  341. if self.clientProto.transport is not None:
  342. self.clientProto.transport.loseConnection()
  343. return waitUntilAllDisconnected(reactor, [self.serverProto, self.clientProto])
  344. def test_openSSLBuffering(self):
  345. serverProto = self.serverProto = SingleLineServerProtocol()
  346. clientProto = self.clientProto = RecordingClientProtocol()
  347. server = protocol.ServerFactory()
  348. client = self.client = protocol.ClientFactory()
  349. server.protocol = lambda: serverProto
  350. client.protocol = lambda: clientProto
  351. sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath)
  352. cCTX = ssl.ClientContextFactory()
  353. port = reactor.listenSSL(0, server, sCTX, interface="127.0.0.1")
  354. self.addCleanup(port.stopListening)
  355. clientConnector = reactor.connectSSL(
  356. "127.0.0.1", port.getHost().port, client, cCTX
  357. )
  358. self.addCleanup(clientConnector.disconnect)
  359. return clientProto.deferred.addCallback(
  360. self.assertEqual, b"+OK <some crap>\r\n"
  361. )
  362. class ConnectionLostTests(TestCase, ContextGeneratingMixin):
  363. """
  364. SSL connection closing tests.
  365. """
  366. if interfaces.IReactorSSL(reactor, None) is None:
  367. skip = "Reactor does not support SSL, cannot run SSL tests"
  368. def testImmediateDisconnect(self):
  369. org = "twisted.test.test_ssl"
  370. self.setupServerAndClient(
  371. (org, org + ", client"), {}, (org, org + ", server"), {}
  372. )
  373. # Set up a server, connect to it with a client, which should work since our verifiers
  374. # allow anything, then disconnect.
  375. serverProtocolFactory = protocol.ServerFactory()
  376. serverProtocolFactory.protocol = protocol.Protocol
  377. self.serverPort = serverPort = reactor.listenSSL(
  378. 0, serverProtocolFactory, self.serverCtxFactory
  379. )
  380. clientProtocolFactory = protocol.ClientFactory()
  381. clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol
  382. clientProtocolFactory.connectionDisconnected = defer.Deferred()
  383. reactor.connectSSL(
  384. "127.0.0.1",
  385. serverPort.getHost().port,
  386. clientProtocolFactory,
  387. self.clientCtxFactory,
  388. )
  389. return clientProtocolFactory.connectionDisconnected.addCallback(
  390. lambda ignoredResult: self.serverPort.stopListening()
  391. )
  392. def test_bothSidesLoseConnection(self):
  393. """
  394. Both sides of SSL connection close connection; the connections should
  395. close cleanly, and only after the underlying TCP connection has
  396. disconnected.
  397. """
  398. @implementer(interfaces.IHandshakeListener)
  399. class CloseAfterHandshake(protocol.Protocol):
  400. gotData = False
  401. def __init__(self):
  402. self.done = defer.Deferred()
  403. def handshakeCompleted(self):
  404. self.transport.loseConnection()
  405. def connectionLost(self, reason):
  406. self.done.errback(reason)
  407. del self.done
  408. org = "twisted.test.test_ssl"
  409. self.setupServerAndClient(
  410. (org, org + ", client"), {}, (org, org + ", server"), {}
  411. )
  412. serverProtocol = CloseAfterHandshake()
  413. serverProtocolFactory = protocol.ServerFactory()
  414. serverProtocolFactory.protocol = lambda: serverProtocol
  415. serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory)
  416. self.addCleanup(serverPort.stopListening)
  417. clientProtocol = CloseAfterHandshake()
  418. clientProtocolFactory = protocol.ClientFactory()
  419. clientProtocolFactory.protocol = lambda: clientProtocol
  420. reactor.connectSSL(
  421. "127.0.0.1",
  422. serverPort.getHost().port,
  423. clientProtocolFactory,
  424. self.clientCtxFactory,
  425. )
  426. def checkResult(failure):
  427. failure.trap(ConnectionDone)
  428. return defer.gatherResults(
  429. [
  430. clientProtocol.done.addErrback(checkResult),
  431. serverProtocol.done.addErrback(checkResult),
  432. ]
  433. )
  434. def testFailedVerify(self):
  435. org = "twisted.test.test_ssl"
  436. self.setupServerAndClient(
  437. (org, org + ", client"), {}, (org, org + ", server"), {}
  438. )
  439. def verify(*a):
  440. return False
  441. self.clientCtxFactory.getContext().set_verify(SSL.VERIFY_PEER, verify)
  442. serverConnLost = defer.Deferred()
  443. serverProtocol = protocol.Protocol()
  444. serverProtocol.connectionLost = serverConnLost.callback
  445. serverProtocolFactory = protocol.ServerFactory()
  446. serverProtocolFactory.protocol = lambda: serverProtocol
  447. self.serverPort = serverPort = reactor.listenSSL(
  448. 0, serverProtocolFactory, self.serverCtxFactory
  449. )
  450. clientConnLost = defer.Deferred()
  451. clientProtocol = protocol.Protocol()
  452. clientProtocol.connectionLost = clientConnLost.callback
  453. clientProtocolFactory = protocol.ClientFactory()
  454. clientProtocolFactory.protocol = lambda: clientProtocol
  455. reactor.connectSSL(
  456. "127.0.0.1",
  457. serverPort.getHost().port,
  458. clientProtocolFactory,
  459. self.clientCtxFactory,
  460. )
  461. dl = defer.DeferredList([serverConnLost, clientConnLost], consumeErrors=True)
  462. return dl.addCallback(self._cbLostConns)
  463. def _cbLostConns(self, results):
  464. (sSuccess, sResult), (cSuccess, cResult) = results
  465. self.assertFalse(sSuccess)
  466. self.assertFalse(cSuccess)
  467. acceptableErrors = [SSL.Error]
  468. # Rather than getting a verification failure on Windows, we are getting
  469. # a connection failure. Without something like sslverify proxying
  470. # in-between we can't fix up the platform's errors, so let's just
  471. # specifically say it is only OK in this one case to keep the tests
  472. # passing. Normally we'd like to be as strict as possible here, so
  473. # we're not going to allow this to report errors incorrectly on any
  474. # other platforms.
  475. if platform.isWindows():
  476. from twisted.internet.error import ConnectionLost
  477. acceptableErrors.append(ConnectionLost)
  478. sResult.trap(*acceptableErrors)
  479. cResult.trap(*acceptableErrors)
  480. return self.serverPort.stopListening()
  481. class FakeContext:
  482. """
  483. L{OpenSSL.SSL.Context} double which can more easily be inspected.
  484. """
  485. def __init__(self, method):
  486. self._method = method
  487. self._options = 0
  488. def set_options(self, options):
  489. self._options |= options
  490. def use_certificate_file(self, fileName):
  491. pass
  492. def use_privatekey_file(self, fileName):
  493. pass
  494. class DefaultOpenSSLContextFactoryTests(TestCase):
  495. """
  496. Tests for L{ssl.DefaultOpenSSLContextFactory}.
  497. """
  498. if interfaces.IReactorSSL(reactor, None) is None:
  499. skip = "Reactor does not support SSL, cannot run SSL tests"
  500. def setUp(self):
  501. # pyOpenSSL Context objects aren't introspectable enough. Pass in
  502. # an alternate context factory so we can inspect what is done to it.
  503. self.contextFactory = ssl.DefaultOpenSSLContextFactory(
  504. certPath, certPath, _contextFactory=FakeContext
  505. )
  506. self.context = self.contextFactory.getContext()
  507. def test_method(self):
  508. """
  509. L{ssl.DefaultOpenSSLContextFactory.getContext} returns an SSL context
  510. which can use SSLv3 or TLSv1 but not SSLv2.
  511. """
  512. # TLS_METHOD allows for negotiating multiple versions of TLS
  513. self.assertEqual(self.context._method, SSL.TLS_METHOD)
  514. # OP_NO_SSLv2 disables SSLv2 support
  515. self.assertEqual(self.context._options & SSL.OP_NO_SSLv2, SSL.OP_NO_SSLv2)
  516. # Make sure TLSv1.2 isn't disabled though.
  517. self.assertFalse(self.context._options & SSL.OP_NO_TLSv1_2)
  518. def test_missingCertificateFile(self):
  519. """
  520. Instantiating L{ssl.DefaultOpenSSLContextFactory} with a certificate
  521. filename which does not identify an existing file results in the
  522. initializer raising L{OpenSSL.SSL.Error}.
  523. """
  524. self.assertRaises(
  525. SSL.Error, ssl.DefaultOpenSSLContextFactory, certPath, self.mktemp()
  526. )
  527. def test_missingPrivateKeyFile(self):
  528. """
  529. Instantiating L{ssl.DefaultOpenSSLContextFactory} with a private key
  530. filename which does not identify an existing file results in the
  531. initializer raising L{OpenSSL.SSL.Error}.
  532. """
  533. self.assertRaises(
  534. SSL.Error, ssl.DefaultOpenSSLContextFactory, self.mktemp(), certPath
  535. )
  536. class ClientContextFactoryTests(TestCase):
  537. """
  538. Tests for L{ssl.ClientContextFactory}.
  539. """
  540. if interfaces.IReactorSSL(reactor, None) is None:
  541. skip = "Reactor does not support SSL, cannot run SSL tests"
  542. def setUp(self):
  543. self.contextFactory = ssl.ClientContextFactory()
  544. self.contextFactory._contextFactory = FakeContext
  545. self.context = self.contextFactory.getContext()
  546. def test_method(self):
  547. """
  548. L{ssl.ClientContextFactory.getContext} returns a context which can use
  549. TLSv1.2 or 1.3 but nothing earlier.
  550. """
  551. self.assertEqual(self.context._method, SSL.TLS_METHOD)
  552. self.assertEqual(self.context._options & SSL.OP_NO_SSLv2, SSL.OP_NO_SSLv2)
  553. self.assertTrue(self.context._options & SSL.OP_NO_SSLv3)
  554. self.assertTrue(self.context._options & SSL.OP_NO_TLSv1)