Última actualización: 2026-12-02

DAY 029 OF 1600 · 2026-11-01

Day 029 — The bound promised seven hours, and the earliest the job could finish was eight

A student's private learning log · one concept at a time. Date: 2026-11-01 · Day: 29 of 1600 Log: a student's private learning log · one concept at a time. ---

Concept #29 — A lower bound is a promise about what is impossible, not a plan

MA07, Operations Research, week 3. The course stops asking what do I choose and asks what do I do first . The notes frame it as planning: a state, actions that change it, a goal, and the cost of the whole trajectory. Once the state contains resources, the thing being optimised stops being a route and becomes a schedule — the crews exist, the jobs have hours, and some jobs cannot start until another one is finished. Two bounds get taught before any algorithm, and both are honest. The work bound : total hours divided by the number of crews. The precedence bound : the longest chain of dependent jobs, because that chain has to be worked straight through. Instance A is five independent jobs — 3, 3, 2, 2, 2 hours — on two identical crews. Work bound 12/2 = 6 . Precedence bound 3, because nothing depends on anything. The stronger of the two is 6, and 6 is achievable. The greedy rule everybody writes first — *longest job on the earliest free crew* — finishes at 7 , which is 16.67% over. The interesting part is not that the greedy rule loses. It is where it loses. I pushed all 120 priority orders through the same scheduler: 24 of them finish in 6 . The scheduler is not the problem and it never was. The priority rule is. Feeding the two 3-hour jobs first is exactly what the textbook heuristic says to do, and it leaves a 2-hour hole no crew can fill. The order that wins is not exotic: P1, P3, P4, P2, P5 — 3 and 2 on one crew, 2 and 2 and 2 on the other, both finishing at 6. Instance B is where the bounds themselves fall short of the truth. A chain A → B → C of 2 hours each, plus D = 4 and E = 4, on two crews. Work bound 14/2 = 7 . Precedence bound 6 (the chain). The stronger bound is 7. The earliest every job can actually finish is 8 . Both bounds are individually true and jointly useless: the chain needs a crew for six consecutive hours, and each of the two long jobs needs a crew of its own, so with two crews somebody waits. Longest-job-first finishes at 10 (+25%). Longest-chain-first finishes at 8 , which is the optimum, and 64 of the 120 orders get there. So the two lessons I keep from today, and they are the same lesson twice: a lower bound is a statement about what is impossible , never about what is achievable — instance B proves an 8 while both bounds promise 7 — and the difference between a good and a bad schedule on the same code is the priority rule, not the algorithm surrounding it. What I tried today: one file, stdlib only, no solver. A non-delay list scheduler, the two textbook bounds, a time-indexed exhaustive search for the true optimum, and all 120 priority permutations so that "the heuristic is off by N" is a measured number and not a phrase I copied. Five jobs, two crews, twelve and fourteen hours of work. # sched.py - MA07 (Operations Research), Week 3: planning over time and resources. # Source: the course notes on planning/scheduling (AIMA 11.1-11.3 and the bridge # to 11.6-11.7: time, resources, schedules). # # One idea only: two identical crews, a set of jobs, some precedences. Two textbook # lower bounds, both loose in different ways; a greedy list scheduler whose answer is # decided by the PRIORITY RULE, not by the scheduler. stdlib only, no solver. # # exact_makespan(): time-indexed exhaustive search. Machines are identical, so a # state is (done set, sorted free times). With no release dates, idling a machine # never helps, so earliest-start enumeration covers every schedule that matters. import itertools from functools import lru_cache MACHINES = 2 # name, duration, predecessors INST_A = [("P1", 3, ()), ("P2", 3, ()), ("P3", 2, ()), ("P4", 2, ()), ("P5", 2, ())] INST_B = [("A", 2, ()), ("B", 2, ("A",)), ("C", 2, ("B",)), ("D", 4, ()), ("E", 4, ())] def dur_of(jobs): return {n: d for n, d, _ in jobs} def pred_of(jobs): return {n: p for n, _, p in jobs} def work_lb(jobs, m): return -(-sum(d for _, d, _ in jobs) // m) def critical_path(jobs): """Longest precedence chain: the earliest any single task can finish.""" dur, pred, memo = dur_of(jobs), pred_of(jobs), {} def cp(n): if n not in memo: memo[n] = dur[n] + max((cp(p) for p in pred[n]), default=0) return memo[n] return max(cp(n) for n, _, _ in jobs) def downstream(jobs): """Hours still ahead of each task: its duration plus its longest successor chain.""" dur = dur_of(jobs) succ = {n: [] for n, _, _ in jobs} for n, _, pr in jobs: for p in pr: succ[p].append(n) memo = {} def tail(n): if n not in memo: memo[n] = dur[n] + max((tail(s) for s in succ[n]), default=0) return memo[n] return {n: tail(n) for n, _, _ in jobs} def list_schedule(jobs, order): """Non-delay list scheduling: walk the priority order, each picked job starts at the earliest time its predecessors are done and a crew is free.""" dur, pred = dur_of(jobs), pred_of(jobs) free, finish, started = [0] * MACHINES, {}, set() while len(started) < len(jobs): picked = next((n for n in order if n not in started and all(p in finish for p in pred[n])), None) if picked is None: raise RuntimeError("deadlock: cyclic precedence") m = free.index(min(free)) start = max(free[m], max((finish[p] for p in pred[picked]), default=0)) free[m] = start + dur[picked] finish[picked], _ = free[m], started.add(picked) return max(finish.values()) def exact_makespan(jobs): dur, pred = dur_of(jobs), pred_of(jobs) names = sorted(dur) idx = {n: i for i, n in enumerate(names)} pmask = {n: sum(1 << idx[p] for p in pred[n]) for n in names} @lru_cache(maxsize=None) def best(done, free): if done == (1 << len(names)) - 1: return max(free) out = None for n in names: if done >> idx[n] & 1 or pmask[n] & done != pmask[n]: continue for m in range(len(free)): nf = list(free) nf[m] += dur[n] v = best(done | (1 << idx[n]), tuple(sorted(nf))) out = v if out is None else min(out, v) return out return best(0, tuple([0] * MACHINES)) def run(tag, jobs): n_task = len(jobs) print(f"== {tag}: {n_task} jobs, {MACHINES} identical crews") for n, d, p in jobs: print(f" {n}: {d}h" + (" after " + ",".join(p) if p else " no predecessor")) wl, cp = work_lb(jobs, MACHINES), critical_path(jobs) print(f" bound from work = {wl} (total {sum(d for _, d, _ in jobs)}h / {MACHINES} crews, rounded up)") print(f" bound from precedence = {cp} (longest chain)") print(f" the stronger bound = {max(wl, cp)}") names = [n for n, _, _ in jobs] d = dur_of(jobs) lpt = sorted(names, key=lambda n: (-d[n], n)) tail = downstream(jobs) cpfirst = sorted(names, key=lambda n: (-tail[n], n)) m_lpt, m_cp = list_schedule(jobs, lpt), list_schedule(jobs, cpfirst) results = {} for order in itertools.permutations(names): results[order] = list_schedule(jobs, order) opt = exact_makespan(jobs) best_orders = [o for o, v in results.items() if v == min(results.values())] print(f" longest-job-first -> {m_lpt} priority {list(lpt)}") print(f" longest-chain-first -> {m_cp} priority {list(cpfirst)}") print(f" exhaustive: {len(results)} priority lists x exact search -> optimum {opt}") print(f" makespans the {len(results)} lists produced: {sorted(set(results.values()))}") print(f" {len(best_orders)} of them reach the optimum; example {list(best_orders[0])} -> {opt}") print(f" gap: longest-job-first {(m_lpt / opt - 1) * 100:+.2f}% " f"longest-chain-first {(m_cp / opt - 1) * 100:+.2f}%") print() return {"lb": max(wl, cp), "lpt": m_lpt, "cp": m_cp, "opt": opt, "best": list(best_orders[0]), "n_best": len(best_orders)} a = run("instance A: independent jobs", INST_A) b = run("instance B: one chain plus two long jobs", INST_B) print("== what the numbers say") print(f" A: bound {a['lb']}, optimum {a['opt']}, greedy shipped {a['lpt']}. " f"Same scheduler, order {a['best']}, makespan {a['opt']}.") print(f" B: bound {b['lb']}, optimum {b['opt']}, greedy shipped {b['lpt']} (longest-chain-first " f"gets {b['cp']}).") print(f" In B the two textbook bounds promise {b['lb']}; the earliest possible finish is " f"{b['opt']}, and the honest gap is {b['opt'] - b['lb']} hour(s) that no bound could see.") print(" A bound is a promise about what is impossible. Only a schedule says what is") print(" possible. And the list scheduler is not the bug: the priority rule is.") Real output: == instance A: independent jobs: 5 jobs, 2 identical crews P1: 3h no predecessor P2: 3h no predecessor P3: 2h no predecessor P4: 2h no predecessor P5: 2h no predecessor bound from work = 6 (total 12h / 2 crews, rounded up) bound from precedence = 3 (longest chain) the stronger bound = 6 longest-job-first -> 7 priority ['P1', 'P2', 'P3', 'P4', 'P5'] longest-chain-first -> 7 priority ['P1', 'P2', 'P3', 'P4', 'P5'] exhaustive: 120 priority lists x exact search -> optimum 6 makespans the 120 lists produced: [6, 7] 24 of them reach the optimum; example ['P1', 'P3', 'P4', 'P2', 'P5'] -> 6 gap: longest-job-first +16.67% longest-chain-first +16.67% == instance B: one chain plus two long jobs: 5 jobs, 2 identical crews A: 2h no predecessor B: 2h after A C: 2h after B D: 4h no predecessor E: 4h no predecessor bound from work = 7 (total 14h / 2 crews, rounded up) bound from precedence = 6 (longest chain) the stronger bound = 7 longest-job-first -> 10 priority ['D', 'E', 'A', 'B', 'C'] longest-chain-first -> 8 priority ['A', 'B', 'D', 'E', 'C'] exhaustive: 120 priority lists x exact search -> optimum 8 makespans the 120 lists produced: [8, 10] 64 of them reach the optimum; example ['A', 'B', 'D', 'E', 'C'] -> 8 gap: longest-job-first +25.00% longest-chain-first +0.00% == what the numbers say A: bound 6, optimum 6, greedy shipped 7. Same scheduler, order ['P1', 'P3', 'P4', 'P2', 'P5'], makespan 6. B: bound 7, optimum 8, greedy shipped 10 (longest-chain-first gets 8). In B the two textbook bounds promise 7; the earliest possible finish is 8, and the honest gap is 1 hour(s) that no bound could see. A bound is a promise about what is impossible. Only a schedule says what is possible. And the list scheduler is not the bug: the priority rule is. What I understood from it: the honest sentence is not "the greedy scheduler is bad". It is "the greedy scheduler is a decision procedure, and the priority list is the decision". On five jobs I can certify the optimum by exhaustive search, which is exactly what makes the measured gaps trustworthy and also exactly why this is not a method for a real schedule — the classic guarantee for list scheduling is a ratio of 2 − 1/m, which with two crews is 1.75, and both of my gaps sit inside it. The guarantee is real. It just does not tell you that the schedule in your hand is the 6-hour one when it is the 7-hour one, and nothing in the pipeline would. ---

Security #29 — The password field was a pattern, because five bytes were never escaped (CWE-90)

LDAP injection is not SQL injection with a different dialect. It is the same mistake — user input concatenated into a query — against a grammar that has its own escaping table, and in LDAP the table is short enough to memorise: in an assertion value, RFC 4515 says five bytes must never appear literally. Backslash, the wildcard * , the two parentheses and NUL. The filter the app builds for a login is one string: (&(uid= + user + )(userPassword= + password + )) . If none of those five bytes is escaped, the password field is not a value. It is a pattern. One asterisk is enough. (&(uid=admin)(userPassword=*)) matches the admin entry no matter what the password is, because means any string* in an assertion value. That is not an encoding trick or a parser quirk; it is the grammar doing precisely what it was specified to do with the byte the app should have escaped. Escape it per RFC 4515 — \2a — and the filter matches zero entries, because now it is asking for the literal two-character string a . The payload everybody quotes is the close-and-reopen one: )(uid= ))(|(uid=* . Concatenated, it produces two filters back to back. My parser is a strict subset of RFC 4515 and it answers ParseError: trailing data at 17 — which is what a real server does with that string, and it is the honest reason this payload does not land everywhere. The other half of the same measurement is why it lands at all: a helper that parses the first balanced filter and drops the rest returns 5 of 5 entries. The difference between those two answers is the difference between a demo and an incident, so I measured both instead of picking the one that looks better. The part that matters more has no bypass in it. No filter trick, no second condition, just a boolean: does (&(uid=admin)(userPassword=Verano*)) match? Yes or no is one bit per request, and one bit is enough. Walking the charset a character at a time recovered a 10-character password in 323 requests ; brute force over the same alphabet is 62^10 = 839,299,365,868,340,224. Nobody brute-forces a password. They ask the password whether it starts with V , and then whether it starts with Ve . And the second parameter nobody looks at: the attribute name . When it comes from a dropdown and gets concatenated like the value does, an allowlist is what closes it — my injected name dies as unknown attribute . Closing the name slot does not close the value slot, and closing neither is the default. The pattern I studied — one concatenation, and the five bytes nobody escapes: flt = "(&(uid=" + user + ")(userPassword=" + pw + "))" # pw = "*" -> (&(uid=admin)(userPassword=*)) 1 match, any password # pw = "Verano*" -> prefix oracle: brute force becomes a binary search # user = "*)(uid=*))(|(uid=*" -> two filters: strict servers refuse, lenient helpers obey What I understood about preventing it: # RFC 4515 section 3 — the only five bytes that matter in a value _MUST_ESCAPE = {"\\": "\\5c", "*": "\\2a", "(": "\\28", ")": "\\29", "\x00": "\\00"} def esc(value: str) -> str: return "".join(_MUST_ESCAPE.get(ch, ch) for ch in value) # attribute names are never user input: pick from a closed set, then interpolate ALLOWED = {"uid", "cn", "mail"} attr = attr if attr in ALLOWED else raise_400() flt = f"(&({attr}={esc(user)})(userPassword={esc(pw)}))" # and a DN is a different grammar: RFC 4514 escaping is NOT this function What I understood: "sanitize the input" is not a fix, it is a hope. The fix is one function that knows the grammar and lives in one place, applied to every slot that reaches the filter — and the knowledge that there are two grammars, not one: escaping a filter value (RFC 4515) does nothing for a DN (RFC 4514), so the code that builds a bind DN needs its own escaping or the same bug moves one line up. The bug is cheap to write, cheap to read past, and it does not crash: it returns rows, which is the worst behaviour a bug can have. The whole sandbox, one file, so every number above can be re-run: # ldap.py - CWE-90: LDAP filter injection (wildcards left unescaped). # stdlib only, in-memory directory, no network, no server. Everything runs on # this file. The filter parser is a strict subset of RFC 4515: it rejects # trailing data and unbalanced parentheses, exactly like a server would. # # The question: the app concatenates the login form into a filter and trusts # the grammar to keep the two conditions separate. Does it? DIRECTORY = [ {"uid": "admin", "cn": "Admin", "userPassword": "Verano2026", "role": "ops"}, {"uid": "marta", "cn": "Marta Ruiz", "userPassword": "marta123", "role": "user"}, {"uid": "diego", "cn": "Diego Soto", "userPassword": "qwerty", "role": "user"}, {"uid": "lucia", "cn": "Lucia Pena", "userPassword": "lucia2025", "role": "user"}, {"uid": "tomas", "cn": "Tomas Vera", "userPassword": "zxcvbn", "role": "user"}, ] ATTRS = ("uid", "cn", "userPassword", "role") class ParseError(ValueError): pass def parse(s, i=0): """filter := '(' ('&' filter+ | '|' filter+ | '!' filter | attr '=' value) ')'""" if i >= len(s) or s[i] != "(": raise ParseError(f"expected '(' at {i}") i += 1 if s[i] == "&" or s[i] == "|": op, i = s[i], i + 1 kids = [] while i < len(s) and s[i] == "(": k, i = parse(s, i) kids.append(k) if not kids: raise ParseError("empty &/|") node = (op, kids) elif s[i] == "!": k, i = parse(s, i + 1) node = ("!", [k]) else: j = s.index("=", i) attr, i = s[i:j], j + 1 j = s.index(")", i) val, i = s[i:j], j if attr not in ATTRS: raise ParseError(f"unknown attribute {attr!r}") node = ("=", [(attr, val)]) if i >= len(s) or s[i] != ")": raise ParseError(f"expected ')' at {i}") return node, i + 1 def evaluate(node, entry): op, kids = node if op == "&": return all(evaluate(k, entry) for k in kids) if op == "|": return any(evaluate(k, entry) for k in kids) if op == "!": return not evaluate(kids[0], entry) attr, val = kids[0] return match(entry.get(attr, ""), val) def match(text, assertion): """Equality with '*' as the substring wildcard, per RFC 4515 assertion values.""" parts = assertion.split("*") if len(parts) == 1: return text == assertion pos = 0 for k, p in enumerate(parts): if p == "": continue if k == 0: if not text.startswith(p): return False pos = len(p) elif k == len(parts) - 1: if not text.endswith(p) or len(text) - len(p) < pos: return False pos = len(text) else: found = text.find(p, pos) if found < 0: return False pos = found + len(p) return True def search(flt, strict=True): if strict: node, end = parse(flt) if end != len(flt): raise ParseError(f"trailing data at {end}: {flt[end:]!r}") else: node, _ = parse(flt) # lenient: first balanced filter wins return [e for e in DIRECTORY if evaluate(node, e)] def login(user, pw, strict=True): flt = "(&(uid=" + user + ")(userPassword=" + pw + "))" try: hits = search(flt, strict=strict) except ParseError as exc: return flt, None, f"ParseError: {exc}" return flt, hits, None def escape(value): """RFC 4515 section 3: the five bytes that must never be literal.""" out = [] for ch in value: if ch in "\\*()\0": out.append("\\%02x" % ord(ch)) else: out.append(ch) return "".join(out) print("== 1. the login filter, as the app builds it") flt, hits, err = login("admin", "Verano2026") print(f" filter = {flt}") print(f" result = {len(hits) if hits is not None else err} match(es) -> " f"{[h['uid'] for h in hits] if hits is not None else '-'}") flt, hits, err = login("admin", "nope") print(f" wrong password: filter = {flt} -> {len(hits) if hits is not None else err} match(es)") print() print("== 2. one character changes what the password field means") flt, hits, err = login("admin", "*") print(f" password '*' filter = {flt}") print(f" {'ParseError: ' + err if err else str(len(hits)) + ' match(es) -> ' + str([h['uid'] for h in hits])}") flt, hits, err = login("admin", "*") print(f" same payload with RFC 4515 escaping -> filter = (&(uid=admin)(userPassword={escape('*')}))") print(f" -> {len(search('(&(uid=admin)(userPassword=' + escape('*') + '))'))} match(es)") print() print("== 3. the classic close-and-reopen payload") payload = "*)(uid=*))(|(uid=*" flt, hits, err = login(payload, "x") print(f" input = {payload!r}") print(f" filter = {flt}") print(f" strict parser -> {err}") print(f" lenient parser (parses the first balanced filter, ignores the rest)") print(f" -> {len(search(flt, strict=False))} match(es): " f"{[h['uid'] for h in search(flt, strict=False)]}") print(f" escaped -> {len(search('(&(uid=' + escape(payload) + ')(userPassword=x))'))} match(es)") print(" The strict answer is what a real server does: it refuses the whole filter.") print(" The lenient answer is what a string-building helper does: it hands the") print(" server the first filter it can balance and silently drops the rest.") print() print("== 4. blind extraction with a prefix oracle, no wildcard in sight") SECRET = DIRECTORY[0]["userPassword"] CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" queries = 0 found = "" while len(found) < len(SECRET): for ch in CHARSET: queries += 1 flt = "(&(uid=admin)(userPassword=" + found + ch + "*))" if search(flt): found += ch break else: break print(f" target password length = {len(SECRET)}") print(f" recovered = {found!r} ({'correct' if found == SECRET else 'WRONG'})") print(f" queries = {queries}") print(f" one query per character position = {len(SECRET)}, brute force = " f"{len(CHARSET) ** len(SECRET):,} without the oracle") print(f" the same corpus with escaping: every query returns 0, so the oracle is dead") esc_queries = 0 for ch in CHARSET[:5]: esc_queries += 1 if search("(&(uid=admin)(userPassword=" + escape(found + ch) + "*))"): print(" LEAK") print(f" -> {esc_queries} escaped queries, 0 matches, prefix never confirmed") print() print("== 5. what it costs to read the whole directory") print(f" filter (&(uid=*)(userPassword=*)) -> {len(search('(&(uid=*)(userPassword=*))'))} of {len(DIRECTORY)} entries") print(f" filter (uid=*) -> {len(search('(uid=*)'))} of {len(DIRECTORY)} entries") print(f" filter (uid=tomas) -> {len(search('(uid=tomas)'))} of {len(DIRECTORY)} entries") print() print("== 6. the attribute name is a parameter too, and an allowlist stops it there") bad_attr = "uid)(userPassword=*" try: print(f" attr={bad_attr!r} -> filter ({bad_attr}=x) -> {len(search('(' + bad_attr + '=x)'))} entries") except ParseError as exc: print(f" attr={bad_attr!r} -> ParseError: {exc}") print(f" attr allowlist {list(ATTRS)}: the name slot is closed,") print(f" the value slot is still open unless it is escaped.") Sandbox check (local only, in-memory directory, no server, no network): == 1. the login filter, as the app builds it filter = (&(uid=admin)(userPassword=Verano2026)) result = 1 match(es) -> ['admin'] wrong password: filter = (&(uid=admin)(userPassword=nope)) -> 0 match(es) == 2. one character changes what the password field means password '*' filter = (&(uid=admin)(userPassword=*)) 1 match(es) -> ['admin'] same payload with RFC 4515 escaping -> filter = (&(uid=admin)(userPassword=\2a)) -> 0 match(es) == 3. the classic close-and-reopen payload input = '*)(uid=*))(|(uid=*' filter = (&(uid=*)(uid=*))(|(uid=*)(userPassword=x)) strict parser -> ParseError: trailing data at 17: '(|(uid=*)(userPassword=x))' lenient parser (parses the first balanced filter, ignores the rest) -> 5 match(es): ['admin', 'marta', 'diego', 'lucia', 'tomas'] escaped -> 0 match(es) The strict answer is what a real server does: it refuses the whole filter. The lenient answer is what a string-building helper does: it hands the server the first filter it can balance and silently drops the rest. == 4. blind extraction with a prefix oracle, no wildcard in sight target password length = 10 recovered = 'Verano2026' (correct) queries = 323 one query per character position = 10, brute force = 839,299,365,868,340,224 without the oracle the same corpus with escaping: every query returns 0, so the oracle is dead -> 5 escaped queries, 0 matches, prefix never confirmed == 5. what it costs to read the whole directory filter (&(uid=*)(userPassword=*)) -> 5 of 5 entries filter (uid=*) -> 5 of 5 entries filter (uid=tomas) -> 1 of 5 entries == 6. the attribute name is a parameter too, and an allowlist stops it there attr='uid)(userPassword=*' -> ParseError: unknown attribute 'uid)(userPassword' attr allowlist ['uid', 'cn', 'userPassword', 'role']: the name slot is closed, the value slot is still open unless it is escaped. What I understood: the module that escapes is worth more than the review comment that says "escape it". Every number here came from a directory of five entries that lives inside the file — no network, no target, nothing that does not exist in this repository. The lesson survives the toy: a filter is a program, a value is data, and the only way to keep the second from becoming the first is an escape table applied on the side of the boundary that owns the grammar. ---

Day 29 notes

Concept #29: two bounds, one scheduler, 120 priority orders per instance. Instance A:

bound 6, optimum 6, greedy 7 (+16.67%), 24 orders reach the optimum. Instance B: bounds promise 7, optimum is 8, greedy 10 (+25%), longest-chain-first 8. Both gaps inside the 2 − 1/m guarantee. ✔

Security #29: * in the password field is a wildcard, not a password; \2a kills it;

the classic close-and-reopen payload is a ParseError on a strict parser and a full directory dump on a lenient one; 323 requests recovered a 10-character password that brute force would need 8.39e17 for. Attribute names get an allowlist, values get an escape table. ✔

1571 days left. One at a time.

Written by my own daily machine, checked by me.

← Back to the index

· Day 029 of 1600 · Matías Rathgeb


[ inicio ]   [ proyectos ]   [ posts ]   [ daylog ]


Página estática. Sin cookies, sin javascript, sin fuentes externas.
Contacto: ver inicio.