Release 12.0.2 (full): 12.0.1 with the repairs found by a first-use sweep: a question is read from its subject's page, turns reach the part that does them, repair judges by the tests that bear on the change. No language model. (part 3)
Browse filesHead oracle_release_runtime_w575. Root 3fc01a97657a2db7011175cebcd8c1e3a2894250e3c0e555f01c228f281ccc86. Supersedes 12.0.1 (b2c7c856387d). Judged by sweep48 and accept47q (both frozen before 12.0.2 code; records/12/sw48_*.json, a47q_*.json), accept46 7/7, and every earlier frozen set and both gates (records/12/q65_report.txt). Changelog: CHANGELOG_1202.md.
Files changed (4)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441"""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 = subprocess.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 = subprocess.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 = subprocess.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}
"""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 overridesa line, a keyword repeats (sshd keeps the first value it obtains), a keyword is written in another case, or a keyword isunset and takes its default. Here the installed service is asked: `sshd -T`, run inside a private mount namespace in whichthe conversation's folder's etc/ssh stands at /etc/ssh, so absolute includes resolve inside the folder and never read thismachine's own /etc. Each value becomes a part (key, effective value, origin pointer); the origin comes from walking theInclude 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, anInclude 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 shaso the reading can be replayed."""import globimport hashlibimport osimport reimport shutilimport subprocessimport tempfileimport timefrom 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)275 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930069 unmodified lines3703713723543733743753763773783793613623803813823833843853865 unmodified lines39239339439539639739839940040140240340440540640740840941041141237841341441541618 unmodified lines43543643743843944040544144244344439 unmodified lines484485486451487488453489490491492493275 unmodified lines t = node.test a, b = _off(starts, t.lineno, t.col_offset), _off(starts, t.end_lineno, t.end_col_offset) add(70, "condition negated on line %d" % t.lineno, a, b, "not (%s)" % src[a:b]) if isinstance(node, (ast.For, ast.While)): # 12.0.2: t = p in a loop, where t was set before it -> t += p before = {t.id for st in fn.body if isinstance(st, ast.Assign) and st.lineno < node.lineno for t in st.targets if isinstance(t, ast.Name)} for st in ast.walk(node): if isinstance(st, ast.Assign) and len(st.targets) == 1 and isinstance(st.targets[0], ast.Name) \ and st.targets[0].id in before \ and st.targets[0].id not in {n.id for n in ast.walk(st.value) if isinstance(n, ast.Name)}: a, b = _off(starts, st.lineno, st.col_offset), _off(starts, st.end_lineno, st.end_col_offset) v0, v1 = _off(starts, st.value.lineno, st.value.col_offset), _off(starts, st.value.end_lineno, st.value.end_col_offset) for op, tok in (("Add", "+="), ("Mult", "*="), ("Sub", "-=")): add(5 if op in target else 40, "%s = -> %s %s on line %d" % (st.targets[0].id, st.targets[0].id, tok, st.lineno), a, b, "%s %s %s" % (st.targets[0].id, tok, src[v0:v1])) if isinstance(node, ast.Return) and isinstance(node.value, ast.BinOp): # 12.0.2: a share taken off its base params = [x.arg for x in fn.args.args if x.arg not in ("self", "cls")] used = [n.id for n in ast.walk(node.value) if isinstance(n, ast.Name) and n.id in params] v0, v1 = _off(starts, node.value.lineno, node.value.col_offset), _off(starts, node.value.end_lineno, node.value.end_col_offset) for pn in dict.fromkeys(used): for tok in ("-", "+"): add(25, "%s %s (...) on line %d" % (pn, tok, node.lineno), v0, v1, "%s %s %s" % (pn, tok, src[v0:v1])) if req.get("empty"): g = guard(src, fn, wanted_value) if g:69 unmodified lines has_pytest = False funcs = any(re.search(r"(?m)^\s*def test_", p.read_text(encoding="utf-8", errors="ignore")) for p in tests) if has_pytest and funcs: return "%s -m pytest -q -x" % sys.executable return "%s -m pytest -q -rA -p no:cacheprovider" % sys.executable # 12.0.2: each test's outcome is read cmds = [] for p in tests[:20]: rel = str(p.relative_to(root)).replace(os.sep, "/") if re.search(r"(?m)^\s*def test_", p.read_text(encoding="utf-8", errors="ignore")): # test functions with no pytest here: each one called, the first failure fails the check cmds.append('%s -c "import runpy,sys; sys.path.insert(0,\'.\'); m=runpy.run_path(\'%s\'); ' 't=[v for k,v in sorted(m.items()) if k.startswith(\'test_\') and callable(v)]; ' '[f() for f in t]; print(len(t), \'tests passed\')"' % (sys.executable, rel)) 't=[(k,v) for k,v in sorted(m.items()) if k.startswith(\'test_\') and callable(v)]; ' 'exec(\'bad=0\\nfor k,v in t:\\n try:\\n v(); print(\\\'PASSED %s::\\\'+k)\\n except Exception:\\n ' 'bad+=1; print(\\\'FAILED %s::\\\'+k)\'); print(len(t)-bad, \'of\', len(t), \'tests passed\'); ' 'sys.exit(1 if bad else 0)"' % (sys.executable, rel, rel, rel)) else: cmds.append("%s %s" % (sys.executable, rel)) return " && ".join(cmds)5 unmodified lines return runjail.env(root=root, PYTHONDONTWRITEBYTECODE="1")
def passed_tests(out): return set(re.findall(r"(?m)^PASSED (\S+)", out or ""))
def failed_tests(out): return set(re.findall(r"(?m)^(?:FAILED|ERROR) (\S+)", out or ""))
def better(base_out, out): """12.0.2: tests that failed before pass now, and none that passed fails""" bp, np_ = passed_tests(base_out), passed_tests(out) return bool(bp is not None and np_ - bp) and bp <= np_ and failed_tests(out) <= failed_tests(base_out)
def run_check(cmd, root, timeout=90): """no bytecode is written or trusted: a one-character change of the same size in the same second would otherwise run the old compiled code (found in the first acceptance run: every right candidate was judged by the stale file)""" try: r = subprocess.run(cmd, shell=True, cwd=str(root), capture_output=True, text=True, timeout=timeout, r = __import__("runjail").run(cmd, shell=True, cwd=str(root), capture_output=True, text=True, timeout=timeout, env=_runenv(root)) return r.returncode == 0, ((r.stdout or "") + (r.stderr or ""))[-3000:], r.returncode except subprocess.TimeoutExpired:18 unmodified lines if hit and not [w for w in req["about"] if any(_stem(w) == _stem(x) for c in found[:1] for x in _words(c[2].name))]: found = hit + [c for c in found if c not in hit] baseline_ok = None base_out = "" _cmd_again = [check_cmd] if check_cmd is not None: baseline_ok = run_check(check_cmd, root)[0] baseline_ok, base_out, _bc = run_check(check_cmd, root) if baseline_ok: check_cmd = None # the check passes already: it cannot judge this change if not found:39 unmodified lines tried += 1 _write(p, new) ok, out, code = run_check(check_cmd, root) if ok: if ok or better(base_out, out): return {"done": True, "file": p, "function": fn.name, "what": what, "before": src, "after": new, "checked": True, "check_out": out, "tried": tried, "considered": considered} "checked": True, "check_out": out, "tried": tried, "considered": considered, "partial": [] if ok else sorted(failed_tests(out))} _write(p, src) # Amendment 13b: no single move passes - two moves together, the most likely first, on parts that do not overlap all_spans = [c for c in cs if c[3] is not None]16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484916 unmodified linesKEEP = {"O7_NET_SCOPE", "O7_DENY_PORTS"} # set below for the run itself
def run(args, timeout=None, **kw): """12.0.2: subprocess.run, bounded for what it starts: the command runs in its own process group, and past its time the whole group is killed, so a shell's children and a test's own processes do not outlive the check (a repair candidate's hung tests ran on for hours after the shell was killed). Same result and TimeoutExpired as subprocess.run.""" import signal import subprocess kw.pop("start_new_session", None) capture = kw.pop("capture_output", False) if capture: kw["stdout"] = kw.get("stdout", subprocess.PIPE) kw["stderr"] = kw.get("stderr", subprocess.PIPE) data = kw.pop("input", None) if data is not None: kw["stdin"] = subprocess.PIPE p = subprocess.Popen(args, start_new_session=True, **kw) try: out, err = p.communicate(data, timeout=timeout) except subprocess.TimeoutExpired: try: os.killpg(p.pid, signal.SIGKILL) except OSError: p.kill() p.communicate() raise return subprocess.CompletedProcess(args, p.returncode, out, err)
def head_ports(): """the ports the head listens on (set by server.main at start)""" return [p for p in (os.environ.get("ORACLE7_HEAD_PORT") or "").split(",") if p.strip().isdigit()]workbench/effective.py+438-438
workbench/repair.py+44-7
workbench/runjail.py+27
workbench/server.py