168 lines
7.9 KiB
Python
168 lines
7.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Run basic normal-workflow and security checks against an isolated loopback daemon.
|
|
|
|
Usage: python3 tests/security_server.py /path/to/build
|
|
Build with BUILD_SECURITY_TESTS=ON; sanitizer builds are recommended.
|
|
"""
|
|
import base64
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import signal
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import urllib.parse
|
|
|
|
BUILD = Path(sys.argv[1]).resolve()
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
checks = []
|
|
|
|
|
|
def check(condition, name):
|
|
if not condition:
|
|
raise AssertionError(name)
|
|
checks.append(name)
|
|
print("PASS:", name, flush=True)
|
|
|
|
|
|
def multipart(fields, files=()):
|
|
boundary = "elog-security-boundary-12345"
|
|
parts = []
|
|
for key, value in fields:
|
|
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n'.encode() + str(value).encode() + b'\r\n')
|
|
for key, filename, data in files:
|
|
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + data + b'\r\n')
|
|
return b''.join(parts) + f'--{boundary}--\r\n'.encode(), f'multipart/form-data; boundary={boundary}'
|
|
|
|
|
|
with tempfile.TemporaryDirectory(prefix="elog-security-") as temp:
|
|
directory = Path(temp)
|
|
books = directory / "logbooks"
|
|
books.mkdir()
|
|
users = directory / "users.xml"
|
|
hashed = subprocess.check_output([str(BUILD / "elogd_security_tests"), "--hash", "test-password"], text=True).strip()
|
|
def account(name, inactive, pending=""):
|
|
return f'<user><name>{name}</name><password encoding="SHA256">{hashed}</password><full_name>{name}</full_name><email>test@example.invalid</email><inactive>{inactive}</inactive>{pending}</user>'
|
|
users.write_text('<?xml version="1.0"?><list>' + account('admin', 0) + account('disabled', 1) + account('pending', 123456, '<activation_code>123456</activation_code>') + '</list>')
|
|
config = directory / "elogd.cfg"
|
|
config.write_text(f'''[global]
|
|
Logging Level = 0
|
|
Resolve host names = 0
|
|
Allow clone = 0
|
|
[public]
|
|
Attributes = Subject
|
|
Menu commands = List, New, Edit, Delete, Config, Import, CSV Import, XML Import
|
|
[protected]
|
|
Attributes = Subject
|
|
Password file = {users}
|
|
Admin user = admin
|
|
Menu commands = List, New, Edit, Delete, Config, Import, CSV Import, XML Import
|
|
[web]
|
|
Attributes = Subject
|
|
Password file = {users}
|
|
Authentication = Webserver
|
|
[denied]
|
|
Attributes = Subject
|
|
Hosts deny = 127.0.0.1
|
|
''')
|
|
with socket.socket() as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
port = sock.getsockname()[1]
|
|
log = directory / "server.log"
|
|
stream = log.open("wb")
|
|
env = dict(os.environ, UBSAN_OPTIONS="halt_on_error=1", ASAN_OPTIONS="abort_on_error=1")
|
|
process = subprocess.Popen([str(BUILD / "elogd"), "-c", str(config), "-d", str(books), "-s", str(ROOT), "-n", "127.0.0.1", "-p", str(port)], stdout=stream, stderr=subprocess.STDOUT, env=env)
|
|
def request(path, fields=None, files=(), cookie=None, headers=None):
|
|
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=15)
|
|
headers = dict(headers or {})
|
|
headers["Connection"] = "close"
|
|
if cookie:
|
|
headers["Cookie"] = cookie
|
|
body = None
|
|
method = "GET"
|
|
if fields is not None:
|
|
method = "POST"
|
|
body, headers["Content-Type"] = multipart(fields, files)
|
|
connection.request(method, path, body, headers)
|
|
response = connection.getresponse()
|
|
if response.headers.get_all("X-Frame-Options") != ["SAMEORIGIN"]:
|
|
raise AssertionError(f"missing or duplicate clickjacking header on {method} {path}")
|
|
response_headers = dict(response.getheaders())
|
|
response_headers['Set-Cookie'] = '\n'.join(response.headers.get_all('Set-Cookie', []))
|
|
result = response.status, response_headers, response.read().decode(errors="replace")
|
|
connection.close()
|
|
return result
|
|
def raw(payload):
|
|
with socket.create_connection(("127.0.0.1", port), timeout=5) as sock:
|
|
sock.sendall(payload)
|
|
sock.shutdown(socket.SHUT_WR)
|
|
sock.settimeout(10)
|
|
response = bytearray()
|
|
try:
|
|
while True:
|
|
part = sock.recv(65536)
|
|
if not part:
|
|
break
|
|
response.extend(part)
|
|
except (ConnectionResetError, socket.timeout):
|
|
pass
|
|
return bytes(response)
|
|
def alive():
|
|
check(process.poll() is None and request('/public/')[0] == 200, 'daemon remains responsive')
|
|
try:
|
|
deadline = time.monotonic() + 15
|
|
while time.monotonic() < deadline:
|
|
if process.poll() is not None:
|
|
raise RuntimeError(log.read_text())
|
|
try:
|
|
if request('/public/')[0] == 200:
|
|
break
|
|
except OSError:
|
|
time.sleep(.1)
|
|
else:
|
|
raise RuntimeError('daemon did not start')
|
|
check(request('/public/')[0] == 200, 'public page includes clickjacking header')
|
|
check(request('/missing/')[0] == 404, 'error page includes clickjacking header')
|
|
check(request('/public/elog.css')[0] == 200, 'static file includes clickjacking header')
|
|
check(request('/protected/')[0] == 200, 'login page available')
|
|
status, headers, body = request('/protected/', [('uname', 'admin'), ('upassword', 'test-password')])
|
|
match = re.search(r'sid=([0-9a-f]{30})', headers.get('Set-Cookie', ''))
|
|
check(status == 302 and match is not None, 'password login works')
|
|
cookie = 'sid=' + match.group(1)
|
|
check(request('/protected/?cmd=Config', cookie=cookie)[0] == 200, 'authenticated configuration page works')
|
|
status, headers, body = request('/public/', [('notignore', '1')], [('csvfile', 'input.csv', b'csv-success\r\n')])
|
|
check('1 entries successfully imported' in body, 'CSV import works')
|
|
xml = b'<ELOG_LIST><ENTRY><MID>12345</MID><DATE>Mon, 19 Oct 2026 12:00:00 +0200</DATE><ENCODING>plain</ENCODING><Subject>xml-success</Subject><TEXT>xml body</TEXT></ENTRY></ELOG_LIST>'
|
|
status, headers, body = request('/public/', [('keep', '1')], [('xmlfile', 'input.xml', xml)])
|
|
check('1 entries successfully imported' in body, 'XML import works')
|
|
for encoding in ['plain', 'ELCode']:
|
|
status, headers, body = request('/public/', [('cmd', 'Preview'), ('Subject', 'preview'), ('encoding', encoding), ('Text', 'Basic preview :)')])
|
|
check(status == 200, 'entry preview works for ' + encoding)
|
|
status, headers, body = request('/public/', [('cmd', 'Preview'), ('Subject', 'table'), ('encoding', 'ELCode'), ('Text', '[table border="1" cellpadding="20" width=75%]cell[/table]')])
|
|
check('<table border="1" cellpadding="20" width="75%">' in body, 'table formatting preserved')
|
|
binary = b'\x00binary attachment\x00end'
|
|
request('/public/', [('cmd', 'Upload')], [('attfile', 'example.txt', binary)])
|
|
found = list(books.rglob('*example.txt'))
|
|
check(len(found) == 1 and found[0].read_bytes() == binary, 'attachment upload works')
|
|
request('/protected/', [], [('csvfile', 'input.csv', b'ignored\r\n')])
|
|
check(not list((books / 'protected').rglob('*.log')), 'protected import requires login')
|
|
raw(b'GET malformed\r\n\r\n')
|
|
alive()
|
|
check('AddressSanitizer' not in log.read_text() and 'runtime error:' not in log.read_text(), 'server checks completed without sanitizer errors')
|
|
print(json.dumps({'passed': len(checks)}, indent=2), flush=True)
|
|
finally:
|
|
process.send_signal(signal.SIGINT) if process.poll() is None else None
|
|
try:
|
|
process.wait(timeout=10)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait()
|
|
stream.close()
|
|
if process.returncode not in (0, -signal.SIGINT):
|
|
print(log.read_text(), file=sys.stderr)
|