Debian Codegraph @

docs/core/examples/tls_alpn_server.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
4 """
5 tls_alpn_server
6 ~~~~~~~~~~~~~~~~~~~
7
8 This test script demonstrates the usage of the acceptableProtocols API as a
9 server peer.
10
11 It performs next protocol negotiation using ALPN.
12
13 It will print what protocol was negotiated for each connection that is made to
14 it.
15
16 To exit the server, use CTRL+C on the command-line.
17
18 Before using this, you should generate a new RSA private key and an associated
19 X.509 certificate and place it in the working directory as `server-key.pem` and
20 `server-cert.pem`.
21
22 You can generate a self signed certificate using OpenSSL::
23
24 openssl req -new -newkey rsa:2048 -days 3 -nodes -x509 \
25 -keyout server-key.pem -out server-cert.pem
26
27 To test this, use OpenSSL's s_client command with the -alpn argument.
28
29 For example::
30
31 openssl s_client -connect localhost:8080 -alpn h2,http/1.1
32
33 Alternatively, use the tls_alpn_client.py script found in the examples
34 directory.
35 """
36
37 from OpenSSL import crypto
38
39 from twisted.internet import reactor, ssl
40 from twisted.internet.endpoints import SSL4ServerEndpoint
41 from twisted.internet.protocol import Factory, Protocol
42 from twisted.python.filepath import FilePath
43
44 # The list of protocols we'd be prepared to speak after the TLS negotiation is
45 # complete.
46 # The order of the protocols here is an order of preference. This indicates
47 # that we'd prefer to use HTTP/2 if possible (where HTTP/2 is using the token
48 # 'h2'), but would also accept HTTP/1.1.
49 # The bytes here are sent literally on the wire, and so there is no room for
50 # ambiguity about text encodings.
51 # Try changing this list by adding, removing, and reordering protocols to see
52 # how it affects the result.
53 ACCEPTABLE_PROTOCOLS = [b"h2", b"http/1.1"]
54
55 # The port that the server will listen on.
56 LISTEN_PORT = 8080
57
58
59 class ShowALPN(Protocol):
60 """
61 This protocol accepts incoming connections and waits for data. When
62 received, it prints what the negotiated protocol is, echoes the data back,
63 and then terminates the connection.
64 """
65
66 def connectionMade(self):
67 self.complete = False
68 print("Connection made")
69
70 def dataReceived(self, data):
71 print(self.transport.negotiatedProtocol)
72 self.transport.write(data)
73 self.complete = True
74 self.transport.loseConnection()
75
76 def connectionLost(self, reason):
77 # If we haven't received any data, an error occurred. Otherwise,
78 # we lost the connection on purpose.
79 if self.complete:
80 print("Connection closed cleanly")
81 else:
82 print(f"Connection lost due to error {reason}")
83
84
85 class ResponderFactory(Factory):
86 def buildProtocol(self, addr):
87 return ShowALPN()
88
89
90 privateKeyData = FilePath("server-key.pem").getContent()
91 privateKey = crypto.load_privatekey(crypto.FILETYPE_PEM, privateKeyData)
92 certData = FilePath("server-cert.pem").getContent()
93 certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certData)
94
95 options = ssl.CertificateOptions(
96 privateKey=privateKey,
97 certificate=certificate,
98 acceptableProtocols=ACCEPTABLE_PROTOCOLS,
99 )
100 endpoint = SSL4ServerEndpoint(reactor, LISTEN_PORT, options)
101 endpoint.listen(ResponderFactory())
102 reactor.run()