-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbackground.js
More file actions
222 lines (213 loc) · 8.55 KB
/
background.js
File metadata and controls
222 lines (213 loc) · 8.55 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
const store = {};
chrome.webRequest.onHeadersReceived.addListener(
(details) => {
const tabId = details.tabId;
if (tabId < 0) return;
const headers = details.responseHeaders || [];
let csp = null;
for (const h of headers) {
const n = (h.name || "").toLowerCase();
if (n === "content-security-policy") {
csp = h.value || "";
break;
}
}
store[tabId] = {
csp,
headers: headers,
url: details.url || "",
time: Date.now()
};
},
{ urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] },
["responseHeaders"]
);
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (!message || !message.type) return;
if (message.type === "GET_HEADERS") {
const tabId = message.tabId;
const v = store[tabId] || null;
sendResponse({ ok: !!v, data: v });
return true;
}
if (message.type === "GET_CSP") {
const tabId = message.tabId;
const v = store[tabId] || null;
sendResponse({ ok: !!v, data: v });
return true;
}
if (message.type === "SQL_FETCH") {
(async () => {
try {
const url = String(message.url || "");
const method = String(message.method || "GET").toUpperCase();
const headersIn = message.headers && typeof message.headers === "object" ? message.headers : {};
const body = message.body === undefined ? undefined : String(message.body);
const headers = {};
Object.keys(headersIn).forEach((k) => {
const v = headersIn[k];
if (v === undefined || v === null) return;
headers[String(k)] = String(v);
});
const start = Date.now();
const resp = await fetch(url, {
method,
headers,
body
});
const ms = Date.now() - start;
const h = [];
resp.headers.forEach((v, k) => h.push(`${k}: ${v}`));
const text = await resp.text();
const limit = 220000;
const bodyOut = text.length > limit ? (text.slice(0, limit) + `\n\n...[TRUNCATED ${text.length - limit} chars]`) : text;
sendResponse({
ok: true,
meta: `${resp.status} ${resp.statusText} | ${ms}ms`,
headers: h.join("\n"),
body: bodyOut
});
} catch (e) {
sendResponse({ ok: false, error: String(e && e.message ? e.message : e) });
}
})();
return true;
}
if (message.type === "DEEP_SNIFF") {
(async () => {
try {
const urls = Array.isArray(message.urls) ? message.urls : [];
const html = typeof message.html === "string" ? message.html : "";
const regs = {
ip: /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d{2,5})?\b/g,
url: /\bhttps?:\/\/[^\s"'<>]+/gi,
domain: /\b(?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9-]+\.(?:com|cn)\b/gi,
jwt: /\beyJ[0-9A-Za-z_-]+\.[0-9A-Za-z_-]+\.[0-9A-Za-z_-]+\b/g,
key: /\b(?:api[_-]?key|access[_-]?key|secret|token)\b\s*[:=]\s*["']?([A-Za-z0-9-_]{16,})["']?/gi,
email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
phone: /\b\d{11}\b/g,
crypto: /\b(AES|RSA|MD5|SHA256|SHA-256|bcrypt)\b/gi,
sensitive: /\b(password|passwd|pwd|username|user_name|token|access_token|id_token|auth_token)\b/gi
};
const out = { ip: [], url: [], absolute_path: [], relative_path: [], domain: [], jwt: [], key: [], email: [], phone: [], crypto: [], sensitive: [] };
const decodeEntities = (s) => {
if (!s) return s;
let t = s.replace(/"|"|"/gi, '"').replace(/'|'|'/gi, "'").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">");
t = t.replace(/\s+/g, (m) => m);
return t;
};
const cleanUrl = (raw) => {
if (!raw) return null;
let u = String(raw).trim();
u = decodeEntities(u);
u = u.replace(/^url\(\s*(['"]?)([^'")]+)\1\s*\)\s*;?$/i, "$2");
u = u.replace(/^['"]+|['")]+$/g, "");
const mFull = u.match(/^(https?:\/\/[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+)/);
if (mFull && mFull[1]) u = mFull[1];
u = u.replace(/[)"'`;:,。、)\]\}\>]+$/g, "");
u = u.replace(/^([^)\s"'`,;,。、)\]\}\>]+).*$/, "$1");
const noQuery = u.split(/[?#]/)[0];
const extBoundary = noQuery.match(/\.(png|jpg|jpeg|gif|svg|webp|ico|css|map|woff2?|ttf|otf|eot|pdf|mp3|mp4|webm|m4a|aac|wav)\b/i);
if (extBoundary) {
const idx = noQuery.toLowerCase().indexOf("." + extBoundary[1].toLowerCase());
if (idx >= 0) {
const cut = idx + 1 + extBoundary[1].length;
u = noQuery.slice(0, cut);
}
}
const staticExt = /\.(?:png|jpg|jpeg|gif|svg|webp|ico|css|map|woff2?|ttf|otf|eot|pdf|mp3|mp4|webm|m4a|aac|wav)$/i;
if (staticExt.test(noQuery)) return null;
if (/^https?:\/\//i.test(u) || u.startsWith("/") || u.startsWith("./") || u.startsWith("../")) return u;
return null;
};
const analyze = (text, sourceName) => {
if (!text) return;
const newlines = [];
let idx = -1;
while ((idx = text.indexOf('\n', idx + 1)) !== -1) {
newlines.push(idx);
}
const findLine = (charIndex) => {
let l = 0, r = newlines.length - 1, res = 0;
while (l <= r) {
const m = (l + r) >>> 1;
if (newlines[m] < charIndex) {
res = m + 1;
l = m + 1;
} else {
r = m - 1;
}
}
return res + 1;
};
const add = (k, val, line) => {
out[k].push({ value: val, source: sourceName, line });
};
for (const k of Object.keys(regs)) {
const matches = text.matchAll(regs[k]);
for (const m of matches) {
const val = m[0];
const line = findLine(m.index);
if (k === "domain") {
add(k, String(val).toLowerCase(), line);
} else if (k === "url") {
const c = cleanUrl(val);
if (c) add(k, c, line);
} else {
add(k, String(val).slice(0, 500), line);
}
}
}
const kv = /\b(password|passwd|pwd|username|user_name|token|access_token|id_token|auth_token)\b\s*[:=]\s*["']?([A-Za-z0-9._-]{4,})["']?/gi;
for (const m of text.matchAll(kv)) {
add("sensitive", m[0].slice(0, 500), findLine(m.index));
}
const processApiMatch = (matches, groupIdx) => {
for (const m of matches) {
if (m[groupIdx]) {
const v = cleanUrl(m[groupIdx]);
if (v) {
const line = findLine(m.index);
if (v.startsWith("/")) add("absolute_path", v, line);
else if (v.startsWith("./") || v.startsWith("../")) add("relative_path", v, line);
else add("url", v, line);
}
}
}
};
processApiMatch(text.matchAll(/fetch\s*\(\s*(['"])([^'"]+)\1/gi), 2);
processApiMatch(text.matchAll(/axios(?:\.\w+)?\s*\(\s*(['"])([^'"]+)\1/gi), 2);
processApiMatch(text.matchAll(/xhr\.open\s*\(\s*['"](?:GET|POST|PUT|DELETE|PATCH)['"]\s*,\s*['"]([^'"]+)['"]/gi), 1);
processApiMatch(text.matchAll(/\$\.\s*ajax\s*\(\s*\{[\s\S]*?url\s*:\s*['"]([^'"]+)['"]/gi), 1);
processApiMatch(text.matchAll(/\$\.\s*(?:get|post|put|delete)\s*\(\s*['"]([^'"]+)['"]/gi), 2);
processApiMatch(text.matchAll(/graphql\s*['"]?endpoint['"]?\s*[:=]\s*['"]([^'"]+)['"]/gi), 1);
processApiMatch(text.matchAll(/['"]((?:\/|\.\.?\/)[A-Za-z0-9/_\-\.]+(?:\?[^\s"'<>]*)?)['"]/g), 1);
};
analyze(html, "Current Page");
for (const u of urls) {
try {
const resp = await fetch(u, { mode: "cors" });
const t = await resp.text();
analyze(t, u);
} catch (e) {}
}
for (const k of Object.keys(out)) {
const seen = new Set();
const unique = [];
for (const item of out[k]) {
const key = item.value + "|" + item.source + "|" + item.line;
if (!seen.has(key)) {
seen.add(key);
unique.push(item);
}
}
out[k] = unique;
}
sendResponse({ ok: true, result: out });
} catch (e) {
sendResponse({ ok: false, error: String(e) });
}
})();
return true;
}
});