blob: 3fd866099b699e8b2c52b534508b6e9ee4505c29 [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,
bnc5fb33bd2016-08-05 12:09:21 -0700105 ssl_bulk_ciphers, ssl_key_exchanges, alpn_protocols,
David Benjamin9aadbed2021-09-15 03:29:09 +0000106 npn_protocols, tls_intolerant, tls_intolerance_type,
107 signed_cert_timestamps, fallback_scsv_enabled, ocsp_response,
David Benjaminf839f1c2018-10-16 06:01:29 +0000108 alert_after_handshake, disable_channel_id, disable_ems,
109 simulate_tls13_downgrade, simulate_tls12_downgrade,
110 tls_max_version):
davidben@chromium.org7d53b542014-04-10 17:56:44 +0000111 self.cert_chain = tlslite.api.X509CertChain()
112 self.cert_chain.parsePemList(pem_cert_and_key)
phajdan.jr@chromium.org9e6098d2013-06-24 19:00:38 +0000113 # Force using only python implementation - otherwise behavior is different
114 # depending on whether m2crypto Python module is present (error is thrown
115 # when it is). m2crypto uses a C (based on OpenSSL) implementation under
116 # the hood.
117 self.private_key = tlslite.api.parsePEMKey(pem_cert_and_key,
118 private=True,
119 implementations=['python'])
davidben@chromium.org31282a12010-08-07 01:10:02 +0000120 self.ssl_client_auth = ssl_client_auth
rsleevi@chromium.orgb2ecdab2010-08-21 04:02:44 +0000121 self.ssl_client_cas = []
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000122 self.ssl_client_cert_types = []
bnc609ad4c2015-10-02 05:11:24 -0700123 self.npn_protocols = npn_protocols
ekasper@google.com24aa8222013-11-28 13:43:26 +0000124 self.signed_cert_timestamps = signed_cert_timestamps
agl@chromium.orgd0e11ca2013-12-11 20:16:13 +0000125 self.fallback_scsv_enabled = fallback_scsv_enabled
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000126 self.ocsp_response = ocsp_response
agl@chromium.org143daa42012-04-26 18:45:34 +0000127
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000128 if ssl_client_auth:
129 for ca_file in ssl_client_cas:
130 s = open(ca_file).read()
131 x509 = tlslite.api.X509()
132 x509.parse(s)
133 self.ssl_client_cas.append(x509.subject)
134
135 for cert_type in ssl_client_cert_types:
136 self.ssl_client_cert_types.append({
137 "rsa_sign": tlslite.api.ClientCertificateType.rsa_sign,
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000138 "ecdsa_sign": tlslite.api.ClientCertificateType.ecdsa_sign,
139 }[cert_type])
140
rsleevi@chromium.org2124c812010-10-28 11:57:36 +0000141 self.ssl_handshake_settings = tlslite.api.HandshakeSettings()
davidbenc16cde32015-01-21 18:21:30 -0800142 # Enable SSLv3 for testing purposes.
143 self.ssl_handshake_settings.minVersion = (3, 0)
rsleevi@chromium.org2124c812010-10-28 11:57:36 +0000144 if ssl_bulk_ciphers is not None:
145 self.ssl_handshake_settings.cipherNames = ssl_bulk_ciphers
davidben@chromium.org74aa8dd2014-04-11 07:20:26 +0000146 if ssl_key_exchanges is not None:
147 self.ssl_handshake_settings.keyExchangeNames = ssl_key_exchanges
davidben@chromium.orgbbf4f402014-06-27 01:16:55 +0000148 if tls_intolerant != 0:
149 self.ssl_handshake_settings.tlsIntolerant = (3, tls_intolerant)
150 self.ssl_handshake_settings.tlsIntoleranceType = tls_intolerance_type
davidben21cda342015-03-17 18:04:28 -0700151 if alert_after_handshake:
152 self.ssl_handshake_settings.alertAfterHandshake = True
nharper1e8bf4b2015-09-18 12:23:02 -0700153 if disable_channel_id:
154 self.ssl_handshake_settings.enableChannelID = False
155 if disable_ems:
156 self.ssl_handshake_settings.enableExtendedMasterSecret = False
David Benjaminf839f1c2018-10-16 06:01:29 +0000157 if simulate_tls13_downgrade:
158 self.ssl_handshake_settings.simulateTLS13Downgrade = True
159 if simulate_tls12_downgrade:
160 self.ssl_handshake_settings.simulateTLS12Downgrade = True
161 if tls_max_version != 0:
162 self.ssl_handshake_settings.maxVersion = (3, tls_max_version)
bnc5fb33bd2016-08-05 12:09:21 -0700163 self.ssl_handshake_settings.alpnProtos=alpn_protocols;
initial.commit94958cf2008-07-26 22:42:52 +0000164
David Benjamin9aadbed2021-09-15 03:29:09 +0000165 self.session_cache = tlslite.api.SessionCache()
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000166 testserver_base.StoppableHTTPServer.__init__(self,
167 server_address,
168 request_hander_class)
initial.commit94958cf2008-07-26 22:42:52 +0000169
170 def handshake(self, tlsConnection):
171 """Creates the SSL connection."""
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000172
initial.commit94958cf2008-07-26 22:42:52 +0000173 try:
agl@chromium.org04700be2013-03-02 18:40:41 +0000174 self.tlsConnection = tlsConnection
initial.commit94958cf2008-07-26 22:42:52 +0000175 tlsConnection.handshakeServer(certChain=self.cert_chain,
176 privateKey=self.private_key,
davidben@chromium.org31282a12010-08-07 01:10:02 +0000177 sessionCache=self.session_cache,
rsleevi@chromium.orgb2ecdab2010-08-21 04:02:44 +0000178 reqCert=self.ssl_client_auth,
rsleevi@chromium.org2124c812010-10-28 11:57:36 +0000179 settings=self.ssl_handshake_settings,
agl@chromium.org143daa42012-04-26 18:45:34 +0000180 reqCAs=self.ssl_client_cas,
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000181 reqCertTypes=self.ssl_client_cert_types,
bnc609ad4c2015-10-02 05:11:24 -0700182 nextProtos=self.npn_protocols,
ekasper@google.com24aa8222013-11-28 13:43:26 +0000183 signedCertTimestamps=
agl@chromium.orgd0e11ca2013-12-11 20:16:13 +0000184 self.signed_cert_timestamps,
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000185 fallbackSCSV=self.fallback_scsv_enabled,
186 ocspResponse = self.ocsp_response)
initial.commit94958cf2008-07-26 22:42:52 +0000187 tlsConnection.ignoreAbruptClose = True
188 return True
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000189 except tlslite.api.TLSAbruptCloseError:
190 # Ignore abrupt close.
191 return True
David Benjaminf025abe2021-09-17 22:59:19 +0000192 except tlslite.api.TLSError as error:
193 print("Handshake failure:", str(error))
initial.commit94958cf2008-07-26 22:42:52 +0000194 return False
195
akalin@chromium.org154bb132010-11-12 02:20:27 +0000196
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000197class TestPageHandler(testserver_base.BasePageHandler):
initial.commit94958cf2008-07-26 22:42:52 +0000198 def __init__(self, request, client_address, socket_server):
David Benjamin1f5bdcf2021-09-15 14:46:41 +0000199 connect_handlers = [self.DefaultConnectResponseHandler]
200 get_handlers = [self.DefaultResponseHandler]
201 post_handlers = get_handlers
202 put_handlers = get_handlers
203 head_handlers = [self.DefaultResponseHandler]
rsimha@chromium.org99a6f172013-01-20 01:10:24 +0000204 testserver_base.BasePageHandler.__init__(self, request, client_address,
205 socket_server, connect_handlers,
206 get_handlers, head_handlers,
207 post_handlers, put_handlers)
nsylvain@chromium.org8d5763b2008-12-30 23:44:27 +0000208
initial.commit94958cf2008-07-26 22:42:52 +0000209 def DefaultResponseHandler(self):
210 """This is the catch-all response handler for requests that aren't handled
211 by one of the special handlers above.
212 Note that we specify the content-length as without it the https connection
213 is not closed properly (and the browser keeps expecting data)."""
214
215 contents = "Default response given for path: " + self.path
216 self.send_response(200)
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000217 self.send_header('Content-Type', 'text/html')
218 self.send_header('Content-Length', len(contents))
initial.commit94958cf2008-07-26 22:42:52 +0000219 self.end_headers()
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000220 if (self.command != 'HEAD'):
David Benjaminf025abe2021-09-17 22:59:19 +0000221 self.wfile.write(contents.encode('utf8'))
initial.commit94958cf2008-07-26 22:42:52 +0000222 return True
223
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000224 def DefaultConnectResponseHandler(self):
225 """This is the catch-all response handler for CONNECT requests that aren't
226 handled by one of the special handlers above. Real Web servers respond
227 with 400 to CONNECT requests."""
228
229 contents = "Your client has issued a malformed or illegal request."
230 self.send_response(400) # bad request
mmenke@chromium.orgbfff75b2011-11-01 02:32:05 +0000231 self.send_header('Content-Type', 'text/html')
232 self.send_header('Content-Length', len(contents))
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000233 self.end_headers()
David Benjaminf025abe2021-09-17 22:59:19 +0000234 self.wfile.write(contents.encode('utf8'))
wtc@chromium.org743d77b2009-02-11 02:48:15 +0000235 return True
236
akalin@chromium.org154bb132010-11-12 02:20:27 +0000237
Adam Rice9476b8c2018-08-02 15:28:43 +0000238class ProxyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
239 """A request handler that behaves as a proxy server. Only CONNECT, GET and
240 HEAD methods are supported.
bashi@chromium.org33233532012-09-08 17:37:24 +0000241 """
242
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100243 redirect_connect_to_localhost = False;
bashi@chromium.org33233532012-09-08 17:37:24 +0000244
bashi@chromium.org33233532012-09-08 17:37:24 +0000245 def _start_read_write(self, sock):
246 sock.setblocking(0)
247 self.request.setblocking(0)
248 rlist = [self.request, sock]
249 while True:
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000250 ready_sockets, _unused, errors = select.select(rlist, [], [])
bashi@chromium.org33233532012-09-08 17:37:24 +0000251 if errors:
252 self.send_response(500)
253 self.end_headers()
254 return
255 for s in ready_sockets:
256 received = s.recv(1024)
257 if len(received) == 0:
258 return
259 if s == self.request:
260 other = sock
261 else:
262 other = self.request
Adam Rice54443aa2018-06-06 00:11:54 +0000263 # This will lose data if the kernel write buffer fills up.
264 # TODO(ricea): Correctly use the return value to track how much was
265 # written and buffer the rest. Use select to determine when the socket
266 # becomes writable again.
bashi@chromium.org33233532012-09-08 17:37:24 +0000267 other.send(received)
268
269 def _do_common_method(self):
270 url = urlparse.urlparse(self.path)
271 port = url.port
272 if not port:
273 if url.scheme == 'http':
274 port = 80
275 elif url.scheme == 'https':
276 port = 443
277 if not url.hostname or not port:
278 self.send_response(400)
279 self.end_headers()
280 return
281
282 if len(url.path) == 0:
283 path = '/'
284 else:
285 path = url.path
286 if len(url.query) > 0:
287 path = '%s?%s' % (url.path, url.query)
288
289 sock = None
290 try:
291 sock = socket.create_connection((url.hostname, port))
David Benjaminf025abe2021-09-17 22:59:19 +0000292 sock.send(('%s %s %s\r\n' %
293 (self.command, path, self.protocol_version)).encode('utf-8'))
294 for name, value in self.headers.items():
295 if (name.lower().startswith('connection')
296 or name.lower().startswith('proxy')):
bashi@chromium.org33233532012-09-08 17:37:24 +0000297 continue
David Benjaminf025abe2021-09-17 22:59:19 +0000298 # HTTP headers are encoded in Latin-1.
299 sock.send(b'%s: %s\r\n' %
300 (name.encode('latin-1'), value.encode('latin-1')))
301 sock.send(b'\r\n')
Adam Rice54443aa2018-06-06 00:11:54 +0000302 # This is wrong: it will pass through connection-level headers and
303 # misbehave on connection reuse. The only reason it works at all is that
304 # our test servers have never supported connection reuse.
305 # TODO(ricea): Use a proper HTTP client library instead.
bashi@chromium.org33233532012-09-08 17:37:24 +0000306 self._start_read_write(sock)
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000307 except Exception:
Adam Rice54443aa2018-06-06 00:11:54 +0000308 logging.exception('failure in common method: %s %s', self.command, path)
bashi@chromium.org33233532012-09-08 17:37:24 +0000309 self.send_response(500)
310 self.end_headers()
311 finally:
312 if sock is not None:
313 sock.close()
314
315 def do_CONNECT(self):
316 try:
317 pos = self.path.rfind(':')
318 host = self.path[:pos]
319 port = int(self.path[pos+1:])
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000320 except Exception:
bashi@chromium.org33233532012-09-08 17:37:24 +0000321 self.send_response(400)
322 self.end_headers()
323
Adam Rice9476b8c2018-08-02 15:28:43 +0000324 if ProxyRequestHandler.redirect_connect_to_localhost:
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100325 host = "127.0.0.1"
326
Adam Rice54443aa2018-06-06 00:11:54 +0000327 sock = None
bashi@chromium.org33233532012-09-08 17:37:24 +0000328 try:
329 sock = socket.create_connection((host, port))
330 self.send_response(200, 'Connection established')
331 self.end_headers()
332 self._start_read_write(sock)
toyoshim@chromium.org9d7219e2012-10-25 03:30:10 +0000333 except Exception:
Adam Rice54443aa2018-06-06 00:11:54 +0000334 logging.exception('failure in CONNECT: %s', path)
bashi@chromium.org33233532012-09-08 17:37:24 +0000335 self.send_response(500)
336 self.end_headers()
337 finally:
Adam Rice54443aa2018-06-06 00:11:54 +0000338 if sock is not None:
339 sock.close()
bashi@chromium.org33233532012-09-08 17:37:24 +0000340
341 def do_GET(self):
342 self._do_common_method()
343
344 def do_HEAD(self):
345 self._do_common_method()
346
Adam Rice9476b8c2018-08-02 15:28:43 +0000347class BasicAuthProxyRequestHandler(ProxyRequestHandler):
348 """A request handler that behaves as a proxy server which requires
349 basic authentication.
350 """
351
352 _AUTH_CREDENTIAL = 'Basic Zm9vOmJhcg==' # foo:bar
353
354 def parse_request(self):
355 """Overrides parse_request to check credential."""
356
357 if not ProxyRequestHandler.parse_request(self):
358 return False
359
David Benjaminf025abe2021-09-17 22:59:19 +0000360 auth = self.headers.get('Proxy-Authorization', None)
Adam Rice9476b8c2018-08-02 15:28:43 +0000361 if auth != self._AUTH_CREDENTIAL:
362 self.send_response(407)
363 self.send_header('Proxy-Authenticate', 'Basic realm="MyRealm1"')
364 self.end_headers()
365 return False
366
367 return True
368
bashi@chromium.org33233532012-09-08 17:37:24 +0000369
mattm@chromium.org830a3712012-11-07 23:00:07 +0000370class ServerRunner(testserver_base.TestServerRunner):
371 """TestServerRunner for the net test servers."""
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000372
mattm@chromium.org830a3712012-11-07 23:00:07 +0000373 def __init__(self):
374 super(ServerRunner, self).__init__()
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000375
mattm@chromium.org830a3712012-11-07 23:00:07 +0000376 def __make_data_dir(self):
377 if self.options.data_dir:
378 if not os.path.isdir(self.options.data_dir):
379 raise testserver_base.OptionError('specified data dir not found: ' +
380 self.options.data_dir + ' exiting...')
381 my_data_dir = self.options.data_dir
382 else:
383 # Create the default path to our data dir, relative to the exe dir.
Asanka Herath0ec37152019-08-02 15:23:57 +0000384 my_data_dir = os.path.join(BASE_DIR, "..", "..", "data")
phajdan.jr@chromium.orgbf74e2b2010-08-17 20:07:11 +0000385
mattm@chromium.org830a3712012-11-07 23:00:07 +0000386 return my_data_dir
newt@chromium.org1fc32742012-10-20 00:28:35 +0000387
mattm@chromium.org830a3712012-11-07 23:00:07 +0000388 def create_server(self, server_data):
389 port = self.options.port
390 host = self.options.host
newt@chromium.org1fc32742012-10-20 00:28:35 +0000391
Adam Rice54443aa2018-06-06 00:11:54 +0000392 logging.basicConfig()
393
estark21667d62015-04-08 21:00:16 -0700394 # Work around a bug in Mac OS 10.6. Spawning a WebSockets server
395 # will result in a call to |getaddrinfo|, which fails with "nodename
396 # nor servname provided" for localhost:0 on 10.6.
Adam Rice54443aa2018-06-06 00:11:54 +0000397 # TODO(ricea): Remove this if no longer needed.
estark21667d62015-04-08 21:00:16 -0700398 if self.options.server_type == SERVER_WEBSOCKET and \
399 host == "localhost" and \
400 port == 0:
401 host = "127.0.0.1"
402
Ryan Sleevi3bfd15d2018-01-23 21:12:24 +0000403 # Construct the subjectAltNames for any ad-hoc generated certificates.
404 # As host can be either a DNS name or IP address, attempt to determine
405 # which it is, so it can be placed in the appropriate SAN.
406 dns_sans = None
407 ip_sans = None
408 ip = None
409 try:
410 ip = socket.inet_aton(host)
411 ip_sans = [ip]
412 except socket.error:
413 pass
414 if ip is None:
415 dns_sans = [host]
416
mattm@chromium.org830a3712012-11-07 23:00:07 +0000417 if self.options.server_type == SERVER_HTTP:
418 if self.options.https:
David Benjamin8ed48d12021-09-14 21:28:30 +0000419 if not self.options.cert_and_key_file:
420 raise testserver_base.OptionError('server cert file not specified')
421 if not os.path.isfile(self.options.cert_and_key_file):
422 raise testserver_base.OptionError(
423 'specified server cert file not found: ' +
424 self.options.cert_and_key_file + ' exiting...')
David Benjaminf025abe2021-09-17 22:59:19 +0000425 pem_cert_and_key = open(self.options.cert_and_key_file, 'r').read()
mattm@chromium.org830a3712012-11-07 23:00:07 +0000426
427 for ca_cert in self.options.ssl_client_ca:
428 if not os.path.isfile(ca_cert):
429 raise testserver_base.OptionError(
430 'specified trusted client CA file not found: ' + ca_cert +
431 ' exiting...')
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000432
433 stapled_ocsp_response = None
David Benjaminf025abe2021-09-17 22:59:19 +0000434 server = HTTPSServer(
435 (host, port), TestPageHandler, pem_cert_and_key,
436 self.options.ssl_client_auth, self.options.ssl_client_ca,
437 self.options.ssl_client_cert_type, self.options.ssl_bulk_cipher,
438 self.options.ssl_key_exchange, self.options.alpn_protocols,
439 self.options.npn_protocols, self.options.tls_intolerant,
440 self.options.tls_intolerance_type,
441 base64.b64decode(self.options.signed_cert_timestamps_tls_ext),
442 self.options.fallback_scsv, stapled_ocsp_response,
443 self.options.alert_after_handshake, self.options.disable_channel_id,
444 self.options.disable_extended_master_secret,
445 self.options.simulate_tls13_downgrade,
446 self.options.simulate_tls12_downgrade, self.options.tls_max_version)
447 print('HTTPS server started on https://%s:%d...' %
448 (host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000449 else:
450 server = HTTPServer((host, port), TestPageHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000451 print('HTTP server started on http://%s:%d...' %
452 (host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000453
454 server.data_dir = self.__make_data_dir()
455 server.file_root_url = self.options.file_root_url
456 server_data['port'] = server.server_port
mattm@chromium.org830a3712012-11-07 23:00:07 +0000457 elif self.options.server_type == SERVER_WEBSOCKET:
mattm@chromium.org830a3712012-11-07 23:00:07 +0000458 # TODO(toyoshim): Remove following os.chdir. Currently this operation
459 # is required to work correctly. It should be fixed from pywebsocket side.
460 os.chdir(self.__make_data_dir())
461 websocket_options = WebSocketOptions(host, port, '.')
davidben@chromium.org009843a2014-06-03 00:13:08 +0000462 scheme = "ws"
mattm@chromium.org830a3712012-11-07 23:00:07 +0000463 if self.options.cert_and_key_file:
davidben@chromium.org009843a2014-06-03 00:13:08 +0000464 scheme = "wss"
mattm@chromium.org830a3712012-11-07 23:00:07 +0000465 websocket_options.use_tls = True
Sergey Ulanovdd8b8ea2017-09-08 22:53:25 +0000466 key_path = os.path.join(ROOT_DIR, self.options.cert_and_key_file)
467 if not os.path.isfile(key_path):
468 raise testserver_base.OptionError(
469 'specified server cert file not found: ' +
470 self.options.cert_and_key_file + ' exiting...')
471 websocket_options.private_key = key_path
472 websocket_options.certificate = key_path
473
mattm@chromium.org830a3712012-11-07 23:00:07 +0000474 if self.options.ssl_client_auth:
pneubeck@chromium.orgf5007112014-07-21 15:22:41 +0000475 websocket_options.tls_client_cert_optional = False
mattm@chromium.org830a3712012-11-07 23:00:07 +0000476 websocket_options.tls_client_auth = True
477 if len(self.options.ssl_client_ca) != 1:
478 raise testserver_base.OptionError(
479 'one trusted client CA file should be specified')
480 if not os.path.isfile(self.options.ssl_client_ca[0]):
481 raise testserver_base.OptionError(
482 'specified trusted client CA file not found: ' +
483 self.options.ssl_client_ca[0] + ' exiting...')
484 websocket_options.tls_client_ca = self.options.ssl_client_ca[0]
David Benjaminf025abe2021-09-17 22:59:19 +0000485 print('Trying to start websocket server on %s://%s:%d...' %
486 (scheme, websocket_options.server_host, websocket_options.port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000487 server = WebSocketServer(websocket_options)
David Benjaminf025abe2021-09-17 22:59:19 +0000488 print('WebSocket server started on %s://%s:%d...' %
489 (scheme, host, server.server_port))
mattm@chromium.org830a3712012-11-07 23:00:07 +0000490 server_data['port'] = server.server_port
ricea@chromium.orga52ebdc2014-07-29 07:42:29 +0000491 websocket_options.use_basic_auth = self.options.ws_basic_auth
Adam Rice9476b8c2018-08-02 15:28:43 +0000492 elif self.options.server_type == SERVER_PROXY:
493 ProxyRequestHandler.redirect_connect_to_localhost = \
494 self.options.redirect_connect_to_localhost
495 server = ThreadingHTTPServer((host, port), ProxyRequestHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000496 print('Proxy server started on port %d...' % server.server_port)
Adam Rice9476b8c2018-08-02 15:28:43 +0000497 server_data['port'] = server.server_port
mattm@chromium.org830a3712012-11-07 23:00:07 +0000498 elif self.options.server_type == SERVER_BASIC_AUTH_PROXY:
Adam Rice9476b8c2018-08-02 15:28:43 +0000499 ProxyRequestHandler.redirect_connect_to_localhost = \
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100500 self.options.redirect_connect_to_localhost
Adam Rice34b2e312018-04-06 16:48:30 +0000501 server = ThreadingHTTPServer((host, port), BasicAuthProxyRequestHandler)
David Benjaminf025abe2021-09-17 22:59:19 +0000502 print('BasicAuthProxy server started on port %d...' % server.server_port)
mattm@chromium.org830a3712012-11-07 23:00:07 +0000503 server_data['port'] = server.server_port
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000504 else:
mattm@chromium.org830a3712012-11-07 23:00:07 +0000505 raise testserver_base.OptionError('unknown server type' +
506 self.options.server_type)
erikkay@google.com70397b62008-12-30 21:49:21 +0000507
mattm@chromium.org830a3712012-11-07 23:00:07 +0000508 return server
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000509
mattm@chromium.org830a3712012-11-07 23:00:07 +0000510 def add_options(self):
511 testserver_base.TestServerRunner.add_options(self)
Adam Rice9476b8c2018-08-02 15:28:43 +0000512 self.option_parser.add_option('--proxy', action='store_const',
513 const=SERVER_PROXY,
514 default=SERVER_HTTP, dest='server_type',
515 help='start up a proxy server.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000516 self.option_parser.add_option('--basic-auth-proxy', action='store_const',
517 const=SERVER_BASIC_AUTH_PROXY,
518 default=SERVER_HTTP, dest='server_type',
519 help='start up a proxy server which requires '
520 'basic authentication.')
521 self.option_parser.add_option('--websocket', action='store_const',
522 const=SERVER_WEBSOCKET, default=SERVER_HTTP,
523 dest='server_type',
524 help='start up a WebSocket server.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000525 self.option_parser.add_option('--https', action='store_true',
526 dest='https', help='Specify that https '
527 'should be used.')
528 self.option_parser.add_option('--cert-and-key-file',
529 dest='cert_and_key_file', help='specify the '
530 'path to the file containing the certificate '
531 'and private key for the server in PEM '
532 'format')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000533 self.option_parser.add_option('--tls-intolerant', dest='tls_intolerant',
534 default='0', type='int',
535 help='If nonzero, certain TLS connections '
536 'will be aborted in order to test version '
537 'fallback. 1 means all TLS versions will be '
538 'aborted. 2 means TLS 1.1 or higher will be '
539 'aborted. 3 means TLS 1.2 or higher will be '
davidbendf2e3862017-04-12 15:23:34 -0700540 'aborted. 4 means TLS 1.3 or higher will be '
mattm@chromium.org830a3712012-11-07 23:00:07 +0000541 'aborted.')
davidben@chromium.orgbbf4f402014-06-27 01:16:55 +0000542 self.option_parser.add_option('--tls-intolerance-type',
543 dest='tls_intolerance_type',
544 default="alert",
545 help='Controls how the server reacts to a '
546 'TLS version it is intolerant to. Valid '
547 'values are "alert", "close", and "reset".')
ekasper@google.com3bce2cf2013-12-17 00:25:51 +0000548 self.option_parser.add_option('--signed-cert-timestamps-tls-ext',
549 dest='signed_cert_timestamps_tls_ext',
ekasper@google.com24aa8222013-11-28 13:43:26 +0000550 default='',
551 help='Base64 encoded SCT list. If set, '
552 'server will respond with a '
553 'signed_certificate_timestamp TLS extension '
554 'whenever the client supports it.')
agl@chromium.orgd0e11ca2013-12-11 20:16:13 +0000555 self.option_parser.add_option('--fallback-scsv', dest='fallback_scsv',
556 default=False, const=True,
557 action='store_const',
558 help='If given, TLS_FALLBACK_SCSV support '
559 'will be enabled. This causes the server to '
560 'reject fallback connections from compatible '
561 'clients (e.g. Chrome).')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000562 self.option_parser.add_option('--ssl-client-auth', action='store_true',
563 help='Require SSL client auth on every '
564 'connection.')
565 self.option_parser.add_option('--ssl-client-ca', action='append',
566 default=[], help='Specify that the client '
567 'certificate request should include the CA '
568 'named in the subject of the DER-encoded '
569 'certificate contained in the specified '
570 'file. This option may appear multiple '
571 'times, indicating multiple CA names should '
572 'be sent in the request.')
davidben@chromium.orgc52e2e62014-05-20 21:51:44 +0000573 self.option_parser.add_option('--ssl-client-cert-type', action='append',
574 default=[], help='Specify that the client '
575 'certificate request should include the '
576 'specified certificate_type value. This '
577 'option may appear multiple times, '
578 'indicating multiple values should be send '
579 'in the request. Valid values are '
580 '"rsa_sign", "dss_sign", and "ecdsa_sign". '
581 'If omitted, "rsa_sign" will be used.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000582 self.option_parser.add_option('--ssl-bulk-cipher', action='append',
583 help='Specify the bulk encryption '
584 'algorithm(s) that will be accepted by the '
davidben26254762015-01-29 14:32:53 -0800585 'SSL server. Valid values are "aes128gcm", '
586 '"aes256", "aes128", "3des", "rc4". If '
587 'omitted, all algorithms will be used. This '
588 'option may appear multiple times, '
589 'indicating multiple algorithms should be '
590 'enabled.');
davidben@chromium.org74aa8dd2014-04-11 07:20:26 +0000591 self.option_parser.add_option('--ssl-key-exchange', action='append',
592 help='Specify the key exchange algorithm(s)'
593 'that will be accepted by the SSL server. '
davidben405745f2015-04-03 11:35:35 -0700594 'Valid values are "rsa", "dhe_rsa", '
595 '"ecdhe_rsa". If omitted, all algorithms '
596 'will be used. This option may appear '
597 'multiple times, indicating multiple '
598 'algorithms should be enabled.');
bnc5fb33bd2016-08-05 12:09:21 -0700599 self.option_parser.add_option('--alpn-protocols', action='append',
600 help='Specify the list of ALPN protocols. '
601 'The server will not send an ALPN response '
602 'if this list does not overlap with the '
603 'list of protocols the client advertises.')
bnc609ad4c2015-10-02 05:11:24 -0700604 self.option_parser.add_option('--npn-protocols', action='append',
bnc5fb33bd2016-08-05 12:09:21 -0700605 help='Specify the list of protocols sent in '
bnc609ad4c2015-10-02 05:11:24 -0700606 'an NPN response. The server will not'
607 'support NPN if the list is empty.')
mattm@chromium.org830a3712012-11-07 23:00:07 +0000608 self.option_parser.add_option('--file-root-url', default='/files/',
609 help='Specify a root URL for files served.')
ricea@chromium.orga52ebdc2014-07-29 07:42:29 +0000610 # TODO(ricea): Generalize this to support basic auth for HTTP too.
611 self.option_parser.add_option('--ws-basic-auth', action='store_true',
612 dest='ws_basic_auth',
613 help='Enable basic-auth for WebSocket')
davidben21cda342015-03-17 18:04:28 -0700614 self.option_parser.add_option('--alert-after-handshake',
615 dest='alert_after_handshake',
616 default=False, action='store_true',
617 help='If set, the server will send a fatal '
618 'alert immediately after the handshake.')
nharper1e8bf4b2015-09-18 12:23:02 -0700619 self.option_parser.add_option('--disable-channel-id', action='store_true')
620 self.option_parser.add_option('--disable-extended-master-secret',
621 action='store_true')
David Benjaminf839f1c2018-10-16 06:01:29 +0000622 self.option_parser.add_option('--simulate-tls13-downgrade',
623 action='store_true')
624 self.option_parser.add_option('--simulate-tls12-downgrade',
625 action='store_true')
626 self.option_parser.add_option('--tls-max-version', default='0', type='int',
627 help='If non-zero, the maximum TLS version '
628 'to support. 1 means TLS 1.0, 2 means '
629 'TLS 1.1, and 3 means TLS 1.2.')
Pavol Marko8ccaaed2018-01-04 18:40:04 +0100630 self.option_parser.add_option('--redirect-connect-to-localhost',
631 dest='redirect_connect_to_localhost',
632 default=False, action='store_true',
633 help='If set, the Proxy server will connect '
634 'to localhost instead of the requested URL '
635 'on CONNECT requests')
erikkay@google.comd5182ff2009-01-08 20:45:27 +0000636
toyoshim@chromium.org16f57522012-10-24 06:14:38 +0000637
initial.commit94958cf2008-07-26 22:42:52 +0000638if __name__ == '__main__':
mattm@chromium.org830a3712012-11-07 23:00:07 +0000639 sys.exit(ServerRunner().main())