File size: 23,197 Bytes
6b3e8a3 04e89f2 | 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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | """effective - a service's settings as the service itself resolves them (12.5 step 12d(ii), round-2 design 5.A).
The audit used to read the main config file's text, which disagrees with the running service whenever an Include overrides
a line, a keyword repeats (sshd keeps the first value it obtains), a keyword is written in another case, or a keyword is
unset and takes its default. Here the installed service is asked: `sshd -T`, run inside a private mount namespace in which
the conversation's folder's etc/ssh stands at /etc/ssh, so absolute includes resolve inside the folder and never read this
machine's own /etc. Each value becomes a part (key, effective value, origin pointer); the origin comes from walking the
Include directives in the order sshd reads them and is a pointer for the fix, never the judge.
What it cannot read is a hole with its reason, never a fallback: no root (a mount namespace needs it), no sshd here, an
Include pointing outside the folder, a configuration sshd rejects, a dump past its time or byte allowance. The receipt says
"the installed sshd reports": a compromised binary is a stated limit, not something checked. The dump is kept with its sha
so the reading can be replayed."""
import glob
import hashlib
import os
import re
import shutil
import subprocess
import tempfile
import time
from pathlib import Path
TIME_ALLOWANCE = 20 # seconds for one dump (a guard; a cut is a counted hole)
BYTE_ALLOWANCE = 262144 # bytes of one dump (a guard; a cut is a counted hole)
_KV = re.compile(r"^\s*([A-Za-z][A-Za-z0-9]*)\s*(?:=\s*|\s+)(.*?)\s*$")
def _sshd_bin():
for p in ("/usr/sbin/sshd", shutil.which("sshd") or ""):
if p and os.access(p, os.X_OK):
return p
return None
def _walk(root, path, seen, out, outside, depth=0):
"""sshd's reading order: each line where it stands, an Include read in place (glob results in sorted order); -> appends
(file, line number, keyword lowercased, value, line text) to out; Include targets outside etc/ssh go to outside"""
if depth > 16 or path in seen or not os.path.isfile(path):
return
seen.add(path)
try:
lines = Path(path).read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
return
in_match = False
for i, ln in enumerate(lines, 1):
s = ln.split("#", 1)[0]
m = _KV.match(s)
if not m:
continue
k, v = m.group(1).lower(), m.group(2)
if k == "match":
in_match = True # a Match block's lines apply to some connections only
continue
if k == "include":
for arg in v.split():
target = arg if arg.startswith("/") else "/etc/ssh/" + arg
if not (target == "/etc/ssh" or target.startswith("/etc/ssh/")):
outside.append("%s (Include in %s:%d)" % (arg, os.path.relpath(path, root), i))
continue
for p in sorted(glob.glob(os.path.join(root, target.lstrip("/")))):
_walk(root, p, seen, out, outside, depth + 1)
continue
if not in_match:
out.append((path, i, k, v.strip(), ln))
def _keep(dump, name="sshd-T"):
st = os.environ.get("ORACLE7_STATE")
if not st:
return None
sha = hashlib.sha256(dump.encode("utf-8", "replace")).hexdigest()
d = Path(st) / "dumps"
try:
d.mkdir(parents=True, exist_ok=True)
(d / ("%s-%s.txt" % (name, sha[:16]))).write_text(dump, encoding="utf-8")
except OSError:
return None
return str(d / ("%s-%s.txt" % (name, sha[:16])))
def sshd(root):
"""-> {"values": {keyword: value}, "origin": {keyword: (file, line, text)}, "receipt": {...}} or {"hole": reason}"""
conf = os.path.join(root, "etc/ssh/sshd_config")
if not os.path.isfile(conf):
return {"hole": "no etc/ssh/sshd_config in this folder"}
if os.name != "posix" or not hasattr(os, "geteuid") or os.geteuid() != 0 or not shutil.which("unshare"):
return {"hole": "not read: no permission (the service's own reading needs root and a private mount namespace here)"}
binary = _sshd_bin()
if binary is None:
return {"hole": "not read: no sshd on this machine to ask"}
order, outside = [], []
_walk(root, conf, set(), order, outside)
if outside:
return {"hole": "not read: an Include points outside this folder, so the service would read this machine's own "
"files: " + "; ".join(outside)}
tmp = tempfile.mkdtemp(prefix="o7-sshd-")
try:
keys = glob.glob(os.path.join(root, "etc/ssh/ssh_host_*_key"))
args = []
if not keys: # sshd -T needs a host key; a temporary one is supplied and said
subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", tmp + "/hk"], check=True,
capture_output=True, timeout=TIME_ALLOWANCE)
args = ["-o", "HostKey=" + tmp + "/hk"]
t0 = time.time()
try:
r = __import__("runjail").run(["unshare", "-m", "--propagation", "private", "sh", "-c",
'mount --bind "$0" /etc/ssh && exec "$@"', os.path.join(root, "etc/ssh"), binary, "-T"] + args,
capture_output=True, timeout=TIME_ALLOWANCE)
except subprocess.TimeoutExpired:
return {"hole": "not read: sshd -T ran past its %d s allowance" % TIME_ALLOWANCE}
secs = time.time() - t0
if len(r.stdout) > BYTE_ALLOWANCE:
return {"hole": "not read: sshd -T gave more than %d bytes; the cut is not read" % BYTE_ALLOWANCE}
out = r.stdout.decode("utf-8", "replace")
if r.returncode != 0 or not out.strip():
err = r.stderr.decode("utf-8", "replace").strip().splitlines()
return {"hole": "not read: sshd could not read this configuration (%s)" % ((err[-1] if err else "exit %d" % r.returncode)[:200])}
values = {}
for ln in out.splitlines():
k, _, v = ln.partition(" ")
if k and k.lower() not in values:
values[k.lower()] = v.strip()
origin = {}
for path, i, k, v, text in order:
origin.setdefault(k, (path, i, text)) # sshd keeps the first value it obtains: the pointer is that line
sha = hashlib.sha256(out.encode("utf-8", "replace")).hexdigest()
return {"values": values, "origin": origin,
"receipt": {"dump": "sshd -T", "says": "the installed sshd reports", "sha": sha, "bytes": len(out),
"seconds": round(secs, 2), "host_key_supplied": bool(args), "kept": _keep(out)}}
finally:
shutil.rmtree(tmp, ignore_errors=True)
# ------------------------------------------------------------------------------------------------------------- nginx
# nginx prints no resolved values: `nginx -T` prints every file it loaded under "# configuration file X:" headers. The dump
# is parsed into blocks (an include is expanded in place from the dump's own sections, glob matches in sorted order, as
# nginx reads them) and each directive is resolved where requests are served: a location takes its own setting, else its
# enclosing location's, server's, http's, else the default. DEFAULTS are named seeds (round-2 design Appendix B) until the
# sealed manual store (5.B) gives them from the installed package's own documentation.
DEFAULTS = {"server_tokens": "on", "autoindex": "off"}
_HEADER = re.compile(r"^# configuration file (\S+):\s*$")
_QUOTES = ('"', "'")
def _tokens(text):
"""-> [(token, line, col)] with a quoted string kept as one token; comments dropped"""
out, i, line, col0, n = [], 0, 1, 0, len(text)
while i < n:
c = text[i]
if c == "\n":
line, col0 = line + 1, i + 1
i += 1
elif c.isspace():
i += 1
elif c == "#":
while i < n and text[i] != "\n":
i += 1
elif c in "{};":
out.append((c, line, i - col0))
i += 1
elif c in _QUOTES:
j = i + 1
while j < n and text[j] != c:
j += 2 if text[j] == "\\" else 1
out.append((text[i + 1:j], line, i - col0))
i = j + 1
else:
j = i
while j < n and not text[j].isspace() and text[j] not in "{};#":
j += 1
out.append((text[i:j], line, i - col0))
i = j
return out
def _parse(path, files, root_prefix, depth=0):
"""the block tree of one loaded file: [{"name", "args", "file", "line", "text", "src", "children"}]"""
import fnmatch
text = files.get(path)
if text is None or depth > 16:
return []
lines = text.splitlines()
toks = _tokens(text)
pos = [0]
def block():
items, words = [], []
while pos[0] < len(toks):
t, ln, col = toks[pos[0]]
pos[0] += 1
if t == "}":
return items
if t in (";", "{"):
if not words:
continue
name, args = words[0][0], [w[0] for w in words[1:]]
wl, wc = words[0][1], words[0][2]
src = lines[wl - 1][wc:col + 1] if (t == ";" and ln == wl and wl - 1 < len(lines)) else None
node = {"name": name, "args": args, "file": path, "line": wl,
"text": lines[wl - 1] if wl - 1 < len(lines) else "", "src": src, "children": None}
if t == "{":
node["children"] = block()
if name == "include" and args and t == ";":
pat = args[0] if args[0].startswith("/") else root_prefix + "/" + args[0]
for p in sorted(x for x in files if fnmatch.fnmatch(x, pat)):
items += _parse(p, files, root_prefix, depth + 1)
else:
items.append(node)
words = []
else:
words.append((t, ln, col))
return items
return block()
def _own(children, k):
return next((n for n in children if n["name"] == k), None)
def _setting(children, k, inherited):
n = _own(children, k)
return ((n["args"][:1] or [""])[0], n) if n else inherited
def _resolve(tree, keys):
"""-> {key: [{"value", "scope", "origin": node or None}]} for every place requests are served"""
out = {k: [] for k in keys}
http = next((n for n in tree if n["name"] == "http" and n["children"] is not None), None)
if http is None:
return out
def walk(children, inherited, scope):
for n in children:
if n["children"] is None or n["name"] not in ("server", "location"):
continue
here = {k: _setting(n["children"], k, inherited[k]) for k in keys}
if n["name"] == "server":
listen = next((x["args"] for x in n["children"] if x["name"] == "listen"), None) or ["(default)"]
label = scope + ["server " + " ".join(listen)]
else:
label = scope + ["location " + " ".join(n["args"])]
locs = [c for c in n["children"] if c["name"] == "location" and c["children"] is not None]
catch_all = any(c["args"][-1:] == ["/"] for c in locs)
if n["name"] == "location" or not catch_all: # requests this block serves with its own settings
for k in keys:
out[k].append({"value": here[k][0], "scope": " / ".join(label), "origin": here[k][1]})
walk(n["children"], here, label)
base = {k: _setting(http["children"], k, (DEFAULTS.get(k), None)) for k in keys}
if not any(n["name"] == "server" for n in http["children"]):
for k in keys:
out[k].append({"value": base[k][0], "scope": "http", "origin": base[k][1]})
walk(http["children"], base, [])
return out
_INCLUDE_NG = re.compile(r"(?m)^[^#\n]*?\binclude\s+([^;#\r\n]+?)\s*;")
def _nginx_includes(root, path, seen, outside, depth=0):
if depth > 16 or path in seen or not os.path.isfile(path):
return
seen.add(path)
for t in _INCLUDE_NG.findall(Path(path).read_text(encoding="utf-8", errors="replace")):
arg = t.strip().strip("".join(_QUOTES))
target = arg if arg.startswith("/") else "/etc/nginx/" + arg
if not target.startswith("/etc/nginx/"):
outside.append("%s (include in %s)" % (arg, os.path.relpath(path, root)))
continue
for p in sorted(glob.glob(os.path.join(root, target.lstrip("/")))):
_nginx_includes(root, p, seen, outside, depth + 1)
def nginx(root, keys=("server_tokens", "autoindex")):
"""-> {"values": {key: [{"value", "scope", "origin"}]}, "receipt": {...}} or {"hole": reason}"""
conf = os.path.join(root, "etc/nginx/nginx.conf")
if not os.path.isfile(conf):
return {"hole": "no etc/nginx/nginx.conf in this folder"}
if os.name != "posix" or not hasattr(os, "geteuid") or os.geteuid() != 0 or not shutil.which("unshare"):
return {"hole": "not read: no permission (the service's own reading needs root and a private mount namespace here)"}
binary = next((p for p in ("/usr/sbin/nginx", shutil.which("nginx") or "") if p and os.access(p, os.X_OK)), None)
if binary is None:
return {"hole": "not read: no nginx on this machine to ask"}
outside = []
_nginx_includes(root, conf, set(), outside)
if outside:
return {"hole": "not read: an include points outside this folder, so nginx would read this machine's own files: " +
"; ".join(outside)}
t0 = time.time()
try:
r = __import__("runjail").run(["unshare", "-m", "--propagation", "private", "sh", "-c",
'mount --bind "$0" /etc/nginx && exec "$1" -T -e stderr', os.path.join(root, "etc/nginx"), binary],
capture_output=True, timeout=TIME_ALLOWANCE)
except subprocess.TimeoutExpired:
return {"hole": "not read: nginx -T ran past its %d s allowance" % TIME_ALLOWANCE}
secs = time.time() - t0
if len(r.stdout) > BYTE_ALLOWANCE:
return {"hole": "not read: nginx -T gave more than %d bytes; the cut is not read" % BYTE_ALLOWANCE}
out = r.stdout.decode("utf-8", "replace")
if r.returncode != 0 or not out.strip():
err = [x for x in r.stderr.decode("utf-8", "replace").strip().splitlines() if "[emerg]" in x or "failed" in x]
return {"hole": "not read: nginx could not load this configuration (%s)" % (
(err[0] if err else "exit %d" % r.returncode)[:200])}
files, cur = {}, None
for ln in out.splitlines(keepends=True):
m = _HEADER.match(ln.rstrip("\n"))
if m:
cur = m.group(1)
files[cur] = ""
elif cur is not None:
files[cur] += ln
files = {k: (v[:-1] if v.endswith("\n\n") else v) for k, v in files.items()}
tree = _parse("/etc/nginx/nginx.conf", files, "/etc/nginx")
vals = _resolve(tree, keys)
roots = []
def _roots(nodes):
for n_ in nodes:
if n_["name"] in ("root", "alias") and n_["args"] and n_["args"][0] not in roots:
roots.append(n_["args"][0])
if n_["children"]:
_roots(n_["children"])
_roots(tree)
for k in vals: # origins point into the folder, where a correction would go
for o in vals[k]:
if o["origin"] is not None:
o["origin"] = dict(o["origin"], file=os.path.join(root, o["origin"]["file"].lstrip("/")), children=None)
sha = hashlib.sha256(out.encode("utf-8", "replace")).hexdigest()
return {"values": vals, "roots": roots, "receipt": {"dump": "nginx -T", "says": "the installed nginx reports", "sha": sha,
"bytes": len(out), "seconds": round(secs, 2), "files": sorted(files),
"kept": _keep(out, "nginx-T")}}
# ------------------------------------------------------------------------------------------------- nginx observation (5.C)
# What the folder's nginx actually serves, observed read-only: its own nginx started inside a private mount and network
# namespace (the folder's etc/nginx at /etc/nginx; private tmpfs over nginx's log and state directories, so nothing is
# written on this machine), asked over loopback: the `Server:` header at each listen address, and whether each path whose
# autoindex resolves on returns a listing. A web root (root/alias) outside etc/nginx is served from the folder's own copy,
# bound over the same path inside the namespace; where the folder has no copy, listings are not observed (that would read
# this machine's own files) and that is said as a hole; the header is still asked. Used to upgrade a finding and, after a
# fix, to prove the effect changed.
def _listen_url(listen):
a = listen or "80"
if a.startswith("unix:"):
return None
if ":" in a and not a.endswith("]"):
host, _, port = a.rpartition(":")
else:
host, port = "", a
if not port.isdigit():
return None
if host in ("", "*", "0.0.0.0", "[::]", "[::1]"):
host = "127.0.0.1"
return "http://%s:%s" % (host, port)
def observe_nginx(root, ng):
"""-> {"served": [{"url", "server", "listed"}], "holes": [...]} or {"hole": reason}; `ng` is nginx()'s reading"""
import shlex
if ng.get("hole"):
return {"hole": ng["hole"]}
binary = next((p for p in ("/usr/sbin/nginx", shutil.which("nginx") or "") if p and os.access(p, os.X_OK)), None)
if binary is None or not hasattr(os, "geteuid") or os.geteuid() != 0:
return {"hole": "not observed: no nginx or no permission here"}
urls, holes = [], []
for o in ng["values"].get("autoindex", []) + ng["values"].get("server_tokens", []):
sc = o["scope"]
if not sc.startswith("server "):
continue
head, *locs = sc.split(" / location ")
listen = head[len("server "):].split()[0] if head[len("server "):].split() else "80"
base = _listen_url(listen) if listen != "(default)" else "http://127.0.0.1:80"
if not base:
continue
loc = locs[-1].split()[-1] if locs else "/"
if not loc.startswith("/"):
loc = "/" # a regex or named location: its prefix is not known here
if base + loc not in urls:
urls.append(base + loc)
if not urls:
return {"hole": "not observed: no listen address read"}
# a listing shows only for a folder with no index file: such folders of the folder's own copy of each web root are
# asked for under the catch-all location (other locations map paths their own way and are not guessed here)
for u in [x for x in urls if x.count("/") == 3]: # "http://host:port/": the catch-all location
for r_ in ng.get("roots", []):
mine = os.path.join(root, r_.lstrip("/"))
if not os.path.isdir(mine):
continue
subs = [d for d in sorted(os.listdir(mine)) if os.path.isdir(os.path.join(mine, d))
and not any(os.path.isfile(os.path.join(mine, d, i)) for i in ("index.html", "index.htm"))]
for d in subs[:3]:
v = u.rstrip("/") + "/" + d + "/"
if v not in urls:
urls.append(v)
binds, listings = [], True
for r_ in ng.get("roots", []):
if r_.startswith("/etc/nginx/") or r_ == "/etc/nginx":
continue
mine = os.path.join(root, r_.lstrip("/"))
if os.path.isdir(mine) and os.path.isdir(r_):
binds.append((mine, r_))
else:
listings = False
holes.append("the web root %s is not in this folder; listings there were not observed" % r_)
tmp = tempfile.mkdtemp(prefix="o7-ngobs-")
q = shlex.quote
lines = ["ip link set lo up", "mount --bind %s /etc/nginx || exit 3" % q(os.path.join(root, "etc/nginx"))]
lines += ["mount --bind %s %s || exit 3" % (q(a), q(b)) for a, b in binds]
lines += ['for d in /var/log/nginx /var/lib/nginx; do [ -d "$d" ] && mount -t tmpfs tmpfs "$d"; done',
"%s -e stderr -g %s || exit 4" % (q(binary), q("daemon on; pid %s/ng.pid;" % tmp)), "sleep 0.6"]
for u in urls:
lines.append("echo HEAD %s \"$(curl -s -m 3 -I %s | tr -d '\\r' | grep -i '^server:' | head -1)\"" % (q(u), q(u)))
if listings:
lines.append("echo LIST %s \"$(curl -s -m 3 %s | grep -c 'Index of')\"" % (q(u), q(u)))
lines.append("kill $(cat %s) 2>/dev/null; true" % q(tmp + "/ng.pid"))
try:
r = __import__("runjail").run(["unshare", "-m", "-n", "--propagation", "private", "sh", "-c", "\n".join(lines)],
capture_output=True, text=True, timeout=TIME_ALLOWANCE)
except subprocess.TimeoutExpired:
return {"hole": "not observed: past the %d s allowance" % TIME_ALLOWANCE}
finally:
shutil.rmtree(tmp, ignore_errors=True)
if r.returncode != 0:
err = r.stderr.strip().splitlines()
return {"hole": "not observed: the folder's nginx did not start (%s)" % ((err[-1] if err else "exit %d" % r.returncode)[:200])}
served = {}
for ln in r.stdout.splitlines():
kind, _, rest = ln.partition(" ")
u, _, val = rest.partition(" ")
row = served.setdefault(u, {"url": u, "server": None, "listed": None})
if kind == "HEAD":
row["server"] = val.split(":", 1)[1].strip() if ":" in val else None
elif kind == "LIST":
row["listed"] = val.strip() not in ("", "0")
return {"served": list(served.values()), "holes": holes}
# ------------------------------------------------------------------------------------------- the sealed manual store (5.B)
def manual(service, keyword):
"""the installed package's own manual entry for a keyword, from the store sealed at freeze
(tools/build_manual_store.py): {"name", "paragraphs", "default", "sha"}, {"hole": reason}, or None when the store holds
no entry for it. The store's sha is checked against its seal on every read; a store that does not match is a hole."""
p = os.environ.get("ORACLE7_MANUAL_STORE") or str(Path(__file__).resolve().parent / "local" / "manual_store.json")
if not os.path.isfile(p) or not os.path.isfile(p + ".sha256"):
return {"hole": "no sealed manual store here"}
blob = Path(p).read_bytes()
sha = hashlib.sha256(blob).hexdigest()
if sha != Path(p + ".sha256").read_text().split()[0].strip():
return {"hole": "the manual store does not match its seal, so it is not read"}
import json as _json
svc = (_json.loads(blob.decode("utf-8")).get("services") or {}).get(service) or {}
e = (svc.get("entries") or {}).get(keyword.lower())
if not e:
return None
return {"name": svc.get("name"), "paragraphs": e.get("paragraphs") or [], "default": e.get("default"), "sha": sha}
|