File size: 13,424 Bytes
7bdf36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""Redaction for the Codex rollout cleaning pipeline.

Design
------
* All finders run on the ORIGINAL text and return spans (start, end, kind, replacement).
  Overlaps are resolved left-to-right (earliest start wins, then longest), so every
  replacement has exact offsets in the redacted text. That is what lets the pipeline
  log only replacements that survive tool-output truncation.
* Finders are linear-time: nothing starts with an unbounded character class followed by
  a distant anchor (e.g. e-mail search is anchored on '@', not on the local part).
* A second "verification" loop re-scans the redacted text with the *secret* finders and
  re-applies them if anything is left (belt and braces).
* Nothing here ever writes an original value anywhere; callers only receive sha256 digests.
"""
import hashlib
import re

SECRET = "<SECRET>"
EMAIL = "<EMAIL>"
IP = "<IP>"

# ----------------------------------------------------------------------------- secrets
_PEM_FULL = re.compile(
    r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----[\s\S]{0,20000}?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----"
)
# Unterminated block (output was cut or the END line was lost): redact BEGIN line + base64 body.
_PEM_OPEN = re.compile(
    r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:[A-Za-z0-9+/=\s]|\\n|\\r){0,8000}"
)
# Token patterns are applied exactly as written in the task spec (no left word-boundary), so a plain grep for the
# same regex over the output finds nothing. Matches that are glued to a preceding word character (for example the
# "sk-" inside a hyphenated file name such as "...task-board-...") are logged with kind suffix ":embedded_in_word"
# so the collateral can be audited from redactions.jsonl.
_AKIA = re.compile(r"AKIA[0-9A-Z]{16}")
_GH = re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}")        # ghp_ (+ gho_/ghu_/ghs_/ghr_)
_GH_PAT = re.compile(r"github_pat_[A-Za-z0-9_]{20,}")
_SK = re.compile(r"sk-[A-Za-z0-9_-]{20,}")
_BEARER = re.compile(
    r"(?i)\bAuthorization\s*[:=]\s*\\*[\"']?\s*Bearer\s+(?P<val>[A-Za-z0-9._~+/=-]{8,})"
)

# key = value secrets.  password|passwd|token|api_key|apikey|secret, optionally prefixed
# (access_token, client_secret, x-api-key, DB_PASSWORD ...) but NOT suffixed (token_count, secrets...)
_KV = re.compile(
    r"(?i)(?<![A-Za-z0-9])(?P<key>(?:[A-Za-z0-9]+[_.-])*(?:password|passwd|token|api[_-]?key|apikey|secret))"
    r"(?![A-Za-z0-9])\\*[\"']?[ \t]*(?::|=(?!=))[ \t]*\\*(?:"
    r"(?P<q>[\"'])(?P<qval>[^\"'\r\n\\]{3,200})\\*(?P=q)"
    r"|(?P<bval>[^\s\"'\\,;&(){}\[\]<>|`]{6,200}))"
)
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z_]*$")  # code identifier with no digits: not a literal secret
_HEX = re.compile(r"^0[xX][0-9A-Fa-f]+$")        # decompiler metadata tokens: "// Token: 0x06000001"
_DOTTED = re.compile(r"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+$")  # member access: this.token_value (JWTs are far longer)


def _kv_value_ok(val, quoted):
    if not val or val[0] in "$%<{(@#*":
        return False
    if val.lower() in ("null", "none", "true", "false", "undefined", "nullptr", "redacted"):
        return False
    if quoted:
        return True
    if _IDENT.match(val) or _HEX.match(val):
        return False
    if len(val) <= 64 and _DOTTED.match(val):
        return False
    return True


# ----------------------------------------------------------------------------- e-mail
_EMAIL_LOCAL = re.compile(r"[A-Za-z0-9._%+-]+$")
_EMAIL_DOMAIN = re.compile(r"[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.([A-Za-z]{2,})")
# TLD-looking file extensions: icon@2x.png, foo@bar.cpp ... are not mail addresses.
_FILE_EXT = frozenset(
    "png jpg jpeg gif svg webp bmp ico tga dds tif tiff psd bin dll exe lib obj asm so dylib pdb log xml yml yaml "
    "html htm css js ts json txt md c h cc cpp hpp cs py rs go java rb php sh bat ps1 cmd csv tsv bk2 bik bik2 "
    "mp4 mkv avi mov wav mp3 ogg zip rar 7z gz tar".split()
)


def _find_emails(text):
    out = []
    i = text.find("@")
    n = len(text)
    while i != -1:
        # local part: walk left (bounded)
        j = i
        lo = max(0, i - 64)
        while j > lo and text[j - 1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._%+-":
            j -= 1
        local = text[j:i]
        if local and any(ch.isalnum() for ch in local):
            m = _EMAIL_DOMAIN.match(text, i + 1)
            if m and m.group(1).lower() not in _FILE_EXT:
                out.append((j, m.end(), "email", EMAIL))
        i = text.find("@", i + 1)
    return out


# ----------------------------------------------------------------------------- windows user paths
_SYSTEM_PROFILES = frozenset(("public", "default", "default user", "all users", "user", "defaultuser0"))
_WIN_USER = re.compile(
    r"(?P<drive>[A-Za-z]:)(?P<s1>\\{1,8}|/{1,2})(?i:Users)(?P<s2>\\{1,8}|/{1,2})(?P<name>[^\\/\s\"'<>|:*?,;(){}\[\]`]+)"
)
_UNIX_USER = re.compile(
    r"(?<![A-Za-z0-9_.-])(?P<pre>/mnt/[a-z]|/[a-z])/(?i:Users)/(?P<name>[^\\/\s\"'<>|:*?,;(){}\[\]`]+)"
)


def _find_user_paths(text):
    out = []
    if "sers" not in text and "SERS" not in text:
        return out
    for m in _WIN_USER.finditer(text):
        name = m.group("name")
        if name.lower() in _SYSTEM_PROFILES:
            continue
        rep = f"{m.group('drive')}{m.group('s1')}Users{m.group('s2')}user"
        out.append((m.start(), m.end(), "win_user_path", rep))
    for m in _UNIX_USER.finditer(text):
        name = m.group("name")
        if name.lower() in _SYSTEM_PROFILES:
            continue
        out.append((m.start(), m.end(), "win_user_path_posix", f"{m.group('pre')}/Users/user"))
    return out


# ----------------------------------------------------------------------------- OneDrive organisation names
# Work/school OneDrive folders are named "OneDrive - <organisation>" and are followed by a path separator,
# e.g. "D:\OneDrive - Some School\Documents". The organisation identifies the account owner, so it is masked.
# The generic consumer folder "OneDrive - Personal" is not an organisation and is kept.
ORG = "<ORG>"
_ONEDRIVE_ORG = re.compile(r"(?<=OneDrive - )(?P<org>[^\\/\r\n\"<>|:*?]{1,80}?)(?=\\|/)")
_ONEDRIVE_KEEP = frozenset(("personal",))


def _find_onedrive_org(text):
    out = []
    if "OneDrive - " not in text:
        return out
    for m in _ONEDRIVE_ORG.finditer(text):
        if m.group("org").strip().lower() in _ONEDRIVE_KEEP:
            continue
        out.append((m.start("org"), m.end("org"), "onedrive_org", ORG))
    return out


# ----------------------------------------------------------------------------- IPv4
_OCT = r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)"
_IPV4 = re.compile(rf"(?<![\w.]){_OCT}(?:\.{_OCT}){{3}}(?!\d|\.\d)")


_VERSION_CTX = re.compile(r"(?i)version[\"']?\s*[=:]?\s*[\"']?$")


def _find_ips(text):
    out = []
    for m in _IPV4.finditer(text):
        v = m.group(0)
        if v == "0.0.0.0" or v.startswith("127."):
            continue
        if _VERSION_CTX.search(text[max(0, m.start() - 16):m.start()]):
            continue  # .NET "Version=4.0.0.0" style assembly versions are not addresses
        out.append((m.start(), m.end(), "ipv4", IP))
    return out


# ----------------------------------------------------------------------------- finders
def _emb(text, start):
    """':embedded_in_word' when the match is glued to a preceding word character."""
    return ":embedded_in_word" if start > 0 and (text[start - 1].isalnum() or text[start - 1] in "_-") else ""


def _find_secrets(text):
    out = []
    if "-----BEGIN" in text:
        for m in _PEM_FULL.finditer(text):
            out.append((m.start(), m.end(), "secret:pem_private_key", SECRET))
        for m in _PEM_OPEN.finditer(text):
            out.append((m.start(), m.end(), "secret:pem_private_key", SECRET))
    if "AKIA" in text:
        for m in _AKIA.finditer(text):
            out.append((m.start(), m.end(), "secret:aws_access_key" + _emb(text, m.start()), SECRET))
    if "gh" in text:
        for m in _GH.finditer(text):
            out.append((m.start(), m.end(), "secret:github_token" + _emb(text, m.start()), SECRET))
    if "github_pat_" in text:
        for m in _GH_PAT.finditer(text):
            out.append((m.start(), m.end(), "secret:github_pat" + _emb(text, m.start()), SECRET))
    if "sk-" in text:
        for m in _SK.finditer(text):
            out.append((m.start(), m.end(), "secret:sk_key" + _emb(text, m.start()), SECRET))
    if "earer" in text:
        for m in _BEARER.finditer(text):
            v = m.group("val")
            if v[0] in "$%<{":
                continue
            out.append((m.start("val"), m.end("val"), "secret:bearer_token", SECRET))
    low = text.lower()
    if ("password" in low) or ("passwd" in low) or ("token" in low) or ("secret" in low) or ("apikey" in low) or ("api_key" in low) or ("api-key" in low):
        for m in _KV.finditer(text):
            if m.group("q"):
                s, e, val, quoted = m.start("qval"), m.end("qval"), m.group("qval"), True
            else:
                s, e, val, quoted = m.start("bval"), m.end("bval"), m.group("bval"), False
            if not _kv_value_ok(val, quoted):
                continue
            kname = re.sub(r"[^a-z]", "", m.group("key").lower().split("_")[-1].split("-")[-1].split(".")[-1])
            out.append((s, e, "secret:kv:" + (kname or "key"), SECRET))
    return out


def _resolve(spans):
    """Earliest start wins; at equal start the longer span wins. Overlapping losers are dropped."""
    spans.sort(key=lambda s: (s[0], -(s[1] - s[0])))
    kept = []
    last_end = -1
    for s in spans:
        if s[0] >= last_end:
            kept.append(s)
            last_end = s[1]
    return kept


def _sha(s):
    return hashlib.sha256(s.encode("utf-8", "surrogatepass")).hexdigest()


def redact_text(text):
    """Redact `text`. Returns (new_text, events) where events is a list of
    (start, end, kind, sha256_of_original, replacement) with start/end in *new_text* coordinates."""
    if not text:
        return text, []
    spans = _find_secrets(text) + _find_emails(text) + _find_user_paths(text) + _find_onedrive_org(text) + _find_ips(text)
    if not spans:
        return text, []
    kept = _resolve(spans)
    pieces = []
    events = []
    pos = 0
    out_len = 0
    for s, e, kind, rep in kept:
        seg = text[pos:s]
        pieces.append(seg)
        out_len += len(seg)
        events.append((out_len, out_len + len(rep), kind, _sha(text[s:e]), rep))
        pieces.append(rep)
        out_len += len(rep)
        pos = e
    pieces.append(text[pos:])
    new = "".join(pieces)
    # Verification loop: a secret-class match must never survive.
    for _ in range(3):
        left = _find_secrets(new)
        if not left:
            break
        left = _resolve(left)
        pieces = []
        pos = 0
        shift_events = []
        for s, e, kind, rep in left:
            pieces.append(new[pos:s])
            pieces.append(rep)
            shift_events.append((s, e, kind, _sha(new[s:e]), rep))
            pos = e
        pieces.append(new[pos:])
        new = "".join(pieces)
        # offsets of earlier events can shift; recompute coarsely by dropping offsets (rare path)
        events = [(-1, -1, k, h, r) for (_, _, k, h, r) in events] + [(-1, -1, k, h, r) for (_, _, k, h, r) in shift_events]
    return new, events


def redact_json_leaves(obj, sink):
    """Redact every string leaf of a parsed JSON value. `sink` receives (kind, sha, replacement) tuples.
    Returns (new_obj, changed)."""
    if isinstance(obj, str):
        new, ev = redact_text(obj)
        for (_, _, k, h, r) in ev:
            sink.append((k, h, r))
        return new, bool(ev)
    if isinstance(obj, list):
        changed = False
        res = []
        for x in obj:
            y, c = redact_json_leaves(x, sink)
            res.append(y)
            changed = changed or c
        return res, changed
    if isinstance(obj, dict):
        changed = False
        res = {}
        for k, v in obj.items():
            y, c = redact_json_leaves(v, sink)
            res[k] = y
            changed = changed or c
        return res, changed
    return obj, False


# ----------------------------------------------------------------------------- validation regexes
# Plain (un-boundaried) secret regexes used by the *validation* step, deliberately broader than the
# redaction finders so that a miss caused by a boundary rule is still surfaced.
VALIDATION_REGEXES = {
    "AKIA": re.compile(r"AKIA[0-9A-Z]{16}"),
    "ghp_": re.compile(r"ghp_[A-Za-z0-9]{20,}"),
    "github_pat_": re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
    "sk-": re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
    "PEM PRIVATE KEY": re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY"),
    "Authorization: Bearer": re.compile(r"(?i)Authorization\s*[:=]\s*\\*[\"']?\s*Bearer\s+(?!<SECRET>)[A-Za-z0-9._~+/=-]{8,}"),
}

# ----------------------------------------------------------------------------- phone-like candidates
# Reported, never redacted.
PHONE_RE = re.compile(
    r"(?<![\w.:/\\-])(?:\+\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?|\d{2,4}[ .-])\d{3,4}[ .-]\d{3,4}(?:[ .-]\d{1,4})?(?![\w.:/\\-])"
)


def phone_candidates(text):
    res = []
    for m in PHONE_RE.finditer(text):
        v = m.group(0)
        digits = re.sub(r"\D", "", v)
        if 9 <= len(digits) <= 15 and re.search(r"[ ().+-]", v):
            res.append(v)
    return res