Repository navigation
Expand file tree
/
Copy pathfinalshell_decoder.py
More file actions
367 lines (303 loc) · 13.2 KB
/
Copy pathfinalshell_decoder.py
File metadata and controls
367 lines (303 loc) · 13.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FinalShell 连接凭据查看工具
- Tab1: 单条解密
- Tab2: 批量解密(自动查找 / 手动选目录,列表展示,一键复制,导出 CSV)
"""
import os, sys, json, glob, base64, hashlib, struct, csv, subprocess
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
# ── 依赖检查 ────────────────────────────────────────────────────────
try:
from Crypto.Cipher import DES
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "pycryptodome", "-q"])
from Crypto.Cipher import DES
# ── 解密算法 ────────────────────────────────────────────────────────
class JavaRandom:
def __init__(self, seed):
self.seed = (seed ^ 0x5DEECE66D) & ((1 << 48) - 1)
def next(self, bits):
self.seed = (self.seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1)
val = self.seed >> (48 - bits)
if bits == 32 and val >= (1 << 31):
val -= (1 << 32)
return val
def nextInt(self, n):
if (n & -n) == n:
return (n * self.next(31)) >> 31
while True:
bits = self.next(31)
val = bits % n
if bits - val + (n - 1) >= 0:
return val
def nextLong(self):
result = ((self.next(32) << 32) + self.next(32)) & 0xFFFFFFFFFFFFFFFF
if result >= 0x8000000000000000:
result -= 0x10000000000000000
return result
def _ranDomKey(head):
def jb(b): return b if b < 128 else b - 256
ks = 3680984568597093857 // JavaRandom(jb(head[5])).nextInt(127)
r = JavaRandom(ks)
for _ in range(max(0, jb(head[0]))):
r.nextLong()
n = r.nextLong()
r2 = JavaRandom(n)
ld = [jb(head[4]), r2.nextLong(), jb(head[7]), jb(head[3]),
r2.nextLong(), jb(head[1]), r.nextLong(), jb(head[2])]
return hashlib.md5(b''.join(struct.pack('>q', v) for v in ld)).digest()
def _decode_v3(data: str) -> str:
"""FinalShell 3.x:JavaRandom 推导 key"""
buf = base64.b64decode(data)
key = _ranDomKey(list(buf[:8]))
dec = DES.new(key[:8], DES.MODE_ECB).decrypt(buf[8:])
pad = dec[-1]
if 0 < pad <= 8:
dec = dec[:-pad]
return dec.decode("utf-8")
def _decode_v2(data: str) -> str:
"""FinalShell 老版本:固定 key DES/ECB"""
key = hashlib.md5(b"finashell").digest()[:8]
buf = base64.b64decode(data)
dec = DES.new(key, DES.MODE_ECB).decrypt(buf)
pad = dec[-1]
if 0 < pad <= 8:
dec = dec[:-pad]
return dec.decode("utf-8")
def decrypt_auto(data: str) -> tuple[str, str]:
"""
自动尝试多种算法,返回 (明文密码, 使用的算法描述)
"""
data = data.strip()
if not data:
return "", ""
for fn, label in [(_decode_v3, "3.x"), (_decode_v2, "2.x/旧版")]:
try:
result = fn(data)
if result.isprintable():
return result, label
except Exception:
pass
return "[解密失败:未知格式或版本不支持]", "?"
# ── conn 目录扫描 ────────────────────────────────────────────────────
def find_conn_dir() -> str:
candidates = [
os.path.expandvars(r"%LOCALAPPDATA%\finalshell\conn"),
os.path.expandvars(r"%APPDATA%\finalshell\conn"),
r"C:\Users\gang\AppData\Local\finalshell\conn",
]
for p in candidates:
if os.path.isdir(p):
return p
return ""
def scan_conn_dir(conn_dir: str) -> list[dict]:
files = list(set(
glob.glob(os.path.join(conn_dir, "**", "*.json"), recursive=True) +
glob.glob(os.path.join(conn_dir, "*.json"))
))
results = []
seen = set()
for fpath in sorted(files):
try:
with open(fpath, encoding="utf-8", errors="replace") as f:
data = json.load(f)
except Exception:
continue
if data.get("folder"):
continue
host = data.get("host") or data.get("address") or ""
if not host:
continue
name = data.get("name") or os.path.basename(fpath)
port = str(data.get("port") or 22)
username = data.get("user_name") or data.get("username") or ""
enc_pass = (data.get("password") or data.get("sftpPassword")
or data.get("sftp_password") or "")
if enc_pass:
password, ver = decrypt_auto(enc_pass)
else:
password, ver = "(密钥认证)", "-"
key = (host, port, username)
if key in seen:
continue
seen.add(key)
results.append({
"name": name, "host": host, "port": port,
"username": username, "password": password, "ver": ver
})
return results
# ── GUI ─────────────────────────────────────────────────────────────
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("FinalShell 凭据查看工具")
self.geometry("900x600")
self.resizable(True, True)
self._build_ui()
def _build_ui(self):
nb = ttk.Notebook(self)
nb.pack(fill="both", expand=True, padx=8, pady=8)
self._tab_single(nb)
self._tab_batch(nb)
# ── Tab1: 单条解密 ──────────────────────────────────────────────
def _tab_single(self, nb):
frame = ttk.Frame(nb, padding=16)
nb.add(frame, text=" 单条解密 ")
ttk.Label(frame, text="加密字符串(Base64):").grid(
row=0, column=0, sticky="w", pady=(0, 4))
self._single_input = tk.StringVar()
entry = ttk.Entry(frame, textvariable=self._single_input, width=60)
entry.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(0, 8))
entry.bind("<Return>", lambda _: self._do_single())
ttk.Button(frame, text="解密", command=self._do_single).grid(
row=2, column=0, sticky="w")
ttk.Label(frame, text="解密结果:").grid(
row=3, column=0, sticky="w", pady=(16, 4))
result_frame = ttk.Frame(frame)
result_frame.grid(row=4, column=0, columnspan=2, sticky="ew")
self._single_result = tk.StringVar()
result_entry = ttk.Entry(result_frame, textvariable=self._single_result,
width=50, state="readonly")
result_entry.pack(side="left", padx=(0, 8))
ttk.Button(result_frame, text="复制",
command=lambda: self._copy_text(self._single_result.get())
).pack(side="left")
self._single_ver = tk.StringVar()
ttk.Label(frame, textvariable=self._single_ver,
foreground="#888").grid(row=5, column=0, sticky="w", pady=(6, 0))
frame.columnconfigure(0, weight=1)
def _do_single(self):
raw = self._single_input.get().strip()
if not raw:
return
pwd, ver = decrypt_auto(raw)
self._single_result.set(pwd)
self._single_ver.set(f"算法版本:FinalShell {ver}" if ver and ver != "?" else "")
# ── Tab2: 批量解密 ──────────────────────────────────────────────
def _tab_batch(self, nb):
frame = ttk.Frame(nb, padding=(16, 12))
nb.add(frame, text=" 批量解密 ")
# 顶部工具栏
toolbar = ttk.Frame(frame)
toolbar.pack(fill="x", pady=(0, 8))
self._dir_var = tk.StringVar(value=find_conn_dir())
dir_entry = ttk.Entry(toolbar, textvariable=self._dir_var, width=55)
dir_entry.pack(side="left", padx=(0, 6))
ttk.Button(toolbar, text="选择目录",
command=self._browse_dir).pack(side="left", padx=(0, 6))
ttk.Button(toolbar, text="▶ 开始解密",
command=self._do_batch).pack(side="left", padx=(0, 6))
ttk.Button(toolbar, text="导出 CSV",
command=self._export_csv).pack(side="left", padx=(0, 6))
self._status_var = tk.StringVar()
ttk.Label(toolbar, textvariable=self._status_var,
foreground="#555").pack(side="left", padx=(12, 0))
# 列表
cols = ("name", "host", "port", "username", "password", "ver")
col_labels = {
"name": "名称", "host": "主机", "port": "端口",
"username": "用户名", "password": "密码", "ver": "版本"
}
col_widths = {
"name": 160, "host": 130, "port": 55,
"username": 110, "password": 180, "ver": 55
}
tree_frame = ttk.Frame(frame)
tree_frame.pack(fill="both", expand=True)
self._tree = ttk.Treeview(tree_frame, columns=cols,
show="headings", selectmode="browse")
for c in cols:
self._tree.heading(c, text=col_labels[c],
command=lambda _c=c: self._sort_by(_c, False))
self._tree.column(c, width=col_widths[c], minwidth=40)
vsb = ttk.Scrollbar(tree_frame, orient="vertical",
command=self._tree.yview)
hsb = ttk.Scrollbar(tree_frame, orient="horizontal",
command=self._tree.xview)
self._tree.configure(yscrollcommand=vsb.set,
xscrollcommand=hsb.set)
self._tree.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
tree_frame.rowconfigure(0, weight=1)
tree_frame.columnconfigure(0, weight=1)
# 点击密码列复制
self._tree.bind("<ButtonRelease-1>", self._on_tree_click)
# 底部提示
ttk.Label(frame,
text="提示:点击「密码」列单元格可直接复制该密码到剪贴板",
foreground="#888").pack(anchor="w", pady=(6, 0))
self._batch_data = []
def _browse_dir(self):
d = filedialog.askdirectory(title="选择 FinalShell conn 目录")
if d:
self._dir_var.set(d)
def _do_batch(self):
conn_dir = self._dir_var.get().strip()
if not conn_dir or not os.path.isdir(conn_dir):
messagebox.showerror("错误", "请选择有效的 conn 目录")
return
self._status_var.set("解密中…")
self.update_idletasks()
self._tree.delete(*self._tree.get_children())
data = scan_conn_dir(conn_dir)
self._batch_data = data
for row in data:
self._tree.insert("", "end", values=(
row["name"], row["host"], row["port"],
row["username"], row["password"], row["ver"]
))
self._status_var.set(f"共 {len(data)} 条连接")
def _on_tree_click(self, event):
region = self._tree.identify_region(event.x, event.y)
if region != "cell":
return
col = self._tree.identify_column(event.x)
# 第5列是 password(#5)
if col != "#5":
return
item = self._tree.identify_row(event.y)
if not item:
return
pwd = self._tree.item(item, "values")[4]
if pwd and not pwd.startswith("(") and not pwd.startswith("["):
self._copy_text(pwd)
self._status_var.set(f"已复制:{pwd}")
def _sort_by(self, col, reverse):
data = [(self._tree.set(k, col), k)
for k in self._tree.get_children("")]
data.sort(reverse=reverse)
for i, (_, k) in enumerate(data):
self._tree.move(k, "", i)
self._tree.heading(col,
command=lambda: self._sort_by(col, not reverse))
def _export_csv(self):
if not self._batch_data:
messagebox.showinfo("提示", "请先执行批量解密")
return
path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV 文件", "*.csv")],
title="导出 CSV"
)
if not path:
return
with open(path, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(
f, fieldnames=["name", "host", "port", "username", "password", "ver"],
extrasaction="ignore"
)
writer.writeheader()
for row in self._batch_data:
writer.writerow(row)
messagebox.showinfo("完成", f"已导出 {len(self._batch_data)} 条到:\n{path}")
def _copy_text(self, text: str):
self.clipboard_clear()
self.clipboard_append(text)
self.update()
# ── 入口 ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
app = App()
app.mainloop()