forked from twisted/treq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
child.py
271 lines (217 loc) · 8.85 KB
/
child.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"""
A local ``httpbin`` server to run integration tests against.
This ensures tests do not depend on `httpbin <https://httpbin.org/>`_.
"""
from __future__ import print_function
import argparse
import datetime
import sys
import httpbin
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.endpoints import TCP4ServerEndpoint, SSL4ServerEndpoint
from twisted.internet.task import react
from twisted.internet.ssl import (Certificate,
CertificateOptions)
from OpenSSL.crypto import PKey, X509
from twisted.python.threadpool import ThreadPool
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives.serialization import Encoding
from .shared import _HTTPBinDescription
def _certificates_for_authority_and_server(service_identity, key_size=2048):
"""
Create a self-signed CA certificate and server certificate signed
by the CA.
:param service_identity: The identity (hostname) of the server.
:type service_identity: :py:class:`unicode`
:param key_size: (optional) The size of CA's and server's private
RSA keys. Defaults to 2048 bits, which is the minimum allowed
by OpenSSL Contexts at the default security level.
:type key_size: :py:class:`int`
:return: a 3-tuple of ``(certificate_authority_certificate,
server_private_key, server_certificate)``.
:rtype: :py:class:`tuple` of (:py:class:`sslverify.Certificate`,
:py:class:`OpenSSL.crypto.PKey`,
:py:class:`OpenSSL.crypto.X509`)
"""
common_name_for_ca = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example CA')]
)
common_name_for_server = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, u'Testing Example Server')]
)
one_day = datetime.timedelta(1, 0, 0)
private_key_for_ca = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=default_backend()
)
public_key_for_ca = private_key_for_ca.public_key()
ca_certificate = (
x509.CertificateBuilder()
.subject_name(common_name_for_ca)
.issuer_name(common_name_for_ca)
.not_valid_before(datetime.datetime.today() - one_day)
.not_valid_after(datetime.datetime.today() + one_day)
.serial_number(x509.random_serial_number())
.public_key(public_key_for_ca)
.add_extension(
x509.BasicConstraints(ca=True, path_length=9), critical=True,
)
.sign(
private_key=private_key_for_ca, algorithm=hashes.SHA256(),
backend=default_backend()
)
)
private_key_for_server = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=default_backend()
)
public_key_for_server = private_key_for_server.public_key()
server_certificate = (
x509.CertificateBuilder()
.subject_name(common_name_for_server)
.issuer_name(common_name_for_ca)
.not_valid_before(datetime.datetime.today() - one_day)
.not_valid_after(datetime.datetime.today() + one_day)
.serial_number(x509.random_serial_number())
.public_key(public_key_for_server)
.add_extension(
x509.BasicConstraints(ca=False, path_length=None), critical=True,
)
.add_extension(
x509.SubjectAlternativeName(
[x509.DNSName(service_identity)]
),
critical=True,
)
.sign(
private_key=private_key_for_ca, algorithm=hashes.SHA256(),
backend=default_backend()
)
)
ca_self_cert = Certificate.loadPEM(
ca_certificate.public_bytes(Encoding.PEM)
)
pkey = PKey.from_cryptography_key(private_key_for_server)
x509_server_certificate = X509.from_cryptography(server_certificate)
return ca_self_cert, pkey, x509_server_certificate
def _make_httpbin_site(reactor, threadpool_factory=ThreadPool):
"""
Return a :py:class:`Site` that hosts an ``httpbin`` WSGI
application.
:param reactor: The reactor.
:param threadpool_factory: (optional) A callable that creates a
:py:class:`ThreadPool`.
:return: A :py:class:`Site` that hosts ``httpbin``
"""
wsgi_threads = threadpool_factory()
wsgi_threads.start()
reactor.addSystemEventTrigger("before", "shutdown", wsgi_threads.stop)
wsgi_resource = WSGIResource(reactor, wsgi_threads, httpbin.app)
return Site(wsgi_resource)
@inlineCallbacks
def _serve_tls(reactor, host, port, site):
"""
Serve a site over TLS.
:param reactor: The reactor.
:param host: The host on which to listen.
:type host: :py:class:`str`
:param port: The host on which to listen.
:type port: :py:class:`int`
:type site: The :py:class:`Site` to serve.
:return: A :py:class:`Deferred` that fires with a
:py:class:`_HTTPBinDescription`
"""
(
ca_cert, private_key, certificate,
) = _certificates_for_authority_and_server(host)
context_factory = CertificateOptions(privateKey=private_key,
certificate=certificate)
endpoint = SSL4ServerEndpoint(reactor,
port,
sslContextFactory=context_factory,
interface=host)
port = yield endpoint.listen(site)
description = _HTTPBinDescription(host=host,
port=port.getHost().port,
cacert=ca_cert.dumpPEM().decode('ascii'))
return description
@inlineCallbacks
def _serve_tcp(reactor, host, port, site):
"""
Serve a site over plain TCP.
:param reactor: The reactor.
:param host: The host on which to listen.
:type host: :py:class:`str`
:param port: The host on which to listen.
:type port: :py:class:`int`
:return: A :py:class:`Deferred` that fires with a
:py:class:`_HTTPBinDescription`
"""
endpoint = TCP4ServerEndpoint(reactor, port, interface=host)
port = yield endpoint.listen(site)
description = _HTTPBinDescription(host=host, port=port.getHost().port)
return description
def _output_process_description(description, stdout=sys.stdout):
"""
Write a process description to standard out.
:param description: The process description.
:type description: :py:class:`_HTTPBinDescription`
:param stdout: (optional) Standard out.
"""
stdout.buffer.write(description.to_json_bytes() + b'\n')
stdout.buffer.flush()
def _forever_httpbin(reactor, argv,
_make_httpbin_site=_make_httpbin_site,
_serve_tcp=_serve_tcp,
_serve_tls=_serve_tls,
_output_process_description=_output_process_description):
"""
Run ``httpbin`` forever.
:param reactor: The Twisted reactor.
:param argv: The arguments with which the script was ran.
:type argv: :py:class:`list` of :py:class:`str`
:return: a :py:class:`Deferred` that never fires.
"""
parser = argparse.ArgumentParser(
description="""
Run httpbin forever. This writes a JSON object to
standard out. The host and port properties
contain the host and port on which httpbin
listens. When run with HTTPS, the cacert property
contains the PEM-encode CA certificate that
clients must trust.
"""
)
parser.add_argument("--https",
help="Serve HTTPS",
action="store_const",
dest='serve',
const=_serve_tls,
default=_serve_tcp)
parser.add_argument("--host",
help="The host on which the server will listen.",
type=str,
default="localhost")
parser.add_argument("--port",
help="The on which the server will listen.",
type=int,
default=0)
arguments = parser.parse_args(argv)
site = _make_httpbin_site(reactor)
description_deferred = arguments.serve(reactor,
arguments.host,
arguments.port,
site)
description_deferred.addCallback(_output_process_description)
description_deferred.addCallback(lambda _: Deferred())
return description_deferred
if __name__ == '__main__':
react(_forever_httpbin, (sys.argv[1:],))