blob: 10b7d54911c222d57236c8d33a4366228fc3e01c [file] [log] [blame]
David Benjaminf025abe2021-09-17 22:59:19 +00001#!/usr/bin/env vpython3
rsimha@chromium.org99a6f172013-01-20 01:10:24 +00002# Copyright 2013 The Chromium Authors. All rights reserved.
license.botf3378c22008-08-24 00:55:55 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
initial.commit94958cf2008-07-26 22:42:52 +00005
Matt Menke3a293bd2021-08-13 20:34:43 +00006"""This is a simple HTTP/TCP/PROXY/BASIC_AUTH_PROXY/WEBSOCKET server used for
7testing Chrome.
initial.commit94958cf2008-07-26 22:42:52 +00008
9It supports several test URLs, as specified by the handlers in TestPageHandler.
cbentzel@chromium.org0787bc72010-11-11 20:31:31 +000010By default, it listens on an ephemeral port and sends the port number back to
11the originating process over a pipe. The originating process can specify an
12explicit port if necessary.
initial.commit94958cf2008-07-26 22:42:52 +000013It can use https if you specify the flag --https=CERT where CERT is the path
14to a pem file containing the certificate and private key that should be used.
initial.commit94958cf2008-07-26 22:42:52 +000015"""
16
David Benjaminf025abe2021-09-17 22:59:19 +000017from __future__ import print_function
18
initial.commit94958cf2008-07-26 22:42:52 +000019import base64
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000020import logging
initial.commit94958cf2008-07-26 22:42:52 +000021import os
akalin@chromium.org4e4f3c92010-11-27 04:04:52 +000022import select
David Benjaminf025abe2021-09-17 22:59:19 +000023from six.moves import BaseHTTPServer, socketserver
24import six.moves.urllib.parse as urlparse
agl@chromium.orgb3ec3462012-03-19 20:32:47 +000025import socket
yhirano@chromium.org51f90d92014-03-24 04:49:23 +000026import ssl
agl@chromium.org77a9ad92012-03-20 15:14:27 +000027import sys
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +000028
maruel@chromium.org5ddc64e2013-12-05 17:50:12 +000029BASE_DIR = os.path.dirname(os.path.abspath(__file__))
30ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(BASE_DIR)))
31
davidben@chromium.org7d53b542014-04-10 17:56:44 +000032# Insert at the beginning of the path, we want to use our copies of the library
Robert Iannucci0e7ec952018-01-18 22:44:16 +000033# unconditionally (since they contain modifications from anything that might be
34# obtained from e.g. PyPi).
Keita Suzuki83e26f92020-03-06 09:42:48 +000035sys.path.insert(0, os.path.join(ROOT_DIR, 'third_party', 'pywebsocket3', 'src'))
davidben@chromium.org7d53b542014-04-10 17:56:44 +000036sys.path.insert(0, os.path.join(ROOT_DIR, 'third_party', 'tlslite'))
37
yhirano@chromium.org51f90d92014-03-24 04:49:23 +000038import mod_pywebsocket.standalone
pliard@chromium.org3f8873f2012-11-14 11:38:55 +000039from mod_pywebsocket.standalone import WebSocketServer
yhirano@chromium.org51f90d92014-03-24 04:49:23 +000040# import manually
41mod_pywebsocket.standalone.ssl = ssl
davidben@chromium.org06fcf202010-09-22 18:15:23 +000042
davidben@chromium.org7d53b542014-04-10 17:56:44 +000043import tlslite
44import tlslite.api
45
davidben@chromium.org7d53b542014-04-10 17:56:44 +000046import testserver_base
47
maruel@chromium.org756cf982009-03-05 12:46:38 +000048SERVER_HTTP = 0
Matt Menke3a293bd2021-08-13 20:34:43 +000049SERVER_BASIC_AUTH_PROXY = 1
50SERVER_WEBSOCKET = 2
51SERVER_PROXY = 3
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000052
53# Default request queue size for WebSocketServer.
54_DEFAULT_REQUEST_QUEUE_SIZE = 128
initial.commit94958cf2008-07-26 22:42:52 +000055
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000056class WebSocketOptions:
57 """Holds options for WebSocketServer."""
58
59 def __init__(self, host, port, data_dir):
60 self.request_queue_size = _DEFAULT_REQUEST_QUEUE_SIZE
61 self.server_host = host
62 self.port = port
63 self.websock_handlers = data_dir
64 self.scan_dir = None
65 self.allow_handlers_outside_root_dir = False
66 self.websock_handlers_map_file = None
67 self.cgi_directories = []
68 self.is_executable_method = None
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000069
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000070 self.use_tls = False
71 self.private_key = None
72 self.certificate = None
toyoshim@chromium.orgd532cf32012-10-18 05:05:51 +000073 self.tls_client_auth = False
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000074 self.tls_client_ca = None
75 self.use_basic_auth = False
Keita Suzuki83e26f92020-03-06 09:42:48 +000076 self.basic_auth_credential = 'Basic ' + base64.b64encode(
David Benjaminf025abe2021-09-17 22:59:19 +000077 b'test:test').decode()
toyoshim@chromium.orgaa1b6e72012-10-09 03:43:19 +000078
mattm@chromium.org830a3712012-11-07 23:00:07 +000079
rsimha@chromium.org99a6f172013-01-20 01:10:24 +000080class HTTPServer(testserver_base.ClientRestrictingServerMixIn,
81 testserver_base.BrokenPipeHandlerMixIn,
82 testserver_base.StoppableHTTPServer):
agl@chromium.org77a9ad92012-03-20 15:14:27 +000083 """This is a specialization of StoppableHTTPServer that adds client
erikwright@chromium.org847ef282012-02-22 16:41:10 +000084 verification."""
85
86 pass
87
David Benjaminf025abe2021-09-17 22:59:19 +000088
89class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
Adam Rice34b2e312018-04-06 16:48:30 +000090 """This variant of HTTPServer creates a new thread for every connection. It
91 should only be used with handlers that are known to be threadsafe."""
92
93 pass
94
mattm@chromium.org830a3712012-11-07 23:00:07 +000095
erikwright@chromium.org847ef282012-02-22 16:41:10 +000096class HTTPSServer(tlslite.api.TLSSocketServerMixIn,
rsimha@chromium.org99a6f172013-01-20 01:10:24 +000097 testserver_base.ClientRestrictingServerMixIn,
98 testserver_base.BrokenPipeHandlerMixIn,
99 testserver_base.StoppableHTTPServer):
agl@chromium.org77a9ad92012-03-20 15:14:27 +0000100 """This is a specialization of StoppableHTTPServer that add https support and
erikwright@chromium.org847ef282012-02-22 16:41:10 +0000101 client verification."""
initial.commit94958cf2008-07-26 22:42:52 +0000102
agl@chromium.org77a9ad92012-03-20 15:14:27 +0000103 def __init__(self, server_address, request_hander_class, pem_cert_and_key,
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000104 ssl_client_auth, ssl_client_cas, ssl_client_cert_types,
David Benjamin0c3cd362021-09-18 18:42:34 +0000105 tls_intolerant, tls_intolerance_type, signed_cert_timestamps,
106 alert_after_handshake, simulate_tls13_downgrade,
107 simulate_tls12_downgrade, tls_max_version):
davidben@chromium.org7d53b542014-04-10 17:56:44 +0000108 self.cert_chain = tlslite.api.X509CertChain()
109 self.cert_chain.parsePemList(pem_cert_and_key)
phajdan.jr@chromium.org9e6098d2013-06-24 19:00:38 +0000110 # Force using only python implementation - otherwise behavior is different
111 # depending on whether m2crypto Python module is present (error is thrown
112 # when it is). m2crypto uses a C (based on OpenSSL) implementation under
113 # the hood.
114 self.private_key = tlslite.api.parsePEMKey(pem_cert_and_key,
115 private=True,
116 implementations=['python'])
davidben@chromium.org31282a12010-08-07 01:10:02 +0000117 self.ssl_client_auth = ssl_client_auth
rsleevi@chromium.orgb2ecdab2010-08-21 04:02:44 +0000118 self.ssl_client_cas = []
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000119 self.ssl_client_cert_types = []
ekasper@google.com24aa8222013-11-28 13:43:26 +0000120 self.signed_cert_timestamps = signed_cert_timestamps
agl@chromium.org143daa42012-04-26 18:45:34 +0000121
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000122 if ssl_client_auth:
123 for ca_file in ssl_client_cas:
124 s = open(ca_file).read()
125 x509 = tlslite.api.X509()
126 x509.parse(s)
127 self.ssl_client_cas.append(x509.subject)
128
129 for cert_type in ssl_client_cert_types:
130 self.ssl_client_cert_types.append({
131 "rsa_sign": tlslite.api.ClientCertificateType.rsa_sign,
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000132 "ecdsa_sign": tlslite.api.ClientCertificateType.ecdsa_sign,
133 }[cert_type])
134
rsleevi@chromium.org2124c812010-10-28 11:57:36 +0000135 self.ssl_handshake_settings = tlslite.api.HandshakeSettings()
davidbenc16cde32015-01-21 18:21:30 -0800136 # Enable SSLv3 for testing purposes.
137 self.ssl_handshake_settings.minVersion = (3, 0)
davidben@chromium.orgbbf4f402014-06-27 01:16:55 +0000138 if tls_intolerant != 0:
139 self.ssl_handshake_settings.tlsIntolerant = (3, tls_intolerant)
140 self.ssl_handshake_settings.tlsIntoleranceType = tls_intolerance_type
davidben21cda342015-03-17 18:04:28 -0700141 if alert_after_handshake:
142 self.ssl_handshake_settings.alertAfterHandshake = True
David Benjaminf839f1c2018-10-16 06:01:29 +0000143 if simulate_tls13_downgrade:
144 self.ssl_handshake_settings.simulateTLS13Downgrade = True
145 if simulate_tls12_downgrade:
146 self.ssl_handshake_settings.simulateTLS12Downgrade = True
147 if tls_max_version != 0:
148 self.ssl_handshake_settings.maxVersion = (3, tls_max_version)
initial.commit94958cf2008-07-26 22:42:52 +0000149
David Benjamin9aadbed2021-09-15 03:29:09 +0000150 self.session_cache = tlslite.api.SessionCache()
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000151 testserver_base.StoppableHTTPServer.__init__(self,
152 server_address,
153 request_hander_class)
initial.commit94958cf2008-07-26 22:42:52 +0000154
155 def handshake(self, tlsConnection):
156 """Creates the SSL connection."""
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000157
initial.commit94958cf2008-07-26 22:42:52 +0000158 try:
agl@chromium.org04700be2013-03-02 18:40:41 +0000159 self.tlsConnection = tlsConnection
David Benjamin0c3cd362021-09-18 18:42:34 +0000160 tlsConnection.handshakeServer(
161 certChain=self.cert_chain,
162 privateKey=self.private_key,
163 sessionCache=self.session_cache,
164 reqCert=self.ssl_client_auth,
165 settings=self.ssl_handshake_settings,
166 reqCAs=self.ssl_client_cas,
167 reqCertTypes=self.ssl_client_cert_types,
168 signedCertTimestamps=self.signed_cert_timestamps)
initial.commit94958cf2008-07-26 22:42:52 +0000169 tlsConnection.ignoreAbruptClose = True
170 return True
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000171 except tlslite.api.TLSAbruptCloseError:
172 # Ignore abrupt close.
173 return True
David Benjaminf025abe2021-09-17 22:59:19 +0000174 except tlslite.api.TLSError as error:
175 print("Handshake failure:", str(error))
initial.commit94958cf2008-07-26 22:42:52 +0000176 return False
177
akalin@chromium.org154bb132010-11-12 02:20:27 +0000178
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000179class TestPageHandler(testserver_base.BasePageHandler):
initial.commit94958cf2008-07-26 22:42:52 +0000180 def __init__(self, request, client_address, socket_server):
David Benjamin1f5bdcf2021-09-15 14:46:41 +0000181 connect_handlers = [self.DefaultConnectResponseHandler]
182 get_handlers = [self.DefaultResponseHandler]
183 post_handlers = get_handlers
184 put_handlers = get_handlers
185 head_handlers = [self.DefaultResponseHandler]
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000186 testserver_base.BasePageHandler.__init__(self, request, client_address,
187 socket_server, connect_handlers,
188 get_handlers, head_handlers,
189 post_handlers, put_handlers)
nsylvain@chromium.org8d5763b2008-12-30 23:44:27 +0000190
initial.commit94958cf2008-07-26 22:42:52 +0000191 def DefaultResponseHandler(self):
192 """This is the catch-all response handler for requests that aren't handled
193 by one of the special handlers above.
194 Note that we specify the content-length as without it the https connection
195 is not closed properly (and the browser keeps expecting data)."""
196
197 contents = "Default response given for path: " + self.path
198 self.send_response(200)
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000199 self.send_header('Content-Type', 'text/html')
200 self.send_header('Content-Length', len(contents))
initial.commit94958cf2008-07-26 22:42:52 +0000201 self.end_headers()
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000202 if (self.command != 'HEAD'):
David Benjaminf025abe2021-09-17 22:59:19 +0000203 self.wfile.write(contents.encode('utf8'))
initial.commit94958cf2008-07-26 22:42:52 +0000204 return True
205
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000206 def DefaultConnectResponseHandler(self):
207 """This is the catch-all response handler for CONNECT requests that aren't
208 handled by one of the special handlers above. Real Web servers respond
209 with 400 to CONNECT requests."""
210
211 contents = "Your client has issued a malformed or illegal request."
212 self.send_response(400) # bad request
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000213 self.send_header('Content-Type', 'text/html')
214 self.send_header('Content-Length', len(contents))
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000215 self.end_headers()
David Benjaminf025abe2021-09-17 22:59:19 +0000216 self.wfile.write(contents.encode('utf8'))
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000217 return True
218
akalin@chromium.org154bb132010-11-12 02:20:27 +0000219
Adam Rice9476b8c2018-08-02 15:28:43 +0000220class ProxyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
221 """A request handler that behaves as a proxy server. Only CONNECT, GET and
222 HEAD methods are supported.
bashi@chromium.org33233532012-09-08 17:37:24 +0000223 """
224
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100225 redirect_connect_to_localhost = False;
bashi@chromium.org33233532012-09-08 17:37:24 +0000226
bashi@chromium.org33233532012-09-08 17:37:24 +0000227 def _start_read_write(self, sock):
228 sock.setblocking(0)
229 self.request.setblocking(0)
230 rlist = [self.request, sock]
231 while True:
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000232 ready_sockets, _unused, errors = select.select(rlist, [], [])
bashi@chromium.org33233532012-09-08 17:37:24 +0000233 if errors:
234 self.send_response(500)
235 self.end_headers()
236 return
237 for s in ready_sockets:
238 received = s.recv(1024)
239 if len(received) == 0:
240 return
241 if s == self.request:
242 other = sock
243 else:
244 other = self.request
Adam Rice54443aa2018-06-06 00:11:54 +0000245 # This will lose data if the kernel write buffer fills up.
246 # TODO(ricea): Correctly use the return value to track how much was
247 # written and buffer the rest. Use select to determine when the socket
248 # becomes writable again.
bashi@chromium.org33233532012-09-08 17:37:24 +0000249 other.send(received)
250
251 def _do_common_method(self):
252 url = urlparse.urlparse(self.path)
253 port = url.port
254 if not port:
255 if url.scheme == 'http':
256 port = 80
257 elif url.scheme == 'https':
258 port = 443
259 if not url.hostname or not port:
260 self.send_response(400)
261 self.end_headers()
262 return
263
264 if len(url.path) == 0:
265 path = '/'
266 else:
267 path = url.path
268 if len(url.query) > 0:
269 path = '%s?%s' % (url.path, url.query)
270
271 sock = None
272 try:
273 sock = socket.create_connection((url.hostname, port))
David Benjaminf025abe2021-09-17 22:59:19 +0000274 sock.send(('%s %s %s\r\n' %
275 (self.command, path, self.protocol_version)).encode('utf-8'))
276 for name, value in self.headers.items():
277 if (name.lower().startswith('connection')
278 or name.lower().startswith('proxy')):
bashi@chromium.org33233532012-09-08 17:37:24 +0000279 continue
David Benjaminf025abe2021-09-17 22:59:19 +0000280 # HTTP headers are encoded in Latin-1.
281 sock.send(b'%s: %s\r\n' %
282 (name.encode('latin-1'), value.encode('latin-1')))
283 sock.send(b'\r\n')
Adam Rice54443aa2018-06-06 00:11:54 +0000284 # This is wrong: it will pass through connection-level headers and
285 # misbehave on connection reuse. The only reason it works at all is that
286 # our test servers have never supported connection reuse.
287 # TODO(ricea): Use a proper HTTP client library instead.
bashi@chromium.org33233532012-09-08 17:37:24 +0000288 self._start_read_write(sock)
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000289 except Exception:
Adam Rice54443aa2018-06-06 00:11:54 +0000290 logging.exception('failure in common method: %s %s', self.command, path)
bashi@chromium.org33233532012-09-08 17:37:24 +0000291 self.send_response(500)
292 self.end_headers()
293 finally:
294 if sock is not None:
295 sock.close()
296
297 def do_CONNECT(self):
298 try:
299 pos = self.path.rfind(':')
300 host = self.path[:pos]
301 port = int(self.path[pos+1:])
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000302 except Exception:
bashi@chromium.org33233532012-09-08 17:37:24 +0000303 self.send_response(400)
304 self.end_headers()
305
Adam Rice9476b8c2018-08-02 15:28:43 +0000306 if ProxyRequestHandler.redirect_connect_to_localhost:
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100307 host = "127.0.0.1"
308
Adam Rice54443aa2018-06-06 00:11:54 +0000309 sock = None
bashi@chromium.org33233532012-09-08 17:37:24 +0000310 try:
311 sock = socket.create_connection((host, port))
312 self.send_response(200, 'Connection established')
313 self.end_headers()
314 self._start_read_write(sock)
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000315 except Exception:
Adam Rice54443aa2018-06-06 00:11:54 +0000316 logging.exception('failure in CONNECT: %s', path)
bashi@chromium.org33233532012-09-08 17:37:24 +0000317 self.send_response(500)
318 self.end_headers()
319 finally:
Adam Rice54443aa2018-06-06 00:11:54 +0000320 if sock is not None:
321 sock.close()
bashi@chromium.org33233532012-09-08 17:37:24 +0000322
323 def do_GET(self):
324 self._do_common_method()
325
326 def do_HEAD(self):
327 self._do_common_method()
328
Adam Rice9476b8c2018-08-02 15:28:43 +0000329class BasicAuthProxyRequestHandler(ProxyRequestHandler):
330 """A request handler that behaves as a proxy server which requires
331 basic authentication.
332 """
333
334 _AUTH_CREDENTIAL = 'Basic Zm9vOmJhcg==' # foo:bar
335
336 def parse_request(self):
337 """Overrides parse_request to check credential."""
338
339 if not ProxyRequestHandler.parse_request(self):
340 return False
341
David Benjaminf025abe2021-09-17 22:59:19 +0000342 auth = self.headers.get('Proxy-Authorization', None)
Adam Rice9476b8c2018-08-02 15:28:43 +0000343 if auth != self._AUTH_CREDENTIAL:
344 self.send_response(407)
345 self.send_header('Proxy-Authenticate', 'Basic realm="MyRealm1"')
346 self.end_headers()
347 return False
348
349 return True
350
bashi@chromium.org33233532012-09-08 17:37:24 +0000351
mattm@chromium.org830a3712012-11-07 23:00:07 +0000352class ServerRunner(testserver_base.TestServerRunner):
353 """TestServerRunner for the net test servers."""
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000354
mattm@chromium.org830a3712012-11-07 23:00:07 +0000355 def __init__(self):
356 super(ServerRunner, self).__init__()
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000357
mattm@chromium.org830a3712012-11-07 23:00:07 +0000358 def __make_data_dir(self):
359 if self.options.data_dir:
360 if not os.path.isdir(self.options.data_dir):
361 raise testserver_base.OptionError('specified data dir not found: ' +
362 self.options.data_dir + ' exiting...')
363 my_data_dir = self.options.data_dir
364 else:
365 # Create the default path to our data dir, relative to the exe dir.
Asanka Herath0ec37152019-08-02 15:23:57 +0000366 my_data_dir = os.path.join(BASE_DIR, "..", "..", "data")
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000367
mattm@chromium.org830a3712012-11-07 23:00:07 +0000368 return my_data_dir
newt@chromium.org1fc32742012-10-20 00:28:35 +0000369
mattm@chromium.org830a3712012-11-07 23:00:07 +0000370 def create_server(self, server_data):
371 port = self.options.port
372 host = self.options.host
newt@chromium.org1fc32742012-10-20 00:28:35 +0000373
Adam Rice54443aa2018-06-06 00:11:54 +0000374 logging.basicConfig()
375
estark21667d62015-04-08 21:00:16 -0700376 # Work around a bug in Mac OS 10.6. Spawning a WebSockets server
377 # will result in a call to |getaddrinfo|, which fails with "nodename
378 # nor servname provided" for localhost:0 on 10.6.
Adam Rice54443aa2018-06-06 00:11:54 +0000379 # TODO(ricea): Remove this if no longer needed.
estark21667d62015-04-08 21:00:16 -0700380 if self.options.server_type == SERVER_WEBSOCKET and \
381 host == "localhost" and \
382 port == 0:
383 host = "127.0.0.1"
384
Ryan Sleevi3bfd15d2018-01-23 21:12:24 +0000385 # Construct the subjectAltNames for any ad-hoc generated certificates.
386 # As host can be either a DNS name or IP address, attempt to determine
387 # which it is, so it can be placed in the appropriate SAN.
388 dns_sans = None
389 ip_sans = None
390 ip = None
391 try:
392 ip = socket.inet_aton(host)
393 ip_sans = [ip]
394 except socket.error:
395 pass
396 if ip is None:
397 dns_sans = [host]
398
mattm@chromium.org830a3712012-11-07 23:00:07 +0000399 if self.options.server_type == SERVER_HTTP:
400 if self.options.https:
David Benjamin8ed48d12021-09-14 21:28:30 +0000401 if not self.options.cert_and_key_file:
402 raise testserver_base.OptionError('server cert file not specified')
403 if not os.path.isfile(self.options.cert_and_key_file):
404 raise testserver_base.OptionError(
405 'specified server cert file not found: ' +
406 self.options.cert_and_key_file + ' exiting...')
David Benjaminf025abe2021-09-17 22:59:19 +0000407 pem_cert_and_key = open(self.options.cert_and_key_file, 'r').read()
mattm@chromium.org830a3712012-11-07 23:00:07 +0000408
409 for ca_cert in self.options.ssl_client_ca:
410 if not os.path.isfile(ca_cert):
411 raise testserver_base.OptionError(
412 'specified trusted client CA file not found: ' + ca_cert +
413 ' exiting...')
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000414
David Benjaminf025abe2021-09-17 22:59:19 +0000415 server = HTTPSServer(
416 (host, port), TestPageHandler, pem_cert_and_key,
417 self.options.ssl_client_auth, self.options.ssl_client_ca,
David Benjamin0c3cd362021-09-18 18:42:34 +0000418 self.options.ssl_client_cert_type, self.options.tls_intolerant,
David Benjaminf025abe2021-09-17 22:59:19 +0000419 self.options.tls_intolerance_type,
420 base64.b64decode(self.options.signed_cert_timestamps_tls_ext),
David Benjamin0c3cd362021-09-18 18:42:34 +0000421 self.options.alert_after_handshake,
David Benjaminf025abe2021-09-17 22:59:19 +0000422 self.options.simulate_tls13_downgrade,
423 self.options.simulate_tls12_downgrade, self.options.tls_max_version)
424 print('HTTPS server started on https://%s:%d...' %
425 (host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000426 else:
427 server = HTTPServer((host, port), TestPageHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000428 print('HTTP server started on http://%s:%d...' %
429 (host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000430
431 server.data_dir = self.__make_data_dir()
432 server.file_root_url = self.options.file_root_url
433 server_data['port'] = server.server_port
mattm@chromium.org830a3712012-11-07 23:00:07 +0000434 elif self.options.server_type == SERVER_WEBSOCKET:
mattm@chromium.org830a3712012-11-07 23:00:07 +0000435 # TODO(toyoshim): Remove following os.chdir. Currently this operation
436 # is required to work correctly. It should be fixed from pywebsocket side.
437 os.chdir(self.__make_data_dir())
438 websocket_options = WebSocketOptions(host, port, '.')
davidben@chromium.org009843a2014-06-03 00:13:08 +0000439 scheme = "ws"
mattm@chromium.org830a3712012-11-07 23:00:07 +0000440 if self.options.cert_and_key_file:
davidben@chromium.org009843a2014-06-03 00:13:08 +0000441 scheme = "wss"
mattm@chromium.org830a3712012-11-07 23:00:07 +0000442 websocket_options.use_tls = True
Sergey Ulanovdd8b8ea2017-09-08 22:53:25 +0000443 key_path = os.path.join(ROOT_DIR, self.options.cert_and_key_file)
444 if not os.path.isfile(key_path):
445 raise testserver_base.OptionError(
446 'specified server cert file not found: ' +
447 self.options.cert_and_key_file + ' exiting...')
448 websocket_options.private_key = key_path
449 websocket_options.certificate = key_path
450
mattm@chromium.org830a3712012-11-07 23:00:07 +0000451 if self.options.ssl_client_auth:
pneubeck@chromium.orgf5007112014-07-21 15:22:41 +0000452 websocket_options.tls_client_cert_optional = False
mattm@chromium.org830a3712012-11-07 23:00:07 +0000453 websocket_options.tls_client_auth = True
454 if len(self.options.ssl_client_ca) != 1:
455 raise testserver_base.OptionError(
456 'one trusted client CA file should be specified')
457 if not os.path.isfile(self.options.ssl_client_ca[0]):
458 raise testserver_base.OptionError(
459 'specified trusted client CA file not found: ' +
460 self.options.ssl_client_ca[0] + ' exiting...')
461 websocket_options.tls_client_ca = self.options.ssl_client_ca[0]
David Benjaminf025abe2021-09-17 22:59:19 +0000462 print('Trying to start websocket server on %s://%s:%d...' %
463 (scheme, websocket_options.server_host, websocket_options.port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000464 server = WebSocketServer(websocket_options)
David Benjaminf025abe2021-09-17 22:59:19 +0000465 print('WebSocket server started on %s://%s:%d...' %
466 (scheme, host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000467 server_data['port'] = server.server_port
ricea@chromium.orga52ebdc2014-07-29 07:42:29 +0000468 websocket_options.use_basic_auth = self.options.ws_basic_auth
Adam Rice9476b8c2018-08-02 15:28:43 +0000469 elif self.options.server_type == SERVER_PROXY:
470 ProxyRequestHandler.redirect_connect_to_localhost = \
471 self.options.redirect_connect_to_localhost
472 server = ThreadingHTTPServer((host, port), ProxyRequestHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000473 print('Proxy server started on port %d...' % server.server_port)
Adam Rice9476b8c2018-08-02 15:28:43 +0000474 server_data['port'] = server.server_port
mattm@chromium.org830a3712012-11-07 23:00:07 +0000475 elif self.options.server_type == SERVER_BASIC_AUTH_PROXY:
Adam Rice9476b8c2018-08-02 15:28:43 +0000476 ProxyRequestHandler.redirect_connect_to_localhost = \
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100477 self.options.redirect_connect_to_localhost
Adam Rice34b2e312018-04-06 16:48:30 +0000478 server = ThreadingHTTPServer((host, port), BasicAuthProxyRequestHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000479 print('BasicAuthProxy server started on port %d...' % server.server_port)
mattm@chromium.org830a3712012-11-07 23:00:07 +0000480 server_data['port'] = server.server_port
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000481 else:
mattm@chromium.org830a3712012-11-07 23:00:07 +0000482 raise testserver_base.OptionError('unknown server type' +
483 self.options.server_type)
erikkay@google.com70397b62008-12-30 21:49:21 +0000484
mattm@chromium.org830a3712012-11-07 23:00:07 +0000485 return server
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000486
mattm@chromium.org830a3712012-11-07 23:00:07 +0000487 def add_options(self):
488 testserver_base.TestServerRunner.add_options(self)
Adam Rice9476b8c2018-08-02 15:28:43 +0000489 self.option_parser.add_option('--proxy', action='store_const',
490 const=SERVER_PROXY,
491 default=SERVER_HTTP, dest='server_type',
492 help='start up a proxy server.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000493 self.option_parser.add_option('--basic-auth-proxy', action='store_const',
494 const=SERVER_BASIC_AUTH_PROXY,
495 default=SERVER_HTTP, dest='server_type',
496 help='start up a proxy server which requires '
497 'basic authentication.')
498 self.option_parser.add_option('--websocket', action='store_const',
499 const=SERVER_WEBSOCKET, default=SERVER_HTTP,
500 dest='server_type',
501 help='start up a WebSocket server.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000502 self.option_parser.add_option('--https', action='store_true',
503 dest='https', help='Specify that https '
504 'should be used.')
505 self.option_parser.add_option('--cert-and-key-file',
506 dest='cert_and_key_file', help='specify the '
507 'path to the file containing the certificate '
508 'and private key for the server in PEM '
509 'format')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000510 self.option_parser.add_option('--tls-intolerant', dest='tls_intolerant',
511 default='0', type='int',
512 help='If nonzero, certain TLS connections '
513 'will be aborted in order to test version '
514 'fallback. 1 means all TLS versions will be '
515 'aborted. 2 means TLS 1.1 or higher will be '
516 'aborted. 3 means TLS 1.2 or higher will be '
davidbendf2e3862017-04-12 15:23:34 -0700517 'aborted. 4 means TLS 1.3 or higher will be '
mattm@chromium.org830a3712012-11-07 23:00:07 +0000518 'aborted.')
davidben@chromium.orgbbf4f402014-06-27 01:16:55 +0000519 self.option_parser.add_option('--tls-intolerance-type',
520 dest='tls_intolerance_type',
521 default="alert",
522 help='Controls how the server reacts to a '
523 'TLS version it is intolerant to. Valid '
524 'values are "alert", "close", and "reset".')
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000525 self.option_parser.add_option('--signed-cert-timestamps-tls-ext',
526 dest='signed_cert_timestamps_tls_ext',
ekasper@google.com24aa8222013-11-28 13:43:26 +0000527 default='',
528 help='Base64 encoded SCT list. If set, '
529 'server will respond with a '
530 'signed_certificate_timestamp TLS extension '
531 'whenever the client supports it.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000532 self.option_parser.add_option('--ssl-client-auth', action='store_true',
533 help='Require SSL client auth on every '
534 'connection.')
535 self.option_parser.add_option('--ssl-client-ca', action='append',
536 default=[], help='Specify that the client '
537 'certificate request should include the CA '
538 'named in the subject of the DER-encoded '
539 'certificate contained in the specified '
540 'file. This option may appear multiple '
541 'times, indicating multiple CA names should '
542 'be sent in the request.')
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000543 self.option_parser.add_option('--ssl-client-cert-type', action='append',
544 default=[], help='Specify that the client '
545 'certificate request should include the '
546 'specified certificate_type value. This '
547 'option may appear multiple times, '
548 'indicating multiple values should be send '
549 'in the request. Valid values are '
550 '"rsa_sign", "dss_sign", and "ecdsa_sign". '
551 'If omitted, "rsa_sign" will be used.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000552 self.option_parser.add_option('--file-root-url', default='/files/',
553 help='Specify a root URL for files served.')
ricea@chromium.orga52ebdc2014-07-29 07:42:29 +0000554 # TODO(ricea): Generalize this to support basic auth for HTTP too.
555 self.option_parser.add_option('--ws-basic-auth', action='store_true',
556 dest='ws_basic_auth',
557 help='Enable basic-auth for WebSocket')
davidben21cda342015-03-17 18:04:28 -0700558 self.option_parser.add_option('--alert-after-handshake',
559 dest='alert_after_handshake',
560 default=False, action='store_true',
561 help='If set, the server will send a fatal '
562 'alert immediately after the handshake.')
David Benjaminf839f1c2018-10-16 06:01:29 +0000563 self.option_parser.add_option('--simulate-tls13-downgrade',
564 action='store_true')
565 self.option_parser.add_option('--simulate-tls12-downgrade',
566 action='store_true')
567 self.option_parser.add_option('--tls-max-version', default='0', type='int',
568 help='If non-zero, the maximum TLS version '
569 'to support. 1 means TLS 1.0, 2 means '
570 'TLS 1.1, and 3 means TLS 1.2.')
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100571 self.option_parser.add_option('--redirect-connect-to-localhost',
572 dest='redirect_connect_to_localhost',
573 default=False, action='store_true',
574 help='If set, the Proxy server will connect '
575 'to localhost instead of the requested URL '
576 'on CONNECT requests')
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000577
toyoshim@chromium.org16f57522012-10-24 06:14:38 +0000578
initial.commit94958cf2008-07-26 22:42:52 +0000579if __name__ == '__main__':
mattm@chromium.org830a3712012-11-07 23:00:07 +0000580 sys.exit(ServerRunner().main())