-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
345 lines (281 loc) · 11.9 KB
/
Copy pathpopup.js
File metadata and controls
345 lines (281 loc) · 11.9 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
// Define global variables
let extractedData = {
ipAddresses: [],
urlsAndUris: [],
hashes: [],
cves: []
};
let extractedMatches = [];
let markersInfo = []; // store { ioc, id } for jump buttons
const patterns = {
ipAddresses: /\b(?:\d{1,3}(?:\.\d{1,3}|\[\.\]){3}\d{1,3}|\d{1,3}(?:\[\.\]\d{1,3}){3}|\d{1,3}(?:\.\d{1,3}){3})\b/g,
urlsAndUris: /\b(?:https?:\/\/[^\s/$.?#].[^\s]*|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|[a-zA-Z0-9-]+\[[.]\][a-zA-Z]{2,}|[a-zA-Z]:\\[^\\]+\\[^\\]+\\[^\\]+\\[^\\]+\.[a-zA-Z0-9]+|\/[^\s/]+(?:\/[^\s/]+)*|\\\\[^\\]+\\[^\\]+(?:\\[^\\]+)+\\[^\s/]+\.[a-zA-Z0-9]+)\b/g,
hashes: /\b[0-9a-fA-F]{32}\b|\b[0-9a-fA-F]{40}\b|\b[0-9a-fA-F]{64}\b/g,
cves: /\bCVE-\d{4}-\d{4,7}\b/g
};
// Union pattern for extracting matches from the returned marker list
const unionPattern = new RegExp(
patterns.ipAddresses.source + '|' +
patterns.urlsAndUris.source + '|' +
patterns.hashes.source + '|' +
patterns.cves.source,
'g'
);
// Extract data from the active tab
function extractDataFromTab(tabId) {
chrome.scripting.executeScript({
target: { tabId: tabId },
function: extractTextWithMarkers
}, function(results) {
// results[0].result is an array of { ioc, id }
markersInfo = results[0].result;
// Extract unique IOCs by type from markersInfo
extractedData = {
ipAddresses: [],
urlsAndUris: [],
hashes: [],
cves: []
};
extractedMatches = [];
for (const { ioc } of markersInfo) {
extractedMatches.push(ioc);
}
// Extract categorized data for internal usage
const categorized = extractIpAddressAndUrlAndHashes(extractedMatches.join(' '));
extractedData = categorized;
console.log("Extracted Data:", extractedData);
console.log("Markers Info:", markersInfo);
displayMatches();
});
}
// Display matches in popup with Remove + Jump buttons
function displayMatches() {
const extractedDataContainer = document.getElementById('extractedData');
extractedDataContainer.innerHTML = '';
const categories = {
hashes: 'Hashes',
ipAddresses: 'IP Addresses',
urlsAndUris: 'Domains / URLs',
cves: 'CVEs'
};
for (const key in categories) {
const label = categories[key];
const items = extractedData[key];
if (items.length === 0) continue;
const section = document.createElement('div');
section.className = 'ioc-section';
const title = document.createElement('h3');
title.textContent = label;
section.appendChild(title);
items.forEach(match => {
const marker = markersInfo.find(m => m.ioc === match);
const id = marker ? marker.id : null;
const div = createItemDiv(match, '', id);
section.appendChild(div);
});
extractedDataContainer.appendChild(section);
}
}
// Create div for each IOC with Remove and Jump buttons
function createItemDiv(value, label, markerId) {
const div = document.createElement('div');
const removeButton = document.createElement('button');
removeButton.textContent = 'Remove';
removeButton.addEventListener('click', function() {
removeItem(value);
});
div.appendChild(removeButton);
if (markerId) {
const jumpButton = document.createElement('button');
jumpButton.textContent = 'Jump to IOC';
jumpButton.addEventListener('click', function() {
jumpToMarker(markerId);
});
div.appendChild(jumpButton);
}
const text = document.createElement('span');
text.textContent = label + value;
div.appendChild(text);
return div;
}
// Remove item from extractedMatches and extractedData
function removeItem(value) {
extractedMatches = extractedMatches.filter(match => match !== value);
removeFromExtractedData(value);
displayMatches();
}
// Remove from extractedData categories
function removeFromExtractedData(value) {
extractedData.ipAddresses = extractedData.ipAddresses.filter(ip => ip !== value);
extractedData.urlsAndUris = extractedData.urlsAndUris.filter(url => url !== value);
extractedData.hashes = extractedData.hashes.filter(hash => hash !== value);
extractedData.cves = extractedData.cves.filter(cve => cve !== value);
}
// Scroll the page to the marker element by id
function jumpToMarker(markerId) {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
function: (id) => {
const el = document.getElementById(id);
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
// Optionally highlight the element briefly
el.style.transition = 'background-color 0.5s ease';
el.style.backgroundColor = 'yellow';
setTimeout(() => { el.style.backgroundColor = ''; }, 1500);
}
},
args: [markerId]
});
});
}
// Extract IP addresses, URLs, hashes, and CVEs from text array or string
function extractIpAddressAndUrlAndHashes(text) {
if (Array.isArray(text)) text = text.join(' ');
const extractedData = {};
for (const key in patterns) {
const pattern = patterns[key];
const matches = text.match(pattern);
if (matches) {
extractedData[key] = [...new Set(matches)];
} else {
extractedData[key] = [];
}
}
return extractedData;
}
// This runs inside the page context to inject markers and return array of matches + ids
function extractTextWithMarkers() {
const patternsArray = [
{ key: 'ipAddresses', pattern: /\b(?:\d{1,3}(?:\.\d{1,3}|\[\.\]){3}\d{1,3}|\d{1,3}(?:\[\.\]\d{1,3}){3}|\d{1,3}(?:\.\d{1,3}){3})\b/g },
{ key: 'urlsAndUris', pattern: /\b(?:https?:\/\/[^\s/$.?#].[^\s]*|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|[a-zA-Z0-9-]+\[[.]\][a-zA-Z]{2,}|[a-zA-Z]:\\[^\\]+\\[^\\]+\\[^\\]+\\[^\\]+\.[a-zA-Z0-9]+|\/[^\s/]+(?:\/[^\s/]+)*|\\\\[^\\]+\\[^\\]+(?:\\[^\\]+)+\\[^\s/]+\.[a-zA-Z0-9]+)\b/g },
{ key: 'hashes', pattern: /\b[0-9a-fA-F]{32}\b|\b[0-9a-fA-F]{40}\b|\b[0-9a-fA-F]{64}\b/g },
{ key: 'cves', pattern: /\bCVE-\d{4}-\d{4,7}\b/g }
];
// Walk text nodes and replace matches with <span> markers with unique IDs
function walkNodes(node) {
// Skip unwanted nodes
if (
node.nodeType === Node.ELEMENT_NODE &&
['SCRIPT', 'STYLE', 'NOSCRIPT', 'CODE', 'PRE'].includes(node.tagName)
) {
return; // skip script, style, code blocks, preformatted text
}
if (node.nodeType === Node.TEXT_NODE) {
// Only process text nodes that have visible text and whose parent is visible
const parent = node.parentElement;
if (!parent) return;
// Skip if parent or any ancestor is hidden (display:none or visibility:hidden)
let el = parent;
while (el && el !== document.body) {
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden') {
return;
}
el = el.parentElement;
}
let text = node.nodeValue;
let matches = [];
// Collect all matches from all patterns
patternsArray.forEach(({ pattern }) => {
pattern.lastIndex = 0;
let m;
while ((m = pattern.exec(text)) !== null) {
matches.push({ index: m.index, length: m[0].length, text: m[0] });
}
});
if (matches.length === 0) return;
// Sort matches by index ascending
matches.sort((a, b) => a.index - b.index);
// Filter overlapping matches, keep first
let filteredMatches = [];
let lastEnd = -1;
for (const match of matches) {
if (match.index >= lastEnd) {
filteredMatches.push(match);
lastEnd = match.index + match.length;
}
}
// Rebuild the node with inserted span markers
const fragment = document.createDocumentFragment();
let lastPos = 0;
filteredMatches.forEach(({ index, length, text }) => {
// Add text before match
if (index > lastPos) {
fragment.appendChild(document.createTextNode(text.substring(lastPos, index)));
}
// Add matched text wrapped in span with unique id
const span = document.createElement('span');
span.textContent = text;
span.className = 'ioc-marker';
const uniqueId = `ioc-${Date.now()}-${Math.floor(Math.random() * 1000000)}`;
span.id = uniqueId;
span.setAttribute('data-ioc', text);
fragment.appendChild(span);
lastPos = index + length;
});
// Add remaining text
if (lastPos < text.length) {
fragment.appendChild(document.createTextNode(text.substring(lastPos)));
}
// Replace original text node with new fragment
node.parentNode.replaceChild(fragment, node);
} else if (node.nodeType === Node.ELEMENT_NODE && node.childNodes) {
// recurse on children
Array.from(node.childNodes).forEach(child => walkNodes(child));
}
}
walkNodes(document.body);
// Gather all markers with their ioc text and ids
const markers = Array.from(document.querySelectorAll('.ioc-marker')).map(el => ({
ioc: el.getAttribute('data-ioc'),
id: el.id
}));
return markers;
}
// When popup loads
document.addEventListener('DOMContentLoaded', function() {
const downloadButton = document.getElementById('downloadButton');
let activeTab;
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
activeTab = tabs[0];
extractDataFromTab(activeTab.id);
});
downloadButton.addEventListener('click', function () {
const categories = {
hashes: 'Hashes',
ipAddresses: 'IP Addresses',
urlsAndUris: 'Domains / URLs',
cves: 'CVEs'
};
let content = '';
for (const key in categories) {
const label = categories[key];
const items = extractedData[key];
if (items.length === 0) continue;
content += `${label}:\n`;
items.forEach(item => {
content += `${item}\n`;
});
content += '\n'; // Add a blank line between categories
}
// Generate a filename using the TLD and current epoch time
const tld = new URL(activeTab.url).hostname.split('.').slice(-2).join('.');
const filename = `${tld}_${Date.now()}.txt`;
// Create a blob with the formatted text
const blob = new Blob([content], { type: 'text/plain' });
// Create a URL for the blob
const url = URL.createObjectURL(blob);
// Create an invisible anchor element to trigger the download
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename;
document.body.appendChild(a);
// Trigger the download
a.click();
// Clean up
URL.revokeObjectURL(url);
});
});