Repository navigation
Expand file tree
/
Copy pathexploitfixr.sh
More file actions
executable file
·448 lines (406 loc) · 16.8 KB
/
Copy pathexploitfixr.sh
File metadata and controls
executable file
·448 lines (406 loc) · 16.8 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#!/usr/bin/env bash
#==============================================================================
# exploitfixr.sh — classify and patch broken public exploits
#==============================================================================
# PURPOSE
# Operator has a public exploit (searchsploit -m, GitHub PoC, writeup
# paste) that doesn't run / doesn't compile / doesn't connect / runs but
# does nothing. exploitfixr reads the exploit + the error + (optionally)
# the bound target's state vector, classifies the failure against
# lib/failure_map.yaml, and prints the modified code or command ready to
# paste. Never executes, never installs, never opens sockets.
#
# WORKFLOW
# 1. Parse CLI (--error, --error-file, --against, --no-target, --stdin)
# 2. Bind target via lib/state.sh inference (matching stuckr.sh)
# 3. Hand exploit text + error + state to lib/exploitfixr_classify.py
# 4. Render per spec §6 (fix), §6 classify-only, or §7 fallback
# 5. Write the fixed copy to /tmp/exploitfixr/<basename>.fixed.<ext>
#
# USAGE
# exploitfixr <file> classify file, no error context
# exploitfixr <file> --error "<msg>" file + error string
# exploitfixr <file> --error-file <path> error from a file
# exploitfixr <file> --against <ip> bind to target state
# exploitfixr <file> --no-target opt out of state binding
# exploitfixr --stdin classify pasted error only
# exploitfixr --no-color disable ANSI (also: NO_COLOR=1)
#
# DESIGN
# - Sibling to stuckr.sh: same lib/state.sh consumer, same banner style,
# same fail-loud fallback discipline.
# - All regex / catalog logic lives in lib/exploitfixr_classify.py;
# bash is too thin for the engine work (spec §10).
# - Original exploit file is NEVER modified. Fixed copy lands in
# /tmp/exploitfixr/ (deterministic, disposable, clears on reboot).
# - 10.10.14.x is NEVER substituted — Kali VPN side per spec §9 and
# lib/substitutions.md.
#==============================================================================
set -o pipefail
# NOT set -e — surface errors with clear messages, don't abort silently.
#------------------------------------------------------------------------------
# CONFIGURATION
#------------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_STATE="${SCRIPT_DIR}/lib/state.sh"
LIB_CLASSIFY="${SCRIPT_DIR}/lib/exploitfixr_classify.py"
FAILURE_MAP="${SCRIPT_DIR}/lib/failure_map.yaml"
SUBSTITUTIONS="${SCRIPT_DIR}/lib/substitutions.md"
EXPLOITDB_SEED_DIR="${SCRIPT_DIR}/exploitdb/data/seed"
FIXED_DIR="/tmp/exploitfixr"
#------------------------------------------------------------------------------
# COLORS & OUTPUT HELPERS
#------------------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
disable_colors() { RED='' GREEN='' YELLOW='' BLUE='' CYAN='' MAGENTA='' BOLD='' DIM='' NC=''; }
{ [[ -n "${NO_COLOR:-}" ]] || [[ ! -t 1 ]]; } && disable_colors
ts() { date '+%H:%M:%S'; }
info() { echo -e "${BLUE}[$(ts)] [*]${NC} $*"; }
warn() { echo -e "${YELLOW}[$(ts)] [!]${NC} $*"; }
error() { echo -e "${RED}[$(ts)] [-]${NC} $*" >&2; }
bar() { printf '═%.0s' {1..63}; printf '\n'; }
hr() { printf '─%.0s' {1..63}; printf '\n'; }
#------------------------------------------------------------------------------
# CLI PARSING
#------------------------------------------------------------------------------
EXPLOIT_FILE=""
ERROR_STRING=""
ERROR_FILE=""
TARGET_IP=""
NO_TARGET=false
STDIN_MODE=false
usage() {
cat <<EOF
exploitfixr.sh — classify and patch broken public exploits
Usage:
exploitfixr <file> classify file, no error context
exploitfixr <file> --error "<msg>" file + error string
exploitfixr <file> --error-file <path> error from a file (long tracebacks)
exploitfixr <file> --against <ip> bind to target state vector
exploitfixr <file> --no-target opt out of state binding
exploitfixr --stdin classify pasted error only (no file)
exploitfixr --no-color disable ANSI (also: NO_COLOR=1)
exploitfixr -h | --help this help
Target binding (default ON, matches stuckr.sh): --against wins, else cwd
under \$TOOLKIT_ROOT/targets/<ip>/, else evidencr last_target.
Never executes, never installs, never opens sockets, never mutates state.
Fixed copy goes to ${FIXED_DIR}/. Original file is never touched.
EOF
}
while [[ $# -gt 0 ]]; do
case "$1" in
--error) ERROR_STRING="$2"; shift 2 ;;
--error-file) ERROR_FILE="$2"; shift 2 ;;
--against) TARGET_IP="$2"; shift 2 ;;
--no-target) NO_TARGET=true; shift ;;
--stdin) STDIN_MODE=true; shift ;;
--no-color) disable_colors; shift ;;
-h|--help) usage; exit 0 ;;
--) shift; break ;;
-*) error "unknown option: $1"; usage >&2; exit 2 ;;
*)
if [[ -z "$EXPLOIT_FILE" ]]; then
EXPLOIT_FILE="$1"
else
error "unexpected positional argument: $1"; usage >&2; exit 2
fi
shift ;;
esac
done
#------------------------------------------------------------------------------
# PRECHECKS
#------------------------------------------------------------------------------
for f in "$LIB_STATE" "$LIB_CLASSIFY" "$FAILURE_MAP"; do
if [[ ! -r "$f" ]]; then error "missing: $f"; exit 1; fi
done
if ! command -v python3 >/dev/null 2>&1; then
error "python3 required (catalog parsing + regex engine)"; exit 1
fi
if ! python3 -c "import yaml" 2>/dev/null; then
error "python3 PyYAML required (apt install -y python3-yaml)"; exit 1
fi
if $STDIN_MODE; then
if [[ -n "$EXPLOIT_FILE" ]]; then
error "--stdin is classify-only — do not pass an exploit file"
exit 2
fi
if [[ -n "$ERROR_STRING" || -n "$ERROR_FILE" ]]; then
error "--stdin reads error from stdin; do not also pass --error/--error-file"
exit 2
fi
else
if [[ -z "$EXPLOIT_FILE" ]]; then
error "missing exploit file (or use --stdin for classify-only)"
usage >&2; exit 2
fi
if [[ ! -r "$EXPLOIT_FILE" ]]; then
error "cannot read exploit file: $EXPLOIT_FILE"; exit 1
fi
fi
# shellcheck disable=SC1090
source "$LIB_STATE"
#------------------------------------------------------------------------------
# TARGET INFERENCE (mirrors stuckr.sh)
#------------------------------------------------------------------------------
infer_target() {
local pwd_abs root_abs
pwd_abs=$(realpath "$PWD" 2>/dev/null || echo "$PWD")
root_abs=$(realpath "$TOOLKIT_ROOT" 2>/dev/null || echo "$TOOLKIT_ROOT")
if [[ "$pwd_abs" == "$root_abs/targets/"* ]]; then
local rest="${pwd_abs#"$root_abs"/targets/}"
echo "${rest%%/*}"
return 0
fi
local lt="$TOOLKIT_ROOT/.evidencr/last_target"
if [[ -r "$lt" ]]; then
local v; v=$(head -1 "$lt" | tr -d '[:space:]')
[[ -n "$v" ]] && { echo "$v"; return 0; }
fi
return 1
}
INFER_HOW=""
if $NO_TARGET; then
TARGET_IP=""
INFER_HOW="opt-out (--no-target)"
elif [[ -n "$TARGET_IP" ]]; then
INFER_HOW="--against"
elif ! $STDIN_MODE; then
if TARGET_IP=$(infer_target); then
INFER_HOW="inferred (cwd or evidencr last_target)"
else
INFER_HOW="no target bound"
fi
fi
#------------------------------------------------------------------------------
# BUILD ERROR-FILE INPUT
#------------------------------------------------------------------------------
TMP_ERR=""
if $STDIN_MODE; then
TMP_ERR=$(mktemp -t exploitfixr.err.XXXXXX)
cat > "$TMP_ERR"
ACTIVE_ERR_FILE="$TMP_ERR"
ACTIVE_EXPLOIT="-"
elif [[ -n "$ERROR_FILE" ]]; then
[[ -r "$ERROR_FILE" ]] || { error "cannot read --error-file: $ERROR_FILE"; exit 1; }
ACTIVE_ERR_FILE="$ERROR_FILE"
ACTIVE_EXPLOIT="$EXPLOIT_FILE"
elif [[ -n "$ERROR_STRING" ]]; then
TMP_ERR=$(mktemp -t exploitfixr.err.XXXXXX)
printf '%s' "$ERROR_STRING" > "$TMP_ERR"
ACTIVE_ERR_FILE="$TMP_ERR"
ACTIVE_EXPLOIT="$EXPLOIT_FILE"
else
ACTIVE_ERR_FILE=""
ACTIVE_EXPLOIT="$EXPLOIT_FILE"
fi
trap '[[ -n "$TMP_ERR" ]] && rm -f "$TMP_ERR"' EXIT
#------------------------------------------------------------------------------
# STATE PIPING
#------------------------------------------------------------------------------
build_state_stream() {
if [[ -z "$TARGET_IP" ]]; then return 0; fi
state_read_target "$TARGET_IP"
state_read_global
}
#------------------------------------------------------------------------------
# RUN CLASSIFIER
#------------------------------------------------------------------------------
CLASSIFY_ERR=$(mktemp -t exploitfixr.cerr.XXXXXX)
trap '[[ -n "$TMP_ERR" ]] && rm -f "$TMP_ERR"; rm -f "$CLASSIFY_ERR"' EXIT
JSON=$(build_state_stream | python3 "$LIB_CLASSIFY" \
"$FAILURE_MAP" "$ACTIVE_EXPLOIT" "$ACTIVE_ERR_FILE" \
"$SUBSTITUTIONS" "$EXPLOITDB_SEED_DIR" 2>"$CLASSIFY_ERR")
RC=$?
if [[ $RC -ne 0 || -z "$JSON" ]]; then
error "classifier failed (rc=$RC)"
[[ -s "$CLASSIFY_ERR" ]] && cat "$CLASSIFY_ERR" >&2
exit 1
fi
#------------------------------------------------------------------------------
# RENDER (§6 / §6 classify-only / §7 fallback)
#
# All JSON parsing is done in a single python3 -c invocation so the renderer
# stays declarative and we don't ship a jq dependency (per AGENTS.md §7).
#------------------------------------------------------------------------------
mkdir -p "$FIXED_DIR" 2>/dev/null || { error "cannot create $FIXED_DIR"; exit 1; }
# Pass JSON + env to a python renderer that emits ready-to-display text.
RENDER_OUT=$(
JSON_PAYLOAD="$JSON" \
EXPLOIT_FILE="$EXPLOIT_FILE" \
TARGET_IP="$TARGET_IP" \
INFER_HOW="$INFER_HOW" \
FIXED_DIR="$FIXED_DIR" \
STDIN_MODE="$STDIN_MODE" \
BOLD="$BOLD" DIM="$DIM" RED="$RED" GREEN="$GREEN" YELLOW="$YELLOW" \
CYAN="$CYAN" MAGENTA="$MAGENTA" NC="$NC" \
python3 - <<'PYRENDER'
import json, os, sys, re
j = json.loads(os.environ['JSON_PAYLOAD'])
EF = os.environ['EXPLOIT_FILE']
TIP = os.environ['TARGET_IP']
HOW = os.environ['INFER_HOW']
FIXED = os.environ['FIXED_DIR']
STDIN = os.environ['STDIN_MODE'] == 'true'
C = {k: os.environ.get(k, '') for k in
('BOLD','DIM','RED','GREEN','YELLOW','CYAN','MAGENTA','NC')}
def bar(): print('═' * 63)
def hr(): print('─' * 63)
def col(c, s): return f"{C[c]}{s}{C['NC']}"
basename = j.get('exploit_basename') or '<stdin>'
os_guess = j.get('os_guess') or 'unknown'
# ── BANNER ───────────────────────────────────────────────────────────────────
bar()
target_line = f"target {TIP} ({os_guess})" if TIP else "no target bound"
title = f" exploitfixr • {basename} • {target_line}"
print(title)
if HOW and TIP:
print(col('DIM', f" binding: {HOW}"))
bar()
print()
mode = j['mode']
# ── §7 FALLBACK ──────────────────────────────────────────────────────────────
if mode == 'fallback':
print(col('RED', 'NO CONFIDENT FIX.'))
print()
cls = j.get('classification') or '(no taxonomy hit at all)'
print(f"Best-effort classification: {cls}")
print(f"Signals: (none — no file/error/state pattern fired)")
print()
cps = j.get('corpus_pointers') or []
if cps:
print('Relevant corpus entries (best service match):')
for slug, rel, cat in cps:
print(f" • {col('CYAN', slug):42s} engagement_relevance: {rel} [{cat}]")
print()
print('Manual research:')
print(f" Suggested search: \"{j['search_string']}\"")
print(f" Suggested vault: Exploit_Research.md, Fixing_Exploits.md")
print()
bar()
sys.exit(0)
# ── §6 CLASSIFY-ONLY (--stdin OR all matches dump-only OR unfixable) ─────────
if mode == 'classify-only':
matches = j.get('matches', [])
keys = ' + '.join(m['key'] for m in matches[:3])
tiers = '/'.join(set(m['confidence'] for m in matches[:3])) + \
'/' + '/'.join(set(m['impact'] for m in matches[:3]))
label = 'CLASSIFIED (NO FIX — CLASSIFY ONLY):' if not STDIN \
else 'CLASSIFIED FROM STDIN:'
print(col('YELLOW', label), col('BOLD', keys))
print(f" ({len(matches)} matches, {tiers})")
print()
print(col('BOLD', 'WHY:'))
for m in matches[:3]:
sigs = '; '.join(m['signals']) or '(state-pred only)'
print(f" [{col('CYAN', m['key'])}] {sigs}")
print(f" {C['DIM']}{m['explanation'].splitlines()[0]}{C['NC']}")
print()
# Show paste commands captured from the matches (e.g. pipx install impacket)
paste_lines = [m for m in matches[:3] if m.get('paste_command')]
if paste_lines:
print(col('BOLD', 'PASTE COMMANDS:'))
for m in paste_lines:
print(f" # {m['key']}")
print(f" {m['paste_command']}")
print()
cps = j.get('corpus_pointers') or []
if cps:
print(col('BOLD', 'Relevant corpus entries (find a working exploit):'))
for slug, rel, cat in cps:
print(f" • {col('CYAN', slug):42s} engagement_relevance: {rel} [{cat}]")
print()
# Refs from matched entries
refs = []
for m in matches[:3]:
for r in m.get('references') or []:
if isinstance(r, dict):
for k, v in r.items():
refs.append(f"{k}: {v}")
if refs:
print(col('BOLD', 'References:'))
for r in refs[:6]:
print(f" • {r}")
print()
bar()
sys.exit(0)
# ── §6 FIX MODE ──────────────────────────────────────────────────────────────
applied = j.get('applied', [])
alternates = j.get('alternates', [])
fixed_text = j.get('fixed_file_text', '')
unchanged = j.get('unchanged', True)
keys = ' + '.join(m['key'] for m in applied)
conf_tiers = ', '.join(set(m['confidence'] for m in applied))
imp_tiers = ', '.join(set(m['impact'] for m in applied))
loc_tiers = ', '.join(set(m['fix_locality'] for m in applied))
print(col('GREEN', 'CLASSIFIED:'), col('BOLD', keys))
print(f" ({len(applied)} {'fixes' if len(applied)!=1 else 'fix'}, "
f"{conf_tiers}/{imp_tiers}/{loc_tiers})")
print()
print(col('BOLD', 'WHY:'))
for m in applied:
sigs = '; '.join(m['signals']) or '(state-pred only)'
print(f" [{col('CYAN', m['key'])}] {sigs}")
print(f" {C['DIM']}{m['explanation'].splitlines()[0]}{C['NC']}")
print()
# Decide presentation: FIXED FILE vs FIXED COMMAND vs NO-OP
command_only_matches = [m for m in applied if m['fix_kind'] == 'command-only']
file_mutating = [m for m in applied if m['fix_kind'] not in ('command-only', 'dump-only')]
if file_mutating and not unchanged:
print(col('BOLD', 'FIXED FILE — copy and run:'))
hr()
sys.stdout.write(fixed_text)
if not fixed_text.endswith('\n'):
print()
hr()
# Write disposable copy
if EF:
base = os.path.basename(EF)
if '.' in base:
stem, ext = base.rsplit('.', 1)
out_name = f"{stem}.fixed.{ext}"
else:
out_name = f"{base}.fixed"
out_path = os.path.join(FIXED, out_name)
try:
with open(out_path, 'w') as f:
f.write(fixed_text)
print()
print(f"Also written to: {col('CYAN', out_path)}")
print(f"Original preserved: {EF} (untouched)")
ext = os.path.splitext(out_path)[1].lstrip('.')
runners = {'py': 'python3', 'sh': 'bash', 'rb': 'ruby', 'pl': 'perl'}
runner = runners.get(ext, '')
if runner:
print()
print(f"{col('BOLD','NEXT:')} {runner} {out_path}")
except OSError as e:
print(f"{C['YELLOW']}(could not write fixed copy: {e}){C['NC']}")
if command_only_matches:
print()
print(col('BOLD', 'FIXED COMMAND — copy and run:'))
hr()
for m in command_only_matches:
print(f" # for fix: {m['key']}")
print(f" {m['paste_command']}")
hr()
if not file_mutating and not command_only_matches:
print(col('YELLOW', '(no automated fix applied — see classification above)'))
if alternates:
print()
print(col('DIM', "if this doesn't resolve it, try also:"))
for m in alternates:
print(f" • {col('CYAN', m['key']):40s} "
f"({m['confidence']}/{m['impact']}/{m['fix_locality']})")
print()
bar()
PYRENDER
)
printf '%s\n' "$RENDER_OUT"