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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441"""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 PathTIME_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 preturn Nonedef _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):returnseen.add(path)try:lines = Path(path).read_text(encoding="utf-8", errors="replace").splitlines()except OSError:returnin_match = Falsefor i, ln in enumerate(lines, 1):s = ln.split("#", 1)[0]m = _KV.match(s)if not m:continuek, v = m.group(1).lower(), m.group(2)if k == "match":in_match = True # a Match block's lines apply to some connections onlycontinueif k == "include":for arg in v.split():target = arg if arg.startswith("/") else "/etc/ssh/" + argif not (target == "/etc/ssh" or target.startswith("/etc/ssh/")):outside.append("%s (Include in %s:%d)" % (arg, os.path.relpath(path, root), i))continuefor p in sorted(glob.glob(os.path.join(root, target.lstrip("/")))):_walk(root, p, seen, out, outside, depth + 1)continueif 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 Nonesha = 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 Nonereturn 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 saidsubprocess.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() - t0if 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 linesha = 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 + 1i += 1elif c.isspace():i += 1elif c == "#":while i < n and text[i] != "\n":i += 1elif c in "{};":out.append((c, line, i - col0))i += 1elif c in _QUOTES:j = i + 1while j < n and text[j] != c:j += 2 if text[j] == "\\" else 1out.append((text[i + 1:j], line, i - col0))i = j + 1else:j = iwhile j < n and not text[j].isspace() and text[j] not in "{};#":j += 1out.append((text[i:j], line, i - col0))i = jreturn outdef _parse(path, files, root_prefix, depth=0):"""the block tree of one loaded file: [{"name", "args", "file", "line", "text", "src", "children"}]"""import fnmatchtext = 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] += 1if t == "}":return itemsif t in (";", "{"):if not words:continuename, 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 Nonenode = {"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 itemsreturn 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 inheriteddef _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 outdef walk(children, inherited, scope):for n in children:if n["children"] is None or n["name"] not in ("server", "location"):continuehere = {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 settingsfor 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):returnseen.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/" + argif not target.startswith("/etc/nginx/"):outside.append("%s (include in %s)" % (arg, os.path.relpath(path, root)))continuefor 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() - t0if 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 = {}, Nonefor 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] += lnfiles = {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 gofor 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 Noneif ":" in a and not a.endswith("]"):host, _, port = a.rpartition(":")else:host, port = "", aif not port.isdigit():return Noneif 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 shlexif 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 "):continuehead, *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:continueloc = locs[-1].split()[-1] if locs else "/"if not loc.startswith("/"):loc = "/" # a regex or named location: its prefix is not known hereif 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 locationfor r_ in ng.get("roots", []):mine = os.path.join(root, r_.lstrip("/"))if not os.path.isdir(mine):continuesubs = [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 = [], Truefor r_ in ng.get("roots", []):if r_.startswith("/etc/nginx/") or r_ == "/etc/nginx":continuemine = os.path.join(root, r_.lstrip("/"))if os.path.isdir(mine) and os.path.isdir(r_):binds.append((mine, r_))else:listings = Falseholes.append("the web root %s is not in this folder; listings there were not observed" % r_)tmp = tempfile.mkdtemp(prefix="o7-ngobs-")q = shlex.quotelines = ["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 Noneelif kind == "LIST":row["listed"] = val.strip() not in ("", "0")return {"served": list(served.values()), "holes": holes}# ------------------------------------------------------------------------------------------- the sealed manual store (5.B)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441"""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 PathTIME_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 preturn Nonedef _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):returnseen.add(path)try:lines = Path(path).read_text(encoding="utf-8", errors="replace").splitlines()except OSError:returnin_match = Falsefor i, ln in enumerate(lines, 1):s = ln.split("#", 1)[0]m = _KV.match(s)if not m:continuek, v = m.group(1).lower(), m.group(2)if k == "match":in_match = True # a Match block's lines apply to some connections onlycontinueif k == "include":for arg in v.split():target = arg if arg.startswith("/") else "/etc/ssh/" + argif not (target == "/etc/ssh" or target.startswith("/etc/ssh/")):outside.append("%s (Include in %s:%d)" % (arg, os.path.relpath(path, root), i))continuefor p in sorted(glob.glob(os.path.join(root, target.lstrip("/")))):_walk(root, p, seen, out, outside, depth + 1)continueif 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 Nonesha = 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 Nonereturn 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 saidsubprocess.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() - t0if 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 linesha = 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 + 1i += 1elif c.isspace():i += 1elif c == "#":while i < n and text[i] != "\n":i += 1elif c in "{};":out.append((c, line, i - col0))i += 1elif c in _QUOTES:j = i + 1while j < n and text[j] != c:j += 2 if text[j] == "\\" else 1out.append((text[i + 1:j], line, i - col0))i = j + 1else:j = iwhile j < n and not text[j].isspace() and text[j] not in "{};#":j += 1out.append((text[i:j], line, i - col0))i = jreturn outdef _parse(path, files, root_prefix, depth=0):"""the block tree of one loaded file: [{"name", "args", "file", "line", "text", "src", "children"}]"""import fnmatchtext = 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] += 1if t == "}":return itemsif t in (";", "{"):if not words:continuename, 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 Nonenode = {"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 itemsreturn 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 inheriteddef _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 outdef walk(children, inherited, scope):for n in children:if n["children"] is None or n["name"] not in ("server", "location"):continuehere = {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 settingsfor 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):returnseen.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/" + argif not target.startswith("/etc/nginx/"):outside.append("%s (include in %s)" % (arg, os.path.relpath(path, root)))continuefor 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() - t0if 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 = {}, Nonefor 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] += lnfiles = {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 gofor 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 Noneif ":" in a and not a.endswith("]"):host, _, port = a.rpartition(":")else:host, port = "", aif not port.isdigit():return Noneif 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 shlexif 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 "):continuehead, *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:continueloc = locs[-1].split()[-1] if locs else "/"if not loc.startswith("/"):loc = "/" # a regex or named location: its prefix is not known hereif 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 locationfor r_ in ng.get("roots", []):mine = os.path.join(root, r_.lstrip("/"))if not os.path.isdir(mine):continuesubs = [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 = [], Truefor r_ in ng.get("roots", []):if r_.startswith("/etc/nginx/") or r_ == "/etc/nginx":continuemine = os.path.join(root, r_.lstrip("/"))if os.path.isdir(mine) and os.path.isdir(r_):binds.append((mine, r_))else:listings = Falseholes.append("the web root %s is not in this folder; listings there were not observed" % r_)tmp = tempfile.mkdtemp(prefix="o7-ngobs-")q = shlex.quotelines = ["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 Noneelif kind == "LIST":row["listed"] = val.strip() not in ("", "0")return {"served": list(served.values()), "holes": holes}# ------------------------------------------------------------------------------------------- the sealed manual store (5.B)
275 unmodified lines27627727827928028169 unmodified lines3513523533543553563573583593603613623633643655 unmodified lines37137237337437537637737837938038118 unmodified lines40040140240340440540640740839 unmodified lines448449450451452453454455456275 unmodified linest = node.testa, 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 req.get("empty"):g = guard(src, fn, wanted_value)if g:69 unmodified lineshas_pytest = Falsefuncs = 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.executablecmds = []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 checkcmds.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))else:cmds.append("%s %s" % (sys.executable, rel))return " && ".join(cmds)5 unmodified linesreturn runjail.env(root=root, PYTHONDONTWRITEBYTECODE="1")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 theold 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,env=_runenv(root))return r.returncode == 0, ((r.stdout or "") + (r.stderr or ""))[-3000:], r.returncodeexcept subprocess.TimeoutExpired:18 unmodified linesif 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_cmd_again = [check_cmd]if check_cmd is not None:baseline_ok = run_check(check_cmd, root)[0]if baseline_ok:check_cmd = None # the check passes already: it cannot judge this changeif not found:39 unmodified linestried += 1_write(p, new)ok, out, code = run_check(check_cmd, root)if ok:return {"done": True, "file": p, "function": fn.name, "what": what, "before": src, "after": new,"checked": True, "check_out": out, "tried": tried, "considered": considered}_write(p, src)# Amendment 13b: no single move passes - two moves together, the most likely first, on parts that do not overlapall_spans = [c for c in cs if c[3] is not None]275 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930069 unmodified lines3703713723733743753763773783793803813823833843853865 unmodified lines39239339439539639739839940040140240340440540640740840941041141241341441541618 unmodified lines43543643743843944044144244344439 unmodified lines484485486487488489490491492493275 unmodified linest = node.testa, 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 += pbefore = {t.id for st in fn.body if isinstance(st, ast.Assign) and st.lineno < node.linenofor 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 baseparams = [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 lineshas_pytest = Falsefuncs = 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 -rA -p no:cacheprovider" % sys.executable # 12.0.2: each test's outcome is readcmds = []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 checkcmds.append('%s -c "import runpy,sys; sys.path.insert(0,\'.\'); m=runpy.run_path(\'%s\'); ''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 linesreturn 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 theold compiled code (found in the first acceptance run: every right candidate was judged by the stale file)"""try: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.returncodeexcept subprocess.TimeoutExpired:18 unmodified linesif 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 = Nonebase_out = ""_cmd_again = [check_cmd]if check_cmd is not None:baseline_ok, base_out, _bc = run_check(check_cmd, root)if baseline_ok:check_cmd = None # the check passes already: it cannot judge this changeif not found:39 unmodified linestried += 1_write(p, new)ok, out, code = run_check(check_cmd, root)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,"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 overlapall_spans = [c for c in cs if c[3] is not None]
16 unmodified lines17181920212216 unmodified linesKEEP = {"O7_NET_SCOPE", "O7_DENY_PORTS"} # set below for the run itselfdef 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()]16 unmodified lines17181920212223242526272829303132333435363738394041424344454647484916 unmodified linesKEEP = {"O7_NET_SCOPE", "O7_DENY_PORTS"} # set below for the run itselfdef 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 thewhole group is killed, so a shell's children and a test's own processes do not outlive the check (a repair candidate'shung tests ran on for hours after the shell was killed). Same result and TimeoutExpired as subprocess.run."""import signalimport subprocesskw.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.PIPEp = 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()raisereturn 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