1# Copyright (c) Twisted Matrix Laboratories.
2# See LICENSE for details.
3
4"""
5Helper classes for twisted.test.test_ssl.
6
7They are in a separate module so they will not prevent test_ssl importing if
8pyOpenSSL is unavailable.
9"""
10
11from OpenSSL import SSL
12
13from twisted.internet import ssl
14from twisted.python.compat import nativeString
15from twisted.python.filepath import FilePath
16
17certPath = nativeString(FilePath(__file__.encode("utf-8")).sibling(b"server.pem").path)
18
19
20class ClientTLSContext(ssl.ClientContextFactory):
21    """
22    SSL Context Factory for client-side connections.
23    """
24
25    isClient = 1
26
27    def getContext(self):
28        """
29        Return an L{SSL.Context} to be use for client-side connections.
30
31        Will not return a cached context.
32        This is done to improve the test coverage as most implementation
33        are caching the context.
34        """
35        return SSL.Context(SSL.SSLv23_METHOD)
36
37
38class ServerTLSContext:
39    """
40    SSL Context Factory for server-side connections.
41    """
42
43    isClient = 0
44
45    def __init__(self, filename=certPath, method=None):
46        self.filename = filename
47        if method is None:
48            method = SSL.SSLv23_METHOD
49
50        self._method = method
51
52    def getContext(self):
53        """
54        Return an L{SSL.Context} to be use for server-side connections.
55
56        Will not return a cached context.
57        This is done to improve the test coverage as most implementation
58        are caching the context.
59        """
60        ctx = SSL.Context(self._method)
61        ctx.use_certificate_file(self.filename)
62        ctx.use_privatekey_file(self.filename)
63        return ctx
64