@walkerch/wxecho 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ /*
2
+ * find_all_keys_macos.c - macOS WeChat memory key scanner
3
+ *
4
+ * Scans WeChat process memory for SQLCipher encryption keys in the
5
+ * x'<key_hex><salt_hex>' format used by WeChat 4.x on macOS.
6
+ *
7
+ * Prerequisites:
8
+ * - WeChat must be ad-hoc signed (or SIP disabled)
9
+ * - Must run as root (sudo)
10
+ *
11
+ * Build:
12
+ * cc -O2 -o find_all_keys_macos find_all_keys_macos.c -framework Foundation
13
+ *
14
+ * Usage:
15
+ * sudo ./find_all_keys_macos [pid]
16
+ * If pid is omitted, automatically finds WeChat PID.
17
+ *
18
+ * Output: JSON file at ./all_keys.json (compatible with decrypt_db.py)
19
+ */
20
+
21
+ #include <stdio.h>
22
+ #include <stdlib.h>
23
+ #include <string.h>
24
+ #include <unistd.h>
25
+ #include <dirent.h>
26
+ #include <ftw.h>
27
+ #include <pwd.h>
28
+ #include <sys/stat.h>
29
+ #include <mach/mach.h>
30
+ #include <mach/mach_vm.h>
31
+
32
+ #define MAX_KEYS 256
33
+ #define KEY_SIZE 32
34
+ #define SALT_SIZE 16
35
+ #define HEX_PATTERN_LEN 96 /* 64 hex (key) + 32 hex (salt) */
36
+ #define CHUNK_SIZE (2 * 1024 * 1024)
37
+
38
+ typedef struct {
39
+ char key_hex[65];
40
+ char salt_hex[33];
41
+ char full_pragma[100];
42
+ } key_entry_t;
43
+
44
+ /* Forward declaration */
45
+ static int read_db_salt(const char *path, char *salt_hex_out);
46
+
47
+ /* nftw callback state for collecting DB files */
48
+ #define MAX_DBS 256
49
+ static char g_db_salts[MAX_DBS][33];
50
+ static char g_db_names[MAX_DBS][256];
51
+ static int g_db_count = 0;
52
+ static int nftw_collect_db(const char *fpath, const struct stat *sb,
53
+ int typeflag, struct FTW *ftwbuf) {
54
+ (void)sb; (void)ftwbuf;
55
+ if (typeflag != FTW_F) return 0;
56
+ size_t len = strlen(fpath);
57
+ if (len < 3 || strcmp(fpath + len - 3, ".db") != 0) return 0;
58
+ if (g_db_count >= MAX_DBS) return 0;
59
+
60
+ char salt[33];
61
+ if (read_db_salt(fpath, salt) != 0) return 0;
62
+
63
+ strcpy(g_db_salts[g_db_count], salt);
64
+ /* Extract relative path from db_storage/ */
65
+ const char *rel = strstr(fpath, "db_storage/");
66
+ if (rel) rel += strlen("db_storage/");
67
+ else {
68
+ rel = strrchr(fpath, '/');
69
+ rel = rel ? rel + 1 : fpath;
70
+ }
71
+ strncpy(g_db_names[g_db_count], rel, 255);
72
+ g_db_names[g_db_count][255] = '\0';
73
+ printf(" %s: salt=%s\n", g_db_names[g_db_count], salt);
74
+ g_db_count++;
75
+ return 0;
76
+ }
77
+
78
+ static int is_hex_char(unsigned char c) {
79
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
80
+ }
81
+
82
+ static pid_t find_wechat_pid(void) {
83
+ FILE *fp = popen("pgrep -x WeChat", "r");
84
+ if (!fp) return -1;
85
+ char buf[64];
86
+ pid_t pid = -1;
87
+ if (fgets(buf, sizeof(buf), fp))
88
+ pid = atoi(buf);
89
+ pclose(fp);
90
+ return pid;
91
+ }
92
+
93
+ /* Read DB salt (first 16 bytes) and return hex string */
94
+ static int read_db_salt(const char *path, char *salt_hex_out) {
95
+ FILE *f = fopen(path, "rb");
96
+ if (!f) return -1;
97
+ unsigned char header[16];
98
+ if (fread(header, 1, 16, f) != 16) { fclose(f); return -1; }
99
+ fclose(f);
100
+ /* Check if unencrypted */
101
+ if (memcmp(header, "SQLite format 3", 15) == 0) return -1;
102
+ for (int i = 0; i < 16; i++)
103
+ sprintf(salt_hex_out + i * 2, "%02x", header[i]);
104
+ salt_hex_out[32] = '\0';
105
+ return 0;
106
+ }
107
+
108
+ int main(int argc, char *argv[]) {
109
+ pid_t pid;
110
+ if (argc >= 2)
111
+ pid = atoi(argv[1]);
112
+ else
113
+ pid = find_wechat_pid();
114
+
115
+ if (pid <= 0) {
116
+ fprintf(stderr, "WeChat not running or invalid PID\n");
117
+ return 1;
118
+ }
119
+
120
+ printf("============================================================\n");
121
+ printf(" macOS WeChat Memory Key Scanner (C version)\n");
122
+ printf("============================================================\n");
123
+ printf("WeChat PID: %d\n", pid);
124
+
125
+ /* Get task port */
126
+ mach_port_t task;
127
+ kern_return_t kr = task_for_pid(mach_task_self(), pid, &task);
128
+ if (kr != KERN_SUCCESS) {
129
+ fprintf(stderr, "task_for_pid failed: %d\n", kr);
130
+ fprintf(stderr, "Make sure: (1) running as root, (2) WeChat is ad-hoc signed\n");
131
+ return 1;
132
+ }
133
+ printf("Got task port: %u\n", task);
134
+
135
+ /* Resolve real user's HOME (sudo may change HOME to /var/root) */
136
+ const char *home = getenv("HOME");
137
+ const char *sudo_user = getenv("SUDO_USER");
138
+ if (sudo_user) {
139
+ struct passwd *pw = getpwnam(sudo_user);
140
+ if (pw && pw->pw_dir)
141
+ home = pw->pw_dir;
142
+ }
143
+ if (!home) home = "/root";
144
+ printf("User home: %s\n", home);
145
+
146
+ /* Collect DB salts by recursively walking db_storage directories.
147
+ * Note: POSIX glob() does not support ** recursive matching on macOS,
148
+ * so we use nftw() to walk the directory tree instead. */
149
+ printf("\nScanning for DB files...\n");
150
+ char db_base_dir[512];
151
+ snprintf(db_base_dir, sizeof(db_base_dir),
152
+ "%s/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files",
153
+ home);
154
+
155
+ /* Walk each account's db_storage directory */
156
+ DIR *xdir = opendir(db_base_dir);
157
+ if (xdir) {
158
+ struct dirent *ent;
159
+ while ((ent = readdir(xdir)) != NULL) {
160
+ if (ent->d_name[0] == '.') continue;
161
+ char storage_path[768];
162
+ snprintf(storage_path, sizeof(storage_path),
163
+ "%s/%s/db_storage", db_base_dir, ent->d_name);
164
+ struct stat st;
165
+ if (stat(storage_path, &st) == 0 && S_ISDIR(st.st_mode)) {
166
+ nftw(storage_path, nftw_collect_db, 20, FTW_PHYS);
167
+ }
168
+ }
169
+ closedir(xdir);
170
+ }
171
+ printf("Found %d encrypted DBs\n", g_db_count);
172
+
173
+ /* Scan memory for x' patterns */
174
+ printf("\nScanning memory for keys...\n");
175
+ key_entry_t keys[MAX_KEYS];
176
+ int key_count = 0;
177
+ size_t total_scanned = 0;
178
+ int region_count = 0;
179
+
180
+ mach_vm_address_t addr = 0;
181
+ while (1) {
182
+ mach_vm_size_t size = 0;
183
+ vm_region_basic_info_data_64_t info;
184
+ mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
185
+ mach_port_t obj_name;
186
+
187
+ kr = mach_vm_region(task, &addr, &size, VM_REGION_BASIC_INFO_64,
188
+ (vm_region_info_t)&info, &info_count, &obj_name);
189
+ if (kr != KERN_SUCCESS) break;
190
+ if (size == 0) { addr++; continue; } /* guard against infinite loop */
191
+
192
+ if ((info.protection & (VM_PROT_READ | VM_PROT_WRITE)) ==
193
+ (VM_PROT_READ | VM_PROT_WRITE)) {
194
+ region_count++;
195
+
196
+ mach_vm_address_t ca = addr;
197
+ while (ca < addr + size) {
198
+ mach_vm_size_t cs = addr + size - ca;
199
+ if (cs > CHUNK_SIZE) cs = CHUNK_SIZE;
200
+
201
+ vm_offset_t data;
202
+ mach_msg_type_number_t dc;
203
+ kr = mach_vm_read(task, ca, cs, &data, &dc);
204
+ if (kr == KERN_SUCCESS) {
205
+ unsigned char *buf = (unsigned char *)data;
206
+ total_scanned += dc;
207
+
208
+ for (size_t i = 0; i + HEX_PATTERN_LEN + 3 < dc; i++) {
209
+ if (buf[i] == 'x' && buf[i + 1] == '\'') {
210
+ /* Check if followed by 96 hex chars and closing ' */
211
+ int valid = 1;
212
+ for (int j = 0; j < HEX_PATTERN_LEN; j++) {
213
+ if (!is_hex_char(buf[i + 2 + j])) { valid = 0; break; }
214
+ }
215
+ if (!valid) continue;
216
+ if (buf[i + 2 + HEX_PATTERN_LEN] != '\'') continue;
217
+
218
+ /* Extract key and salt hex */
219
+ char key_hex[65], salt_hex[33];
220
+ memcpy(key_hex, buf + i + 2, 64);
221
+ key_hex[64] = '\0';
222
+ memcpy(salt_hex, buf + i + 2 + 64, 32);
223
+ salt_hex[32] = '\0';
224
+
225
+ /* Convert to lowercase for comparison */
226
+ for (int j = 0; key_hex[j]; j++)
227
+ if (key_hex[j] >= 'A' && key_hex[j] <= 'F')
228
+ key_hex[j] += 32;
229
+ for (int j = 0; salt_hex[j]; j++)
230
+ if (salt_hex[j] >= 'A' && salt_hex[j] <= 'F')
231
+ salt_hex[j] += 32;
232
+
233
+ /* Deduplicate */
234
+ int dup = 0;
235
+ for (int k = 0; k < key_count; k++) {
236
+ if (strcmp(keys[k].key_hex, key_hex) == 0 &&
237
+ strcmp(keys[k].salt_hex, salt_hex) == 0) {
238
+ dup = 1; break;
239
+ }
240
+ }
241
+ if (dup) continue;
242
+
243
+ if (key_count < MAX_KEYS) {
244
+ strcpy(keys[key_count].key_hex, key_hex);
245
+ strcpy(keys[key_count].salt_hex, salt_hex);
246
+ snprintf(keys[key_count].full_pragma, sizeof(keys[key_count].full_pragma),
247
+ "x'%s%s'", key_hex, salt_hex);
248
+ key_count++;
249
+ }
250
+ }
251
+ }
252
+ mach_vm_deallocate(mach_task_self(), data, dc);
253
+ }
254
+ /* Advance with overlap to catch patterns spanning chunk boundaries.
255
+ * Pattern is x'<96 hex chars>' = 99 bytes total. */
256
+ if (cs > HEX_PATTERN_LEN + 3)
257
+ ca += cs - (HEX_PATTERN_LEN + 3);
258
+ else
259
+ ca += cs;
260
+ }
261
+ }
262
+ addr += size;
263
+ }
264
+
265
+ printf("\nScan complete: %zuMB scanned, %d regions, %d unique keys\n",
266
+ total_scanned / 1024 / 1024, region_count, key_count);
267
+
268
+ /* Match keys to DBs */
269
+ printf("\n%-25s %-66s %s\n", "Database", "Key", "Salt");
270
+ printf("%-25s %-66s %s\n",
271
+ "-------------------------",
272
+ "------------------------------------------------------------------",
273
+ "--------------------------------");
274
+
275
+ int matched = 0;
276
+ for (int i = 0; i < key_count; i++) {
277
+ const char *db = NULL;
278
+ for (int j = 0; j < g_db_count; j++) {
279
+ if (strcmp(keys[i].salt_hex, g_db_salts[j]) == 0) {
280
+ db = g_db_names[j];
281
+ matched++;
282
+ break;
283
+ }
284
+ }
285
+ printf("%-25s %-66s %s\n",
286
+ db ? db : "(unknown)",
287
+ keys[i].key_hex,
288
+ keys[i].salt_hex);
289
+ }
290
+ printf("\nMatched %d/%d keys to known DBs\n", matched, key_count);
291
+
292
+ /* Save JSON: { "rel/path.db": { "enc_key": "hex" }, ... }
293
+ * Uses forward slashes (native macOS paths, valid JSON without escaping).
294
+ */
295
+ const char *out_path = "all_keys.json";
296
+ FILE *fp = fopen(out_path, "w");
297
+ if (fp) {
298
+ fprintf(fp, "{\n");
299
+ int first = 1;
300
+ for (int i = 0; i < key_count; i++) {
301
+ const char *db = NULL;
302
+ for (int j = 0; j < g_db_count; j++) {
303
+ if (strcmp(keys[i].salt_hex, g_db_salts[j]) == 0) {
304
+ db = g_db_names[j];
305
+ break;
306
+ }
307
+ }
308
+ if (!db) continue;
309
+ fprintf(fp, "%s \"%s\": {\"enc_key\": \"%s\"}",
310
+ first ? "" : ",\n", db, keys[i].key_hex);
311
+ first = 0;
312
+ }
313
+ fprintf(fp, "\n}\n");
314
+ fclose(fp);
315
+ printf("Saved to %s\n", out_path);
316
+ }
317
+
318
+ return 0;
319
+ }
@@ -0,0 +1,38 @@
1
+ import os
2
+ import posixpath
3
+
4
+
5
+ def strip_key_metadata(keys):
6
+ """移除 all_keys.json 中以下划线开头的元数据字段,返回新 dict。"""
7
+ return {k: v for k, v in keys.items() if not k.startswith("_")}
8
+
9
+
10
+ def _is_safe_rel_path(path):
11
+ """检查路径不包含 .. 等遍历组件。"""
12
+ normalized = path.replace("\\", "/")
13
+ return ".." not in posixpath.normpath(normalized).split("/")
14
+
15
+
16
+ def key_path_variants(rel_path):
17
+ """生成同一路径的多种分隔符表示,兼容 Windows/Linux JSON key。"""
18
+ normalized = rel_path.replace("\\", "/")
19
+ variants = []
20
+ for candidate in (
21
+ rel_path,
22
+ normalized,
23
+ normalized.replace("/", "\\"),
24
+ normalized.replace("/", os.sep),
25
+ ):
26
+ if candidate not in variants:
27
+ variants.append(candidate)
28
+ return variants
29
+
30
+
31
+ def get_key_info(keys, rel_path):
32
+ """按相对路径查找数据库密钥,自动兼容不同平台分隔符。"""
33
+ if not _is_safe_rel_path(rel_path):
34
+ return None
35
+ for candidate in key_path_variants(rel_path):
36
+ if candidate in keys and not candidate.startswith("_"):
37
+ return keys[candidate]
38
+ return None