test_ssl.py 23 KB

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