: asapien/superpulse

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 
#!/usr/bin/env python3
"""Real lighttpd + synthetic HTTP/FastCGI services; no production or real secrets."""
import http.client
import json
import os
from pathlib import Path
import shutil
import socket
import socketserver
import struct
import subprocess
import tempfile
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

ROOT = Path(__file__).resolve().parents[1]
LIGHTTPD = os.environ.get('LIGHTTPD', shutil.which('lighttpd') or 'lighttpd')
hits = []


class Upstream(BaseHTTPRequestHandler):
    def do_GET(self):
        hits.append((self.path, dict(self.headers)))
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Set-Cookie', 'upstream=must-not-reach-browser')
        self.end_headers()
        self.wfile.write(json.dumps({'name': 'Synthetic device'}).encode())

    def log_message(self, *args):
        pass


def exact(conn, size):
    data = b''
    while len(data) < size:
        chunk = conn.recv(size - len(data))
        if not chunk:
            raise EOFError()
        data += chunk
    return data


def record(kind, rid, body=b''):
    return struct.pack('!BBHHBB', 1, kind, rid, len(body), 0, 0) + body


class Authorizer(socketserver.BaseRequestHandler):
    def handle(self):
        params = b''
        while True:
            _, kind, rid, size, padding, _ = struct.unpack('!BBHHBB', exact(self.request, 8))
            body = exact(self.request, size)
            exact(self.request, padding)
            if kind == 4:
                if body:
                    params += body
                    continue
                # Decode FastCGI name/value pairs, including 4-byte lengths.
                values = {}
                pos = 0
                def length():
                    nonlocal pos
                    value = params[pos]
                    if value & 128:
                        value = struct.unpack('!I', params[pos:pos + 4])[0] & 0x7fffffff
                        pos += 4
                    else:
                        pos += 1
                    return value
                while pos < len(params):
                    n, v = length(), length()
                    name = params[pos:pos + n].decode()
                    pos += n
                    values[name] = params[pos:pos + v].decode()
                    pos += v
                allowed = values.get('HTTP_COOKIE') == 'session=allowed'
                output = (b'Status: 200\r\nVariable-REMOTE_USER: synthetic\r\n\r\n' if allowed
                          else b'Status: 403\r\nContent-Type: text/plain\r\n\r\nDenied')
                self.request.sendall(record(6, rid, output) + record(6, rid)
                                     + record(3, rid, b'\0' * 8))
                return


with tempfile.TemporaryDirectory(prefix='superpulse-proxy-') as directory:
    tmp = Path(directory)
    upstream = ThreadingHTTPServer(('127.0.0.1', 0), Upstream)
    auth = socketserver.ThreadingUnixStreamServer(str(tmp / 'auth.sock'), Authorizer)
    for server in (upstream, auth):
        threading.Thread(target=server.serve_forever, daemon=True).start()
    with socket.socket() as probe:
        probe.bind(('127.0.0.1', 0))
        port = probe.getsockname()[1]
    secret = tmp / 'snipeit.conf'
    secret.write_text('var.superpulse.snipeit-token = "synthetic-not-a-secret"\n')
    secret.chmod(0o600)
    # Only substitute deployment addresses; exercise the actual shipped policy.
    snippet = (ROOT / 'deploy/superpulse-proxy.conf').read_text()
    snippet = snippet.replace('/etc/superpulse/snipeit.conf', str(secret))
    snippet = snippet.replace('"port" => 81', f'"port" => {upstream.server_port}')
    (tmp / 'policy.conf').write_text(snippet)
    config = tmp / 'lighttpd.conf'
    config.write_text(f'''
server.document-root = "{tmp}"
server.bind = "127.0.0.1"
server.port = {port}
server.errorlog = "{tmp}/error.log"
server.modules = ( "mod_access", "mod_fastcgi", "mod_setenv", "mod_proxy" )
$HTTP["host"] == "logs.saikrupagas.com" {{
    fastcgi.server = ( "/" => (( "socket" => "{tmp}/auth.sock",
        "check-local" => "disable", "mode" => "authorizer" )) )
    proxy.server = ( "" => (( "host" => "127.0.0.1", "port" => {upstream.server_port} )) )
    include "{tmp}/policy.conf"
}}
''')
    command = [LIGHTTPD]
    if os.environ.get('LIGHTTPD_MODULES'):
        command += ['-m', os.environ['LIGHTTPD_MODULES']]
    subprocess.run(command + ['-tt', '-f', str(config)], check=True)
    with (tmp / 'process.log').open('w+') as log:
        process = subprocess.Popen(command + ['-D', '-f', str(config)], stdout=log, stderr=log)
        try:
            for _ in range(100):
                if process.poll() is not None:
                    raise RuntimeError((tmp / 'error.log').read_text())
                try:
                    with socket.create_connection(('127.0.0.1', port), timeout=.1):
                        break
                except OSError:
                    time.sleep(.05)
            else:
                raise RuntimeError('lighttpd startup timeout')

            def request(path, method='GET', authorized=True, host='logs.saikrupagas.com'):
                conn = http.client.HTTPConnection('127.0.0.1', port, timeout=5)
                headers = {'Host': host, 'Authorization': 'Bearer attacker-value'}
                if authorized:
                    headers['Cookie'] = 'session=allowed'
                conn.request(method, path, headers=headers)
                response = conn.getresponse()
                result = response.status, dict(response.getheaders()), response.read()
                conn.close()
                return result

            status, headers, body = request('/api/devices/TEST_1-2.3')
            assert status == 200, (status, body)
            path, received = hits[-1]
            assert path == '/api/v1/hardware/bytag/TEST_1-2.3', path
            assert received['Host'] == 'equipment.saikrupagas.com', received
            assert received['Authorization'] == 'Bearer synthetic-not-a-secret'
            assert headers['Cache-Control'] == 'no-store', headers
            assert not any(k.lower() == 'set-cookie' for k in headers), headers
            assert b'synthetic-not-a-secret' not in body

            count = len(hits)
            for path, method, allowed in [
                ('/api/devices/TEST', 'GET', False),
                ('/api/devices/TEST', 'POST', True),
                ('/api/devices/TEST', 'HEAD', True),
                ('/api/devices/TEST?search=anything', 'GET', True),
                ('/api/devices', 'GET', True),
                ('/api/devices/', 'GET', True),
                ('/api/devices/TEST/extra', 'GET', True),
                ('/api/devices/.hidden', 'GET', True),
                ('/.env.php', 'GET', True),
                ('/logs.php?id=TEST', 'GET', True),
                ('/deploy/superpulse-proxy.conf', 'GET', True),
            ]:
                status, _, _ = request(path, method, allowed)
                assert status in (400, 403, 405), (path, method, status)
                assert len(hits) == count, (path, 'unexpected upstream request')
            request('/index.html')
            assert hits[-1][0] == '/index.html'
            assert hits[-1][1]['Host'] == 'logs.saikrupagas.com'
            assert hits[-1][1]['Authorization'] == 'Bearer attacker-value'
            assert request('/api/devices/TEST', host='unrelated.example')[0] == 404
            secret.unlink()
            assert subprocess.run(command + ['-tt', '-f', str(config)],
                                  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0
            print('PASS: auth gate, fixed route/host, token replacement, method/query restrictions, '
                  'private paths, no-store, cookie suppression, vhost isolation, missing-secret failure')
        finally:
            process.terminate()
            process.wait(timeout=5)
            upstream.shutdown()
            auth.shutdown()