-
Notifications
You must be signed in to change notification settings - Fork 3
/
hounds.js
336 lines (308 loc) · 10.8 KB
/
hounds.js
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
#!/usr/bin/env node
const yargs = require('yargs/yargs');
const {hideBin} = require('yargs/helpers');
const puppeteer = require('puppeteer-extra');
const normalizeUrl = import("normalize-url");
var validUrl = require("valid-url");
var url = require("url");
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
const badHandlers = ["javascript:", "tel:", "mailto:"];
const argv = yargs(hideBin(process.argv))
.option('url', {
alias: 'u',
type: 'string',
description: 'Site to crawl'
})
.option('scope', {
alias: 's',
type: 'string',
description: 'Allowed scope (Ex: example.com)'
})
.option('proxy', {
alias: 'p',
type: 'string',
description: 'Proxy (Ex: proto://IP:port => http://127.0.0.1:8080)'
})
.option('full', {
alias: 'f',
type: 'boolean',
description: 'Full HTTP requests in JSON format (default: false)'
})
.option('robots', {
alias: 'r',
type: 'boolean',
description: 'Flag to scan robots.txt'
})
.demandOption(['url', 'scope'], 'Include both the url and scope parameters')
.help()
.argv
let scope = argv.scope;
let proxy = argv.proxy;
let fullMode = argv.full;
let robots = argv.robots;
let visitedUrls = [];
let urlsToVisit = [];
let hashCodes = [];
let browser;
async function run() {
while (urlsToVisit.length != 0) {
var mainUrl = urlsToVisit.shift();
var old_pages;
var page;
try {
old_pages = await browser.pages().catch(function() {});
if (old_pages.length != 0) {
page = old_pages[0];
} else {
page = await browser.newPage();
await page.setViewport({
width: 1920,
height: 1040
});
}
} catch (err) {
console.error(err.message);
}
if (visitedUrls.includes(mainUrl)) {
run();
return;
}
try {
if (!url.parse(mainUrl).hostname.endsWith(scope)) {
return;
}
} catch (err) {
await run();
return;
}
if (!validUrl.isUri(mainUrl)) {
await run();
return;
}
var cookies = await page.cookies();
try {
await page.setRequestInterception(true);
let requrl = "";
page.on("request", (request) => {
requrl = request.url();
if (url.parse(requrl).hostname.endsWith(scope)) {
if (fullMode){
const result = formatRequest(request, cookies);
const hash = hashRequest(request);
if (!visitedUrls.includes(hash)) {
console.log(result);
visitedUrls.push(hash);
}
} else {
if (!visitedUrls.includes(requrl)) {
console.log(requrl);
visitedUrls.push(requrl);
}
}
}
request.continue().catch(function() {});
});
page.on("response", (response) => {
const request = response.request();
const respurl = request.url();
if (respurl != requrl && url.parse(respurl).hostname.endsWith(scope)) {
if (fullMode){
const result = formatRequest(request);
const hash = hashRequest(request);
if (!visitedUrls.includes(hash)) {
console.log(result);
visitedUrls.push(hash);
}
} else {
if (!visitedUrls.includes(respurl)) {
console.log(respurl);
visitedUrls.push(respurl);
}
}
if (response.status() == 301 || response.status() == 302) {
if (response.headers().location) {
var location = response.headers().location;
parseElems([location], mainUrl);
}
}
}
});
await page.goto(mainUrl, {
waitUntil: "networkidle2",
});
visitedUrls.push(mainUrl);
var elems = await page.evaluate(() =>
Array.from(document.querySelectorAll("a[href]"), (a) =>
a.getAttribute("href")
)
);
if (robots && elems.length == 0 && mainUrl.includes('/robots.txt')){
const element = await page.waitForSelector('pre');
const value = await element.evaluate(el => el.textContent);
getRobots(value, argv.url)
}
parseElems(elems, mainUrl);
// Try to click submit on any form. Only do this once per form to prevent getting stuck in spammy loops
var prev_hash_count = hashCodes.length;
hashCodes = await page.evaluate((hashCodes) => {
var get_string = (el) => el.outerHTML;
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) {
return hash;
}
for (var i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
};
var forms = document.getElementsByTagName("FORM");
for (var i = 0; i < forms.length; i++) {
var hash = get_string(forms[i]).hashCode();
if (!hashCodes.includes(hash)) {
hashCodes.push(hash);
forms[i].submit();
}
}
return hashCodes;
}, hashCodes);
var curr_hash_count = hashCodes.length;
// If we clicked on a new form, then we should analyze the current DOM to see if we were redirected or if new links were added.
if (curr_hash_count > prev_hash_count) {
elems = await page.evaluate(() =>
Array.from(document.querySelectorAll("a[href]"), (a) =>
a.getAttribute("href")
)
);
parseElems(elems, mainUrl);
}
} catch (err) {
// console.error(err.message);
}
if (urlsToVisit.length == 0) {
await browser.close();
return;
}
}
}
function parseElems(elems, mainUrl) {
for (var e in elems) {
if (elems[e].startsWith("http")) {
let normal_u = normalizeUrl(elems[e]);
if (validUrl.isUri(normal_u)) {
if (
url.parse(normal_u).hostname.endsWith(scope) &&
!visitedUrls.includes(normal_u) &&
!urlsToVisit.includes(normal_u)
) {
urlsToVisit.push(normal_u);
}
}
} else {
if (!badHandlers.some(h => elems[e].startsWith(h))){
try {
let parsedUrl = url.parse(mainUrl);
let path = parsedUrl.pathname
// Location: /app/foo.html
if (elems[e].startsWith("/")) {
path = "";
} else {
if (!path.endsWith("/")) {
path += "/";
}
}
let u = parsedUrl.protocol + "//" + parsedUrl.host + path + elems[e];
let normal_u = normalizeUrl(u, {removeTrailingSlash: false});
if (validUrl.isUri(normal_u)) {
if (
url.parse(normal_u).hostname.endsWith(scope) &&
!visitedUrls.includes(normal_u) &&
!urlsToVisit.includes(normal_u)
) {
urlsToVisit.push(normal_u);
}
}
} catch (err) {
// console.error(err);
}
}
}
}
}
function getRobots(robotText, mainUrl) {
var entries = robotText.split("\n").filter((line) => line.startsWith("Disallow:") || line.startsWith("Allow:"));
for (var i = 0; i < entries.length; i++){
var e = entries[i].split(": ")[1];
urlsToVisit.push(mainUrl + e);
}
}
function formatRequest(request, cookies) {
var result = {};
var headers = request.headers();
if (typeof(cookies) != 'undefined') {
var cookieStr = "";
for (var i = 0; i < cookies.length; i++){
var key = cookies[i]["name"];
var value = cookies[i]["value"];
cookieStr += key + "=" + value + ";";
}
if (cookieStr.length != 0){
headers['Cookie'] = cookieStr;
}
}
if (typeof(request.postData()) === 'undefined') {
result = {
Method: request.method(),
Url: request.url(),
Headers: headers,
};
} else {
headers['Content-Length'] = String(request.postData().length);
result = {
Method: request.method(),
Url: request.url(),
Headers: headers,
Body: request.postData(),
};
}
return JSON.stringify(result)
}
function hashRequest(request) {
var result = {};
if (typeof(request.postData()) === 'undefined') {
result = {
Method: request.method(),
Url: request.url(),
};
} else {
result = {
Method: request.method(),
Url: request.url(),
Body: request.postData(),
};
}
return JSON.stringify(result)
}
start(argv.url, proxy);
async function start(mainUrl) {
let args = [
"--window-size=1920,1040",
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36"
]
if (proxy) {
args.push("--proxy-server=" + proxy)
}
browser = await puppeteer.launch({
executablePath: require('puppeteer').executablePath(),
ignoreHTTPSErrors: true,
args: args
});
if (robots) {
urlsToVisit.push(mainUrl + '/robots.txt');
}
urlsToVisit.push(mainUrl);
run();
}