Cherry-picked X-Frame-Options
This commit is contained in:
1 parent
6ff11275bd
commit
940dd5f3a9
2 files changed
+177
No files matched your search
@@ -7189,6 +7189,7 @@ void redirect(LOGBOOK *lbs, const char *rel_path) {
|
||||
/* redirect */
|
||||
rsprintf("HTTP/1.1 302 Found\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
if (keep_alive) {
|
||||
rsprintf("Connection: Keep-Alive\r\n");
|
||||
rsprintf("Keep-Alive: timeout=60, max=10\r\n");
|
||||
@@ -7436,6 +7437,7 @@ void show_http_header(LOGBOOK *lbs, BOOL expires, const char *cookie, int code)
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
|
||||
if (getcfg("global", "charset", str, sizeof(str)))
|
||||
rsprintf("Content-Type: text/html;charset=%s\r\n", str);
|
||||
@@ -7462,6 +7464,7 @@ void show_plain_header(int size, const char *file_name) {
|
||||
/* header */
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
rsprintf("Accept-Ranges: bytes\r\n");
|
||||
|
||||
if (keep_alive) {
|
||||
@@ -8230,6 +8233,7 @@ void show_error(const char *error) {
|
||||
/* header */
|
||||
rsprintf("HTTP/1.1 404 Not Found\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
if (getcfg("global", "charset", str, sizeof(str)))
|
||||
rsprintf("Content-Type: text/html;charset=%s\r\n", str);
|
||||
else
|
||||
@@ -8296,6 +8300,7 @@ void set_sid_cookie(LOGBOOK *lbs, const char *sid, const char *full_name) {
|
||||
|
||||
rsprintf("HTTP/1.1 302 Found\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
if (keep_alive) {
|
||||
rsprintf("Connection: Keep-Alive\r\n");
|
||||
rsprintf("Keep-Alive: timeout=60, max=10\r\n");
|
||||
@@ -8360,6 +8365,7 @@ void send_file_direct(char *file_name, bool allow_html) {
|
||||
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
rsprintf("Accept-Ranges: bytes\r\n");
|
||||
|
||||
/* set expiration time to one day if no thumbnail */
|
||||
@@ -15575,6 +15581,7 @@ int show_md5_page(LOGBOOK *lbs) {
|
||||
/* header */
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
rsprintf("Accept-Ranges: bytes\r\n");
|
||||
rsprintf("Connection: close\r\n");
|
||||
rsprintf("Content-Type: text/plain;charset=%s\r\n", DEFAULT_HTTP_CHARSET);
|
||||
@@ -19647,6 +19654,7 @@ void show_rss_feed(LOGBOOK *lbs) {
|
||||
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
|
||||
if (!getcfg("global", "charset", charset, sizeof(charset)))
|
||||
strcpy(charset, DEFAULT_HTTP_CHARSET);
|
||||
@@ -27079,6 +27087,7 @@ void show_uploader_json(LOGBOOK *lbs) {
|
||||
|
||||
rsprintf("HTTP/1.1 200 Document follows\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
rsprintf("Accept-Ranges: bytes\r\n");
|
||||
rsprintf("Pragma: no-cache\r\n");
|
||||
rsprintf("Cache-control: private, max-age=0, no-cache, no-store\r\n");
|
||||
@@ -30294,6 +30303,7 @@ void server_loop(void) {
|
||||
/* just return header */
|
||||
rsprintf("HTTP/1.1 200 OK\r\n");
|
||||
rsprintf("Server: ELOG HTTP %s-%s\r\n", VERSION, git_revision());
|
||||
rsprintf("X-Frame-Options: SAMEORIGIN\r\n");
|
||||
rsprintf("Connection: close\r\n");
|
||||
rsprintf("Content-Type: text/html\r\n\r\n");
|
||||
keep_alive = FALSE;
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/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)
|
||||
Reference in new issue
Block a user