william1324 commited on
Commit
ea57ef5
·
verified ·
1 Parent(s): 2e4999a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -140
app.py CHANGED
@@ -1,178 +1,154 @@
1
  import os
2
- import subprocess
3
- import urllib.request
4
  import gradio as gr
5
  from datasets import load_dataset
6
- import spaces
7
 
8
- def download_file(url, filename):
9
- """使用 Python 原生庫下載檔案,避開系統層面 wget 被阻擋的問題"""
10
  try:
11
- print(f"開始下載: {url} -> {filename}")
12
- opener = urllib.request.build_opener()
13
- opener.addheaders = [('User-agent', 'Mozilla/5.0')]
14
- urllib.request.install_opener(opener)
15
- urllib.request.urlretrieve(url, filename)
16
- return True
17
- except Exception as e:
18
- print(f"下載失敗: {str(e)}")
19
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- @spaces.GPU
22
- def crack_pdf(pdf_file, hf_repo, custom_mask):
23
  if pdf_file is None:
24
  yield "❌ 請先上傳 PDF 檔案!"
25
  return
26
-
27
- # ==========================================
28
- # 步驟 1: 自動下載並部署免安裝版 Hashcat (Linux 二進位)
29
- # ==========================================
30
- hashcat_dir = "hashcat-6.2.6"
31
- hashcat_bin = f"./{hashcat_dir}/hashcat.bin"
32
-
33
- if not os.path.exists(hashcat_bin):
34
- yield "🔄 首次執行,正在背景下載 Linux 專用免安裝版 Hashcat(約 5-10 秒)..."
35
-
36
- # 官方 Linux 執行檔的壓縮包網址
37
- url_hc = "https://github.com"
38
- tar_file = "hashcat_download.tar.gz"
39
-
40
- if download_file(url_hc, tar_file):
41
- yield "🔄 下載成功,正在本地解壓縮..."
42
- try:
43
- subprocess.run(f"tar -zxf {tar_file}", shell=True, check=True)
44
- subprocess.run(f"chmod +x {hashcat_bin}", shell=True, check=True)
45
- subprocess.run(f"rm -f {tar_file}", shell=True) # 清理空間
46
- yield "✅ Hashcat 運作環境自動部署成功!\n"
47
- except Exception as e:
48
- yield f"❌ 解壓失敗: {str(e)}。請嘗試重新點擊。"
49
- return
50
- else:
51
- yield "❌ 無法透過網路下載 Hashcat 執行檔。提示:請確認您的 Space 是否能正常連網。"
52
- return
53
- else:
54
- yield "✅ 偵測到本地 Hashcat 運作環境。\n"
55
 
56
- # ==========================================
57
- # 步驟 2: 自動準備 PDF 雜湊提取工具 (pdf2john.py)
58
- # ==========================================
59
- pdf2john_script = "pdf2john.py"
60
- if not os.path.exists(pdf2john_script):
61
- yield "🔄 正在自動下載 PDF 雜湊提取工具..."
62
- url_john = "https://githubusercontent.com"
63
- if download_file(url_john, pdf2john_script):
64
- subprocess.run(f"chmod +x {pdf2john_script}", shell=True)
65
- yield "✅ 提取工具下載完成。\n"
66
- else:
67
- yield "❌ 提取工具下載失敗,請重新點擊按鈕重試。"
68
  return
 
 
 
 
 
69
 
70
  # ==========================================
71
- # 步驟 3: 提取 PDF 雜湊值
72
  # ==========================================
73
- yield "🔄 正在解析 PDF 檔案結構並提取雜湊值 (Hash)..."
74
- hash_path = "pdf_hash.txt"
75
- try:
76
- cmd_extract = f"python3 {pdf2john_script} '{pdf_file.name}' > {hash_path}"
77
- subprocess.run(cmd_extract, shell=True, check=True)
78
- except subprocess.CalledProcessError as e:
79
- yield f"❌ PDF 雜湊提取失敗 (請確認該 PDF 是否確實有設定密碼保護): {str(e)}"
80
- return
81
-
82
- if not os.path.exists(hash_path) or os.path.getsize(hash_path) == 0:
83
- yield "❌ 未能從該 PDF 中提取出有效的雜湊值,檔案可能未加密。"
 
 
 
 
84
  return
85
 
86
- with open(hash_path, "r") as f:
87
- hash_content = f.read().strip()
88
-
89
- # 根據前綴特徵判斷 Hashcat 的 -m 參數類型
90
- mode = "10500"
91
- pdf_type_str = "未知版本"
92
- if "pdf1*" in hash_content:
93
- mode = "10400"
94
- pdf_type_str = "PDF 1.1 - 1.3 (40-bit)"
95
- elif "pdf3*" in hash_content:
96
- mode = "10500"
97
- pdf_type_str = "PDF 1.4 - 1.6 (128-bit)"
98
- elif "pdf4*" in hash_content:
99
- mode = "10600"
100
- pdf_type_str = "PDF 1.7 Extension 3 (268-bit)"
101
- elif "pdf5*" in hash_content:
102
- mode = "10700"
103
- pdf_type_str = "PDF 1.7 Level 8 (Acrobat 10-11)"
104
-
105
- current_status = f"📋 偵測到 PDF 加密規格:{pdf_type_str} (Hashcat 代碼: -m {mode})\n"
106
- yield current_status
107
-
108
  # ==========================================
109
- # 步驟 4: 配置 🚀 Hashcat 執行指令
110
  # ==========================================
111
- if custom_mask:
112
- cmd_crack = f"{hashcat_bin} -m {mode} -a 3 {hash_path} '{custom_mask}' --potfile-disable --quiet"
113
- current_status += f"🚀 啟動遮罩攻擊,當前遮罩為: {custom_mask}\n⏳ 正在使用雲端算力進行暴力破解,請稍候..."
114
- yield current_status
115
  else:
116
- current_status += f"🔄 正在從 Hugging Face 下載並轉換字典檔: {hf_repo} ..."
117
- yield current_status
118
  try:
119
- dataset = load_dataset(hf_repo, split="train", trust_remote_code=True)
120
- wordlist_path = "downloaded_wordlist.txt"
 
121
 
122
- with open(wordlist_path, "w", encoding="utf-8", errors="ignore") as f:
123
- for item in dataset:
124
- for key in ['password', 'text', 'word', 'pass']:
125
- if key in item and item[key]:
126
- f.write(str(item[key]).strip() + "\n")
127
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- cmd_crack = f"{hashcat_bin} -m {mode} -a 0 {hash_path} {wordlist_path} --potfile-disable --quiet"
130
- current_status += f"\n📊 字典下載成功!已寫入本地儲存區。\n🚀 啟動字典攻擊...\n⏳ 正在執行,請稍候..."
131
- yield current_status
132
- except Exception as e:
133
- yield f"{current_status}\n❌ 由於網路沙箱限制,無法直接拉取外部 Hub 字典。錯誤: {str(e)}\n💡 提示:請改用【方案 B:自訂遮罩攻擊】進行免網路的密碼破解。"
134
- return
135
-
136
- # ==========================================
137
- # 步驟 5: 執行 Hashcat 運算與結果呈現
138
- # ==========================================
139
- try:
140
- cmd_crack += " --force"
141
- result = subprocess.run(cmd_crack, shell=True, capture_output=True, text=True)
142
-
143
- if result.returncode == 0 or "Cracked" in result.stdout:
144
- cmd_show = f"{hashcat_bin} -m {mode} {hash_path} --show --force"
145
- show_result = subprocess.run(cmd_show, shell=True, capture_output=True, text=True)
146
- yield f"{current_status}\n\n🎉 🎉 🎉 破解成功! 🎉 🎉 🎉\n\n【解鎖密碼結果】如下:\n{show_result.stdout.strip()}"
147
- else:
148
- yield f"{current_status}\n\n❌ 破解結束。在目前的字典或遮罩組合範圍內,未找到匹配的密碼。\n\n【系統除錯資訊】:\n{result.stderr}\n{result.stdout}"
149
 
150
- except Exception as e:
151
- yield f"❌ Hashcat 執行期間發生系統異常: {str(e)}"
152
 
153
  # ==========================================
154
- # Gradio UI 介面
155
  # ==========================================
156
- with gr.Blocks(title="雲端 Hashcat PDF 解鎖器", theme=gr.themes.Soft()) as demo:
157
- gr.Markdown("# 🛠️ Hugging Face 雲端 Hashcat PDF 解鎖器")
158
- gr.Markdown("本工具採用全新自動化環境下載與部署架構,一鍵即可在雲端進行 PDF 密碼恢復。")
159
 
160
  with gr.Row():
161
  with gr.Column(scale=1):
162
  pdf_input = gr.File(label="1. 上傳受保護的 PDF 檔案 (.pdf)", file_types=[".pdf"])
163
 
164
- with gr.Tab("方案 A:HF 字典攻擊"):
165
- hf_repo_input = gr.Textbox(value="Canstralian/Wordlists", label="Hugging Face 字典庫儲存庫")
 
 
 
166
 
167
- with gr.Tab("方案 B:自訂遮罩攻擊"):
168
- mask_input = gr.Textbox(label="Hashcat 遮罩 (Mask)", placeholder="例如: Secret?d?d?d")
169
- gr.Markdown("<small>提示:`?l`=小寫, `?u`=大寫, `?d`=數字, `?s`=特殊符號</small>")
 
 
 
170
 
171
- btn = gr.Button("🚀 開始雲端破譯", variant="primary", size="large")
172
 
173
  with gr.Column(scale=1):
174
- output_box = gr.Textbox(label="🖥️ 雲端算力執行狀態與破譯結果", lines=18, placeholder="等待任務啟動...")
 
 
 
 
175
 
176
- btn.click(fn=crack_pdf, inputs=[pdf_input, hf_repo_input, mask_input], outputs=output_box)
 
 
 
 
177
 
178
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import os
2
+ import itertools
 
3
  import gradio as gr
4
  from datasets import load_dataset
5
+ from pypdf import PdfReader
6
 
7
+ def check_pdf_password(pdf_path, password):
8
+ """檢查單個密碼是否能成功解鎖 PDF"""
9
  try:
10
+ reader = PdfReader(pdf_path)
11
+ if reader.is_encrypted:
12
+ # 嘗試解密
13
+ result = reader.decrypt(password)
14
+ # 部分情況下 decrypt 傳回 1 或 2 代表成功
15
+ if result > 0:
16
+ # 測試是否真的能讀取頁面(防範偽陽性)
17
+ _ = len(reader.pages)
18
+ return True
19
+ else:
20
+ return True # 未加密
21
+ except Exception:
22
+ pass
23
+ return False
24
+
25
+ def generate_mask_passwords(mask):
26
+ """將 Hashcat 遮罩語法(部分支援)轉換為 Python 密碼生成器"""
27
+ # 支援基礎的 ?d (數字)
28
+ # 例如: Secret?d?d?d -> 產生 Secret000 到 Secret999
29
+ if "?d" not in mask:
30
+ return [mask]
31
+
32
+ parts = mask.split("?d")
33
+ num_digits = len(parts) - 1
34
+ prefix = parts[0]
35
+
36
+ # 生成所有可能的數字組合
37
+ combinations = itertools.product("0123456789", repeat=num_digits)
38
+ passwords = []
39
+ for combo in combinations:
40
+ passwords.append(prefix + "".join(combo))
41
+ return passwords
42
 
43
+ def crack_pdf_pure_python(pdf_file, hf_repo, custom_mask):
 
44
  if pdf_file is None:
45
  yield "❌ 請先上傳 PDF 檔案!"
46
  return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # 檢查 PDF 加密狀態
49
+ try:
50
+ reader = PdfReader(pdf_file.name)
51
+ if not reader.is_encrypted:
52
+ yield "💡 提示:此 PDF 檔案本來就沒有加密,可以直接打開!"
 
 
 
 
 
 
 
53
  return
54
+ except Exception as e:
55
+ yield f"❌ 無法讀取 PDF 檔案結構: {str(e)}"
56
+ return
57
+
58
+ yield "📋 PDF 結構解析成功(檔案處於加密受保護狀態)...\n"
59
 
60
  # ==========================================
61
+ # 方案 B: 自訂遮罩攻擊 (純 Python 暴力破譯)
62
  # ==========================================
63
+ if custom_mask:
64
+ yield f"🔄 正在將遮罩 '{custom_mask}' 展開為密碼組合..."
65
+ passwords = generate_mask_passwords(custom_mask)
66
+ total = len(passwords)
67
+ yield f"🚀 開始執行遮罩破譯(共計 {total} 組嘗試)...\n"
68
+
69
+ for idx, pwd in enumerate(passwords):
70
+ if idx % max(1, total // 10) == 0:
71
+ yield f"⏳ 已嘗試 {idx}/{total} 組密碼組合..."
72
+
73
+ if check_pdf_password(pdf_file.name, pwd):
74
+ yield f"🎉 🎉 🎉 破解成功! 🎉 🎉 🎉\n\n【解鎖密碼結果】:{pwd}"
75
+ return
76
+
77
+ yield f"❌ 破譯結束。在自訂遮罩 [{custom_mask}] 產生的 {total} 組組合中未找到正確密碼。"
78
  return
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  # ==========================================
81
+ # 方案 A: 字典攻擊模式 (載入 Hugging Face 字典)
82
  # ==========================================
 
 
 
 
83
  else:
84
+ yield f"🔄 正在從 Hugging Face 線上加載密碼資料集: {hf_repo} ..."
 
85
  try:
86
+ # 線上串流 (Streaming) 讀取資料集,不佔用本機硬碟空間,速度極快
87
+ dataset = load_dataset(hf_repo, split="train", streaming=True, trust_remote_code=True)
88
+ yield "📊 資料集連線建立成功!開始進行即時流式字典碰撞...\n"
89
 
90
+ count = 0
91
+ for item in dataset:
92
+ count += 1
93
+ # 尋找可能包含密碼的欄位
94
+ pwd = None
95
+ for key in ['password', 'text', 'word', 'pass']:
96
+ if key in item and item[key]:
97
+ pwd = str(item[key]).strip()
98
+ break
99
+
100
+ if not pwd:
101
+ continue
102
+
103
+ if count % 500 == 0:
104
+ yield f"⏳ 已即時碰撞 {count} 個字典密碼..."
105
+
106
+ if check_pdf_password(pdf_file.name, pwd):
107
+ yield f"🎉 🎉 🎉 破解成功! 🎉 🎉 🎉\n\n【解鎖密碼結果】:{pwd}"
108
+ return
109
 
110
+ yield f"❌ 破譯結束。已完整比對該資料集的 {count} 個密碼,未能成功解鎖。"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ except Exception as e:
113
+ yield f"❌ 字典加載或比對失敗: {str(e)}\n\n💡 建議:如果該資料集封鎖了外部連接,請切換至【方案 B:自訂遮罩攻擊】輸入您的猜測密碼(例如:Secret?d?d?d)進行解鎖。"
114
 
115
  # ==========================================
116
+ # Gradio 響應式網頁介面
117
  # ==========================================
118
+ with gr.Blocks(title="雲端 PDF 線上解鎖器", theme=gr.themes.Soft()) as demo:
119
+ gr.Markdown("# 🛠️ Hugging Face 雲端 PDF 線上解鎖器")
120
+ gr.Markdown("採用全 Python 內建安全架構,無須依賴系統層面外掛。100% 兼容任何 Hugging Face Spaces 容器環境。")
121
 
122
  with gr.Row():
123
  with gr.Column(scale=1):
124
  pdf_input = gr.File(label="1. 上傳受保護的 PDF 檔案 (.pdf)", file_types=[".pdf"])
125
 
126
+ with gr.Tab("方案 A:HF 字典碰撞"):
127
+ hf_repo_input = gr.Textbox(
128
+ value="Canstralian/Wordlists",
129
+ label="Hugging Face 密碼字典庫"
130
+ )
131
 
132
+ with gr.Tab("方案 B:自訂遮罩暴力破譯"):
133
+ mask_input = gr.Textbox(
134
+ label="密碼特徵遮罩",
135
+ placeholder="例如: 123?d?d?d (代表123後面猜3碼數字)"
136
+ )
137
+ gr.Markdown("<small>目前支援語法:`?d` 代表 0-9 的任意數字。</small>")
138
 
139
+ btn = gr.Button("🚀 開始雲端解鎖", variant="primary", size="large")
140
 
141
  with gr.Column(scale=1):
142
+ output_box = gr.Textbox(
143
+ label="🖥️ 雲端算力即時解鎖進度與結果",
144
+ lines=18,
145
+ placeholder="等待任務啟動..."
146
+ )
147
 
148
+ btn.click(
149
+ fn=crack_pdf_pure_python,
150
+ inputs=[pdf_input, hf_repo_input, mask_input],
151
+ outputs=output_box
152
+ )
153
 
154
  demo.launch(server_name="0.0.0.0", server_port=7860)