-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava_capa.py
More file actions
201 lines (184 loc) · 13.7 KB
/
Copy pathjava_capa.py
File metadata and controls
201 lines (184 loc) · 13.7 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
#!/usr/bin/env python3
"""java_capa.py - lightweight capability tagger for Java malware (a "capa-lite").
capa itself does NOT support Java bytecode (it handles PE/ELF/.NET/shellcode and
sandbox traces, not .class/JAR). This fills that gap with a rule set of Java API
and string signatures, mapping each class to the capabilities it shows.
Works on either:
- a decompiled source tree (a directory of .java), or
- a .jar directly (scans printable strings in each .class constant pool).
ROBUSTNESS TO OBFUSCATION:
String encryption can hide string *literals* (e.g. "Login Data", "schtasks"),
but it CANNOT hide API/type references (java.awt.Robot, Cipher.getInstance,
com.sun.jna...) - those must stay linkable in the constant pool. Rules that key
on imported APIs (marked api) survive string obfuscation; rules that key on
literal strings (marked str) do not. Both are included and labelled in --evidence.
Usage:
py -3 java_capa.py <dir-or-jar> [--evidence] [--min N] [--imports]
It is a TRIAGE aid: heuristic, not proof. Confirm hits by reading the cited class.
"""
import os, re, sys, argparse, zipfile, string
# capability -> list of (kind, regex). kind: "api" survives string-obfuscation, "str" does not.
RULES = {
# --- Execution ---
"execution/command-shell": [("api", r"getRuntime\(\)\.exec"), ("api", r"ProcessBuilder"), ("str", r"cmd\.exe"), ("str", r"cmd /c"), ("str", r"/bin/sh"), ("str", r"powershell")],
"execution/scripting": [("str", r"cscript"), ("str", r"wscript"), ("str", r"mshta"), ("str", r"\.vbs\b"), ("str", r"rundll32")],
"execution/dynamic-class-load": [("api", r"URLClassLoader"), ("api", r"defineClass"), ("api", r"Class\.forName"), ("api", r"\.loadClass"), ("api", r"getDeclaredMethod"), ("api", r"Method\)?\.invoke"), ("api", r"java\.lang\.reflect")],
# --- Persistence ---
"persistence/scheduled-task": [("str", r"schtasks"), ("str", r"/sc minute"), ("str", r"/tn ")],
"persistence/registry-run": [("str", r"CurrentVersion\\+Run"), ("str", r"\breg add\b"), ("api", r"RegCreateKey"), ("api", r"Advapi32")],
"persistence/startup-folder": [("str", r"\\+Startup"), ("str", r"win32_startupcommand"), ("str", r"Common Startup")],
"persistence/service": [("str", r"\bsc create\b"), ("api", r"CreateService"), ("str", r"InstallService")],
"persistence/wmi-event": [("str", r"__EventFilter"), ("str", r"CommandLineEventConsumer"), ("str", r"ActiveScriptEventConsumer")],
# --- Privilege escalation / defense evasion ---
"privilege/uac-bypass": [("str", r"\brunas\b"), ("str", r"ShellExecute"), ("str", r"fodhelper"), ("str", r"eventvwr"), ("str", r"ms-settings")],
"evasion/disable-security": [("str", r"Set-MpPreference"), ("str", r"netsh advfirewall"), ("str", r"DisableAntiSpyware"), ("str", r"\btaskkill\b"), ("str", r"\bsc stop\b")],
"evasion/anti-vm-sandbox": [("str", r"VirtualBox"), ("str", r"vmware"), ("str", r"\bvbox\b"), ("str", r"Sandboxie"), ("str", r"\bqemu\b"), ("str", r"vmtoolsd")],
"evasion/self-delete": [("api", r"deleteOnExit"), ("str", r"cmd /c del"), ("str", r"choice /c y"), ("str", r"ping .* del ")],
"evasion/timing-sleep": [("api", r"Thread\.sleep"), ("api", r"TimeUnit\.\w+\.sleep")],
# --- Discovery ---
"discovery/system-info": [("str", r"\bwmic\b"), ("str", r"systeminfo"), ("api", r"os\.name"), ("str", r"COMPUTERNAME"), ("api", r"getHostName"), ("api", r"user\.name"), ("api", r"java\.version")],
"discovery/network-config": [("str", r"ipconfig"), ("api", r"NetworkInterface"), ("api", r"getInetAddresses"), ("str", r"\barp -a\b"), ("str", r"netstat")],
"discovery/process-list": [("str", r"tasklist"), ("api", r"ProcessHandle"), ("str", r"\bps -ef\b")],
"discovery/security-product": [("str", r"AntiVirusProduct"), ("str", r"SecurityCenter2"), ("str", r"Get-MpComputerStatus")],
# --- Collection ---
"collection/keylogging": [("api", r"GlobalKeyboardHook"), ("api", r"NativeKeyListener"), ("api", r"keyPressed"), ("api", r"keyReleased"), ("api", r"system\.keyboard"), ("api", r"SetWindowsHookEx"), ("str", r"Keyboard Log")],
"collection/screen-capture": [("api", r"java\.awt\.Robot"), ("api", r"createScreenCapture"), ("api", r"getScreenSize")],
"collection/webcam": [("str", r"\bwebcam\b"), ("api", r"com\.github\.sarxos"), ("api", r"DSVideoDevice"), ("str", r"VideoCapture")],
"collection/audio-mic": [("api", r"TargetDataLine"), ("api", r"AudioSystem"), ("api", r"javax\.sound\.sampled"), ("api", r"DataLine")],
"collection/clipboard": [("api", r"getSystemClipboard"), ("api", r"Toolkit.*getSystemClipboard"), ("api", r"DataFlavor"), ("api", r"\.getContents\(")],
# --- Credential access ---
"creds/browser-chromium": [("str", r"Login Data"), ("str", r"Local State"), ("str", r"os_crypt"), ("api", r"AES/GCM"), ("str", r"\bCookies\b"), ("str", r"Web Data"), ("str", r"encrypted_key")],
"creds/browser-gecko": [("str", r"logins\.json"), ("str", r"key4\.db"), ("str", r"key3\.db"), ("str", r"signons"), ("str", r"cert9\.db"), ("api", r"\bnss3\b")],
"creds/email-clients": [("str", r"Thunderbird"), ("str", r"Outlook"), ("str", r"FoxMail"), ("str", r"IMAP Password")],
"creds/crypto-wallets": [("str", r"wallet\.dat"), ("str", r"Electrum"), ("str", r"Exodus"), ("str", r"metamask"), ("str", r"keystore")],
"creds/apps-tokens": [("str", r"Discord"), ("str", r"FileZilla"), ("str", r"recentservers\.xml"), ("str", r"Pidgin"), ("str", r"\bToken\b")],
# --- C2 / exfil ---
"c2/raw-socket": [("api", r"java\.net\.Socket"), ("api", r"ServerSocket"), ("api", r"InetSocketAddress"), ("api", r"DataOutputStream"), ("api", r"DataInputStream"), ("api", r"\.connect\(")],
"c2/http": [("api", r"HttpURLConnection"), ("api", r"openConnection"), ("str", r"User-Agent"), ("api", r"setRequestMethod")],
"c2/external-ip-check": [("str", r"checkip"), ("str", r"ipify"), ("str", r"whatismyip"), ("str", r"amazonaws\.com/latest")],
"exfil/email-smtp": [("api", r"javax\.mail"), ("str", r"\bsmtp\b"), ("api", r"Transport\.send"), ("api", r"MimeMessage")],
"exfil/ftp": [("str", r"ftp://"), ("api", r"FTPClient"), ("api", r"commons\.net\.ftp")],
# --- Impact ---
"impact/account-manipulation": [("str", r"\bnet user\b"), ("str", r"\bnet localgroup\b"), ("str", r"\bnet1 user\b")],
"impact/ransom-encrypt": [("str", r"\bransom\b"), ("str", r"\.locked\b"), ("str", r"your files"), ("str", r"decrypt.*bitcoin")],
"impact/dos-flood": [("str", r"\bflood\b"), ("str", r"slowloris"), ("str", r"UDP flood")],
# --- Download / ingress ---
"download/ingress-tool": [("api", r"openStream"), ("api", r"HttpURLConnection"), ("str", r"repo1\.maven\.org"), ("str", r"https?://"), ("api", r"getResourceAsStream")],
# --- Native interop ---
"native/jna-winapi": [("api", r"com\.sun\.jna"), ("api", r"Native\.load"), ("api", r"user32"), ("api", r"kernel32"), ("api", r"advapi32"), ("api", r"gdi32"), ("api", r"\bPointer\b")],
# --- Crypto / encoding ---
"crypto/cipher": [("api", r"Cipher\.getInstance"), ("api", r"AES/"), ("api", r"PBKDF2"), ("api", r"SecretKeyFactory"), ("api", r"IvParameterSpec"), ("api", r"\bRC4\b"), ("api", r"Blowfish")],
"crypto/encoding": [("api", r"parseBase64Binary"), ("api", r"java\.util\.Base64"), ("api", r"DatatypeConverter"), ("api", r"GZIPInputStream"), ("api", r"Deflater")],
# --- File ops ---
"file-operations": [("api", r"FileOutputStream"), ("api", r"Files\.copy"), ("api", r"Files\.write"), ("api", r"RandomAccessFile")],
# --- STRRAT-class signatures (added from S1 class-map review) ---
"lateral/hidden-rdp": [("str", r"hrdpinst\.exe"), ("str", r"multrdp"), ("str", r"wshsoft\.company"), ("str", r"dontdisplaylastusername"), ("str", r"\b3389\b")],
"privilege/create-hidden-admin": [("str", r"net localgroup administrators"), ("str", r"administratoren"), ("str", r"administradores")],
"collection/hvnc-hidden-desktop": [("str", r"Strigoi Browser"), ("api", r"PrintWindow"), ("api", r"BitBlt"), ("api", r"keybd_event"), ("str", r"--window-position")],
"impact/ransomware": [("str", r"\.crimson"), ("str", r"rw-encrypt"), ("str", r"crimson_info")],
"c2/reverse-shell": [("api", r"redirectErrorStream"), ("str", r'powershell\.exe",\s*"-')],
"c2/reverse-proxy": [("str", r"RProx"), ("str", r"Connection Established"), ("str", r"Proxy-Connection")],
"collection/remote-desktop": [("api", r"\.mousePress\("), ("api", r"\.mouseMove\("), ("api", r"createScreenCapture")],
"creds/windows-vault": [("str", r"PasswordVault"), ("str", r"Windows\.Security\.Credentials")],
"evasion/registry-via-reflection":[("api", r"WindowsRegSetValueEx"), ("api", r"WindowsRegOpenKey"), ("api", r"WindowsRegDeleteKey")],
"discovery/geo-ip-lookup": [("str", r"ip-api\.com"), ("str", r"ipinfo\.io"), ("str", r"checkip")],
"evasion/anti-idle-mouse": [("api", r"MouseInfo"), ("api", r"getPointerInfo")],
"host/filelock-mutex": [("str", r"lock\.file"), ("api", r"FileChannel"), ("api", r"\.tryLock\(")],
"config/embedded-encrypted": [("str", r"resources/config\.txt"), ("str", r"config\.txt")],
"creds/browser-session-clone": [("str", r"-no-remote"), ("str", r"Firefox\.bat")],
}
# imports/refs worth surfacing per class (the survives-obfuscation signal)
INTERESTING_IMPORT = re.compile(
r"(java\.awt|java\.net|javax\.crypto|javax\.sound|java\.lang\.reflect|"
r"com\.sun\.jna|lc\.kra|org\.sqlite|sun\.|javax\.mail|java\.util\.zip|"
r"java\.security|java\.nio)", re.I)
def strings_from_class(data, minlen=4):
"""Extract printable ASCII runs from raw .class bytes (constant pool, etc.)."""
out, cur = [], []
printable = set(string.printable) - set("\t\n\r\x0b\x0c")
for b in data:
c = chr(b)
if c in printable:
cur.append(c)
else:
if len(cur) >= minlen:
out.append("".join(cur))
cur = []
if len(cur) >= minlen:
out.append("".join(cur))
return "\n".join(out)
def iter_units(path):
"""Yield (class_name, text) for each .java file or .class entry."""
if path.lower().endswith(".jar"):
z = zipfile.ZipFile(path)
for n in z.namelist():
if n.endswith(".class"):
yield n, strings_from_class(z.read(n))
else:
for root, _, files in os.walk(path):
for fn in files:
if fn.endswith(".java"):
p = os.path.join(root, fn)
with open(p, "r", encoding="utf-8", errors="replace") as f:
yield os.path.relpath(p, path), f.read()
def scan_text(text):
"""Return text plus a slash->dot normalized copy so .class refs (java/awt/Robot)
also match dotted API patterns, while raw forms (cmd /c) stay intact."""
return text + "\n" + text.replace("/", ".")
def imports_of(text):
found = set()
for m in re.finditer(r"(?:import\s+)?([a-z][a-z0-9_]*(?:[./][A-Za-z][A-Za-z0-9_]*){2,})", text):
ref = m.group(1).replace("/", ".")
if INTERESTING_IMPORT.search(ref):
# keep the package-ish prefix, trim trailing method bits
found.add(ref)
return sorted(found)[:12]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("path", help=".jar file or decompiled source directory")
ap.add_argument("--evidence", action="store_true", help="show a sample match + kind (api/str) per capability")
ap.add_argument("--min", type=int, default=1, help="only list classes with >= N capabilities")
ap.add_argument("--imports", action="store_true", help="also list each class's notable API imports (survives string-obfuscation)")
a = ap.parse_args()
compiled = {cap: [(kind, re.compile(p, re.I)) for kind, p in pats] for cap, pats in RULES.items()}
per_class, per_cap, imports = {}, {}, {}
total = 0
for name, text in iter_units(a.path):
total += 1
norm = text.replace("/", ".") # slash->dot copy is char-aligned with text (same offsets/lines)
hits = {}
for cap, regs in compiled.items():
for kind, rg in regs:
m = rg.search(text) or rg.search(norm)
if m:
line = text.count("\n", 0, m.start()) + 1 # .java: source line; .jar: index in the string dump
hits[cap] = (kind, m.group(0), line)
per_cap.setdefault(cap, set()).add(name)
break
if hits:
per_class[name] = hits
if a.imports:
imports[name] = imports_of(text)
print(f"== SUMMARY == classes scanned: {total} | with >=1 capability: {len(per_class)} | capabilities seen: {len(per_cap)}")
print("\n== CLASS -> CAPABILITIES ==")
for name in sorted(per_class, key=lambda k: (-len(per_class[k]), k)):
caps = per_class[name]
if len(caps) < a.min:
continue
print(f"\n{name} [{len(caps)} cap]")
for cap in sorted(caps):
kind, ev, ln = caps[cap]
out = f" - {cap}"
if a.evidence:
out += f" [{kind}] {name}:{ln} ({ev!r})"
print(out)
if a.imports and imports.get(name):
print(f" imports: {', '.join(imports[name])}")
print("\n== CAPABILITY -> CLASSES ==")
for cap in sorted(per_cap):
cls = sorted(per_cap[cap])
print(f"\n{cap} ({len(cls)})")
for c in cls:
print(f" {c}")
if __name__ == "__main__":
main()