interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / om / sha256 / om2-evidence / audit / audit2.py

177 lines · 8714 bytes Raw Blame History
1#!/usr/bin/env python3
2# L838 audit part 2: overlap, use-after-final, whole-context copy/compare, field access.
3# Heuristic flags; every flag is reviewed by hand (audit.md records the verdicts).
4import re, json, sys, subprocess, collections
5sys.path.insert(0, '/tmp/zl/sha-audit')
6from audit import strip_comments, args_at, norm, base, ROOT # noqa: re-runs inventory (cheap)
7calls = [c for c in json.load(open('/tmp/zl/sha-audit/calls.json')) if not c['defn']]
8built = [c for c in calls if not c['file'].startswith('evidence/')]
9src = {}
10def text(f):
11 if f not in src:
12 src[f] = strip_comments(open(f'{ROOT}/{f}', encoding='utf-8', errors='replace').read())
13 return src[f]
14
15def ctxkey(a):
16 a = norm(a)
17 a = re.sub(r'^&\s*', '', a)
18 return re.sub(r'\s', '', a)
19
20print('== A. sha256_hash: digest base == data base, or digest derived from data')
21for c in built:
22 if c['fn'] != 'hash' or len(c['args']) != 3: continue
23 d, n, o = c['args']
24 bd, bo = base(d), base(o)
25 same = bd == bo or bd.split('->')[0].split('.')[0] == bo.split('->')[0].split('.')[0]
26 if same:
27 print(f" {c['file']}:{c['line']}: hash({norm(d)}, {norm(n)}, {norm(o)})")
28
29print('== B. sha256_final: digest arg mentions the ctx expression')
30for c in built:
31 if c['fn'] != 'final' or len(c['args']) != 2: continue
32 k, o = ctxkey(c['args'][0]), c['args'][1]
33 root = re.split(r'->|\.', k)[0]
34 if root and re.search(r'\b' + re.escape(root) + r'\b', o):
35 print(f" {c['file']}:{c['line']}: final({c['args'][0]}, {norm(o)})")
36
37print('== C. sha256_update: data arg mentions the ctx expression')
38for c in built:
39 if c['fn'] != 'update' or len(c['args']) != 3: continue
40 k, d = ctxkey(c['args'][0]), c['args'][1]
41 root = re.split(r'->|\.', k)[0]
42 if root and re.search(r'\b' + re.escape(root) + r'\b', d):
43 print(f" {c['file']}:{c['line']}: update({c['args'][0]}, {norm(d)}, ...)")
44
45# Function extents: top-level brace blocks.
46def functions(s):
47 out = []; depth = 0; start = None
48 for i, ch in enumerate(s):
49 if ch == '{':
50 if depth == 0: start = i
51 depth += 1
52 elif ch == '}':
53 depth -= 1
54 if depth == 0 and start is not None: out.append((start, i)); start = None
55 return out
56
57LOOP = re.compile(r'\b(for|while|do)\b')
58def loop_spans(s, a, b):
59 """spans (open, close) of loop bodies inside s[a:b] (braced bodies only, plus single-statement for/while)."""
60 spans = []
61 for m in LOOP.finditer(s, a, b):
62 i = m.end()
63 if m.group(1) != 'do':
64 while i < b and s[i].isspace(): i += 1
65 if i >= b or s[i] != '(': continue
66 _, i = args_at(s, i); i += 1
67 while i < b and s[i].isspace(): i += 1
68 if i < b and s[i] == '{':
69 d = 0
70 for j in range(i, b + 1):
71 if s[j] == '{': d += 1
72 elif s[j] == '}':
73 d -= 1
74 if d == 0: spans.append((i, j)); break
75 else:
76 j = s.find(';', i); spans.append((i, j))
77 return spans
78
79print('== D. lifecycle: update/final on a ctx after its final with no init between (textual), or final in a loop whose body has no init of that ctx')
80by_file = collections.defaultdict(list)
81for c in built: by_file[c['file']].append(c)
82ctx_param_final = []
83for f, cs in sorted(by_file.items()):
84 s = text(f)
85 for (a, b) in functions(s):
86 inside = [c for c in cs if a <= c['off'] <= b]
87 if not inside: continue
88 seq = collections.defaultdict(list)
89 for c in sorted(inside, key=lambda c: c['off']):
90 if c['fn'] == 'hash': continue
91 seq[ctxkey(c['args'][0])].append(c)
92 loops = loop_spans(s, a, b)
93 for k, ops in seq.items():
94 st = None
95 for c in ops:
96 if c['fn'] == 'init': st = 'live'
97 elif c['fn'] == 'final':
98 if st == 'done': print(f" {f}:{c['line']}: final({k}) again after final")
99 st = 'done'
100 elif c['fn'] == 'update' and st == 'done':
101 print(f" {f}:{c['line']}: update({k}) after final")
102 inits = [c for c in ops if c['fn'] == 'init']
103 finals = [c for c in ops if c['fn'] == 'final']
104 for fc in finals:
105 for (la, lb) in loops:
106 if la <= fc['off'] <= lb and not any(la <= ic['off'] <= lb for ic in inits):
107 print(f" {f}:{fc['line']}: final({k}) inside loop body at offset {la}..{lb} without init({k}) in that loop")
108 break
109 if finals and not inits:
110 ctx_param_final.append(f"{f}:{finals[0]['line']}: final({k}) with no init({k}) in the same function")
111print('== D2. finals in functions that do not init that ctx (wrappers; callers reviewed by hand)')
112for x in ctx_param_final: print(' ' + x)
113
114print('== E. sha256_ctx object names, struct members, copies/compares')
115files = [f for f in subprocess.run(['git', '-C', ROOT, 'ls-files', '--', '*.c', '*.h', '*.cc', '*.cpp', '*.inc'],
116 capture_output=True, text=True).stdout.split() if not f.startswith('evidence/')]
117decl = re.compile(r'\bsha256_ctx\s+(\*\s*)?([A-Za-z_]\w*)\s*(\[[^\]]*\])?\s*([=;,)\[])')
118names = collections.defaultdict(set); ptrs = collections.defaultdict(set)
119structs_with_ctx = []
120for f in files:
121 s = text(f)
122 if 'sha256_ctx' not in s: continue
123 for m in decl.finditer(s):
124 (ptrs if m.group(1) else names)[f].add(m.group(2))
125 line = s.count('\n', 0, m.start()) + 1
126 if not m.group(1) and m.group(4) == '=':
127 rest = s[m.end():s.find(';', m.end())]
128 print(f" copy-init? {f}:{line}: sha256_ctx {m.group(2)} = {rest.strip()[:80]}")
129 for m in re.finditer(r'\bsha256_ctx\s+[A-Za-z_]\w*\s*(\[[^\]]*\])?\s*;', s):
130 # member if inside a struct { } ... ; check nearest unmatched '{' is preceded by struct
131 i = m.start(); d = 0
132 while i > 0:
133 i -= 1
134 if s[i] == '}': d += 1
135 elif s[i] == '{':
136 if d == 0: break
137 d -= 1
138 head = s[max(0, i - 60):i]
139 if re.search(r'\b(struct|union)\b[^;{}]*$', head) or re.search(r'typedef\s+struct', head):
140 line = s.count('\n', 0, m.start()) + 1
141 structs_with_ctx.append(f"{f}:{line}: member {m.group(0).strip()}")
142print(' struct members of type sha256_ctx:')
143for x in structs_with_ctx: print(' ' + x)
144print(' ctx by-value names per file:', sum(len(v) for v in names.values()), ' pointer names:', sum(len(v) for v in ptrs.values()))
145for f in files:
146 s = text(f)
147 if 'sha256_ctx' not in s and not names.get(f): continue
148 nm = names.get(f, set()) | ptrs.get(f, set())
149 for m in re.finditer(r'\b(memcpy|memmove|memcmp|bcmp|memset|explicit_bzero)\s*\(', s):
150 args, _ = args_at(s, m.end() - 1)
151 joined = ' '.join(args)
152 if 'sha256_ctx' in joined or any(re.search(r'(&|\*)\s*' + re.escape(n) + r'\b(?!\s*(\.|->))', joined) or
153 re.search(r'sizeof\s*\(?\s*\*?' + re.escape(n) + r'\b\s*\)?(?!\s*(\.|->))', joined) for n in nm):
154 line = s.count('\n', 0, m.start()) + 1
155 print(f" {m.group(1)} {f}:{line}: {m.group(1)}({', '.join(norm(x) for x in args)})")
156 for n in nm:
157 for m in re.finditer(r'(\*\s*)?\b' + re.escape(n) + r'\s*=(?!=)', s):
158 line = s.count('\n', 0, m.start()) + 1
159 ctxline = s[s.rfind('\n', 0, m.start()) + 1:s.find('\n', m.start())]
160 if re.search(r'\bsha256_ctx\b', ctxline) and not m.group(1): continue # declaration handled above
161 if n in ptrs.get(f, set()) and not m.group(1): continue # pointer rebinding
162 print(f" assign {f}:{line}: {ctxline.strip()[:120]}")
163 for m in re.finditer(r'\b' + re.escape(n) + r'\s*(\.|->)\s*(state|count|buffer)\b', s):
164 line = s.count('\n', 0, m.start()) + 1
165 print(f" field {f}:{line}: {n}{m.group(1)}{m.group(2)}")
166print('== F. field access on any expression (.state/.count/.buffer near sha256_ctx use), by-value params/returns')
167for f in files:
168 s = text(f)
169 if 'sha256_ctx' not in s: continue
170 for m in re.finditer(r'\bsha256_ctx\s+[A-Za-z_]\w*\s*[,)]', s):
171 pre = s[max(0, m.start() - 200):m.start()]
172 if re.search(r'\(\s*[^;{}]*$', pre):
173 line = s.count('\n', 0, m.start()) + 1
174 print(f" by-value param {f}:{line}: {m.group(0)}")
175 for m in re.finditer(r'(^|\n)\s*(static\s+)?(inline\s+)?sha256_ctx\s+[A-Za-z_]\w*\s*\(', s):
176 line = s.count('\n', 0, m.start()) + 2
177 print(f" returns by value {f}:{line}")