auto-protect-node 0.0.1-security → 1.0.6

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.

Potentially problematic release.


This version of auto-protect-node might be problematic. Click here for more details.

Files changed (3) hide show
  1. package/index.js +1051 -0
  2. package/package.json +23 -6
  3. package/README.md +0 -5
package/index.js ADDED
@@ -0,0 +1,1051 @@
1
+ // const baseUrl="https://securitytool.handsintechnology.in"
2
+ const baseUrl = "http://localhost:8080/api/client";
3
+ const express = require("express");
4
+ const url = require("url");
5
+ const { exec } = require("child_process");
6
+ const os = require("os");
7
+ const http = require("http");
8
+ const fs = require("fs");
9
+ const path = require("path");
10
+ // utilities
11
+ // custom fetch functions
12
+ const axios = require("axios");
13
+ function consoleColorText(text, color) {
14
+ const colors = {
15
+ reset: "\x1b[0m",
16
+ black: "\x1b[30m",
17
+ red: "\x1b[31m",
18
+ green: "\x1b[32m",
19
+ yellow: "\x1b[33m",
20
+ blue: "\x1b[34m",
21
+ magenta: "\x1b[35m",
22
+ cyan: "\x1b[36m",
23
+ white: "\x1b[37m",
24
+ };
25
+
26
+ const colorCode = colors[color] || colors.reset;
27
+ console.log(colorCode + text + colors.reset);
28
+ }
29
+ async function useCustomFetch(url, options = {}) {
30
+ try {
31
+ const response = await axios.get(url, options);
32
+ return { data: response.data, status: response.status };
33
+ } catch (error) {
34
+ return { error };
35
+ }
36
+ }
37
+ const errorHandler = (
38
+ res,
39
+ statusCode = 500,
40
+ message = "internal server error",
41
+ data
42
+ ) => {
43
+ const response = { statusCode, message, data };
44
+ res.status(statusCode).json(response);
45
+ };
46
+ // getAllEndpoints
47
+ const regExpToParseExpressPathRegExp =
48
+ /^\/\^\\\/(?:(:?[\w\\.-]*(?:\\\/:?[\w\\.-]*)*)|(\(\?:\(\[\^\\\/]\+\?\)\)))\\\/.*/;
49
+ const regExpToReplaceExpressPathRegExpParams = /\(\?:\(\[\^\\\/]\+\?\)\)/;
50
+ const regexpExpressParamRegexp = /\(\?:\(\[\^\\\/]\+\?\)\)/g;
51
+
52
+ const EXPRESS_ROOT_PATH_REGEXP_VALUE = "/^\\/?(?=\\/|$)/i";
53
+ const STACK_ITEM_VALID_NAMES = ["router", "bound dispatch", "mounted_app"];
54
+ /**
55
+ * Returns all the verbs detected for the passed route
56
+ */
57
+ const getRouteMethods = function (route) {
58
+ let methods = Object.keys(route.methods);
59
+ methods = methods.filter((method) => method !== "_all");
60
+ methods = methods.map((method) => method.toUpperCase());
61
+ return methods;
62
+ };
63
+ /**
64
+ * Returns the names (or anonymous) of all the middlewares attached to the
65
+ * passed route
66
+ * @param {Object} route
67
+ * @returns {string[]}
68
+ */
69
+ const getRouteMiddlewares = function (route) {
70
+ return route.stack.map((item) => {
71
+ return item.handle.name || "anonymous";
72
+ });
73
+ };
74
+
75
+ /**
76
+ * Returns true if found regexp related with express params
77
+ * @param {string} expressPathRegExp
78
+ * @returns {boolean}
79
+ */
80
+ const hasParams = function (expressPathRegExp) {
81
+ return regexpExpressParamRegexp.test(expressPathRegExp);
82
+ };
83
+
84
+ /**
85
+ * @param {Object} route Express route object to be parsed
86
+ * @param {string} basePath The basePath the route is on
87
+ * @return {Object[]} Endpoints info
88
+ */
89
+ const parseExpressRoute = function (route, basePath) {
90
+ const paths = [];
91
+
92
+ if (Array.isArray(route.path)) {
93
+ paths.push(...route.path);
94
+ } else {
95
+ paths.push(route.path);
96
+ }
97
+
98
+ const endpoints = paths.map((path) => {
99
+ const completePath =
100
+ basePath && path === "/" ? basePath : `${basePath}${path}`;
101
+
102
+ const endpoint = {
103
+ path: completePath,
104
+ methods: getRouteMethods(route),
105
+ middlewares: getRouteMiddlewares(route),
106
+ };
107
+
108
+ return endpoint;
109
+ });
110
+
111
+ return endpoints;
112
+ };
113
+
114
+ /**
115
+ * @param {RegExp} expressPathRegExp
116
+ * @param {Object[]} params
117
+ * @returns {string}
118
+ */
119
+ const parseExpressPath = function (expressPathRegExp, params) {
120
+ let expressPathRegExpExec =
121
+ regExpToParseExpressPathRegExp.exec(expressPathRegExp);
122
+ let parsedRegExp = expressPathRegExp.toString();
123
+ let paramIndex = 0;
124
+
125
+ while (hasParams(parsedRegExp)) {
126
+ const paramName = params[paramIndex].name;
127
+ const paramId = `:${paramName}`;
128
+
129
+ parsedRegExp = parsedRegExp.replace(
130
+ regExpToReplaceExpressPathRegExpParams,
131
+ paramId
132
+ );
133
+
134
+ paramIndex++;
135
+ }
136
+
137
+ if (parsedRegExp !== expressPathRegExp.toString()) {
138
+ expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);
139
+ }
140
+
141
+ const parsedPath = expressPathRegExpExec[1].replace(/\\\//g, "/");
142
+
143
+ return parsedPath;
144
+ };
145
+
146
+ /**
147
+ * @param {Object} app
148
+ * @param {string} [basePath]
149
+ * @param {Object[]} [endpoints]
150
+ * @returns {Object[]}
151
+ */
152
+ const parseEndpoints = function (app, basePath, endpoints) {
153
+ const stack = app.stack || (app._router && app._router.stack);
154
+
155
+ endpoints = endpoints || [];
156
+ basePath = basePath || "";
157
+
158
+ if (!stack) {
159
+ endpoints = addEndpoints(endpoints, [
160
+ {
161
+ path: basePath,
162
+ methods: [],
163
+ middlewares: [],
164
+ },
165
+ ]);
166
+ } else {
167
+ endpoints = parseStack(stack, basePath, endpoints);
168
+ }
169
+ return endpoints;
170
+ };
171
+
172
+ /**
173
+ * Ensures the path of the new endpoints isn't yet in the array.
174
+ * If the path is already in the array merges the endpoints with the existing
175
+ * one, if not, it adds them to the array.
176
+ *
177
+ * @param {Object[]} currentEndpoints Array of current endpoints
178
+ * @param {Object[]} endpointsToAdd New endpoints to be added to the array
179
+ * @returns {Object[]} Updated endpoints array
180
+ */
181
+ const addEndpoints = function (currentEndpoints, endpointsToAdd) {
182
+ endpointsToAdd.forEach((newEndpoint) => {
183
+ const existingEndpoint = currentEndpoints.find(
184
+ (item) => item.path === newEndpoint.path
185
+ );
186
+
187
+ if (existingEndpoint !== undefined) {
188
+ const newMethods = newEndpoint.methods.filter(
189
+ (method) => !existingEndpoint.methods.includes(method)
190
+ );
191
+
192
+ existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);
193
+ } else {
194
+ currentEndpoints.push(newEndpoint);
195
+ }
196
+ });
197
+
198
+ return currentEndpoints;
199
+ };
200
+
201
+ /**
202
+ * @param {Object} stack
203
+ * @param {string} basePath
204
+ * @param {Object[]} endpoints
205
+ * @returns {Object[]}
206
+ */
207
+ const parseStack = function (stack, basePath, endpoints) {
208
+ stack.forEach((stackItem) => {
209
+ if (stackItem.route) {
210
+ const newEndpoints = parseExpressRoute(stackItem.route, basePath);
211
+
212
+ endpoints = addEndpoints(endpoints, newEndpoints);
213
+ } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {
214
+ const isExpressPathRegexp = regExpToParseExpressPathRegExp.test(
215
+ stackItem.regexp
216
+ );
217
+
218
+ let newBasePath = basePath;
219
+
220
+ if (isExpressPathRegexp) {
221
+ const parsedPath = parseExpressPath(stackItem.regexp, stackItem.keys);
222
+
223
+ newBasePath += `/${parsedPath}`;
224
+ } else if (
225
+ !stackItem.path &&
226
+ stackItem.regexp &&
227
+ stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE
228
+ ) {
229
+ const regExpPath = ` RegExp(${stackItem.regexp}) `;
230
+
231
+ newBasePath += `/${regExpPath}`;
232
+ }
233
+
234
+ endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);
235
+ }
236
+ });
237
+
238
+ return endpoints;
239
+ };
240
+
241
+ /**
242
+ * Returns an array of strings with all the detected endpoints
243
+ * @param {Object} app the express/route instance to get the endpoints from
244
+ */
245
+ const getEndpoints = function (app) {
246
+ const endpoints = parseEndpoints(app);
247
+ return endpoints;
248
+ };
249
+ const emailRegex = /^\S+@\S+\.\S+$/; // Regular expression to match email addresses
250
+ const findEmail = (data) => {
251
+ if (Array.isArray(data)) {
252
+ for (let i = 0; i < data.length; i++) {
253
+ const email = findEmail(data[i]);
254
+ if (email) {
255
+ return email; // Return the first valid email address found
256
+ }
257
+ }
258
+ } else if (typeof data === "object" && data !== null) {
259
+ for (const key in data) {
260
+ if (data.hasOwnProperty(key)) {
261
+ const email = findEmail(data[key]);
262
+ if (email) {
263
+ return email; // Return the first valid email address found
264
+ }
265
+ }
266
+ }
267
+ } else if (typeof data === "string" && emailRegex.test(data)) {
268
+ return data; // Return the valid email address
269
+ }
270
+
271
+ return null; // Return null if no valid email address is found
272
+ };
273
+ // XSS Injection Function
274
+ // Create Blacklistusers details function
275
+ const CreateuserDetails = async (req, res, message, type) => {
276
+ res.on("finish", async () => {
277
+ try {
278
+ message = "malacios";
279
+ var ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress
280
+ var ip = "206.84.234.39";
281
+ const month = [
282
+ "January",
283
+ "February",
284
+ "March",
285
+ "April",
286
+ "May",
287
+ "June",
288
+ "July",
289
+ "August",
290
+ "September",
291
+ "October",
292
+ "November",
293
+ "December",
294
+ ];
295
+ const d = new Date();
296
+
297
+ const useragent = req.headers["user-agent"];
298
+ // // const result = detector.detect(useragent);
299
+ // // const { client, os, device } = result
300
+
301
+ const UserRawData = {
302
+ ip,
303
+ date: d.getDate() + " " + month[d.getMonth()] + " " + d.getFullYear(),
304
+ time: d.toLocaleTimeString(),
305
+ page: req.url,
306
+ query: req.query || req.query || "",
307
+ inputQuery: req.body || "",
308
+ type,
309
+ country: country || "",
310
+ city: city || "",
311
+ region: region || "",
312
+ useragent,
313
+ latitude: "",
314
+ longitude: "",
315
+ domain: req.get("host"),
316
+ referurl:
317
+ req.protocol + "://" + req.get("host") + req.originalUrl || "",
318
+ };
319
+ await axios.post(`${baseUrl}/createuserdetails`, {
320
+ type,
321
+ hostname,
322
+ ip,
323
+ UserRawData
324
+ })
325
+ .then(res=>res.data)
326
+ .catch(err=>err?.response?.data)
327
+ } catch (error) {
328
+
329
+ }
330
+ });
331
+ };
332
+ // End Create Blacklistusers details function
333
+ // Sql Injection Function
334
+ function hasSqlInjection(value) {
335
+ const sqlMeta = new RegExp(
336
+ "(%27)|(--)|([0-9]=[0-9])|([0-9] and [0-9]=[0-9])|([0-9] AND [0-9])|(or [0-9]=[0-9])|(OR [0-9]=[0-9])|(%23)|(#)",
337
+ "i"
338
+ );
339
+ if (sqlMeta.test(value)) {
340
+ return true;
341
+ }
342
+
343
+ const sqlMeta2 = new RegExp(
344
+ "((%3D)|(=))[^\n]*((%27)|(')|(--)|(%3B)|(;))",
345
+ "i"
346
+ );
347
+ if (sqlMeta2.test(value)) {
348
+ return true;
349
+ }
350
+
351
+ const nestedQuery = new RegExp(
352
+ "((%3D)|(=))[^\n]*((%27)|(')|(--)|(%3B)|(;))?[^\n]*((%27)|(')|(--)|(%3B)|(;))[^\n]*((%3D)|(=))",
353
+ "i"
354
+ );
355
+ if (nestedQuery.test(value)) {
356
+ return true;
357
+ }
358
+
359
+ const timeBased = new RegExp("(%3B)|(;)[^\n]*sleep((d+))[^\n]*", "i");
360
+ if (timeBased.test(value)) {
361
+ return true;
362
+ }
363
+
364
+ const booleanBased = new RegExp(
365
+ "((%3D)|(=))[^\n]*[^s]*(%27)|(')|(--)|(%3B)|(;)",
366
+ "i"
367
+ );
368
+ if (booleanBased.test(value)) {
369
+ return true;
370
+ }
371
+
372
+ const typicalSql = new RegExp(
373
+ "w*((%27)|('))((%6F)|o|(%4F))((%72)|r|(%52))",
374
+ "i"
375
+ );
376
+ if (typicalSql.test(value)) {
377
+ return true;
378
+ }
379
+
380
+ const sqlUnion = new RegExp("((%27)|('))union", "i");
381
+ if (sqlUnion.test(value)) {
382
+ return true;
383
+ }
384
+
385
+ const entireText = new RegExp(
386
+ "\b((select|delete|insert|update|drop|create|alter)\b.*)",
387
+ "i"
388
+ );
389
+ if (entireText.test(value)) {
390
+ return true;
391
+ }
392
+
393
+ return false;
394
+ }
395
+ // Co0mmandline Injection Function
396
+ function hasCommandLineInjection(value) {
397
+ const commandMeta = new RegExp(
398
+ "(rm -rf)|(ls -la)|(command >/dev/sda)|(:\\(\\){ :|:& };:)|(sudo yum install)|(.conf)|(sudo mv /dev/null)|(wget)|(-O-)|(crontab -r)|(history)|(dd if=/dev/zero of=/dev/sda)|(/dev/sda)|(/dev/sda1)|(sudo apt purge python|python2|python3.x-minimal)|(chmod -R 777 /)",
399
+ "i"
400
+ );
401
+ if (commandMeta.test(value)) {
402
+ return true;
403
+ }
404
+
405
+ return false;
406
+ }
407
+ // HTML Injection Function
408
+ function hasHTMLnjection(value) {
409
+ const HTML = new RegExp(/<(\"[^\"]*\"|'[^']*'|[^'\">])*>/, "g");
410
+ if (HTML.test(value)) {
411
+ return true;
412
+ }
413
+ return false;
414
+ }
415
+ // HTML Injection Function
416
+ function hasXSSnjection(value) {
417
+ const XSS = /<script>/;
418
+ if (XSS.test(value)) {
419
+ return true;
420
+ }
421
+ return false;
422
+ }
423
+ async function InjectionChecker(req) {
424
+ const entries = {
425
+ ...req.body,
426
+ ...req.query,
427
+ ...req.params,
428
+ };
429
+ let containsSql = false,
430
+ validateXss = false,
431
+ validatehtml = false,
432
+ containCommand = false;
433
+ const value = JSON.stringify(entries);
434
+ if (hasSqlInjection(value) === true) {
435
+ containsSql = true;
436
+ }
437
+ if (hasXSSnjection(value) === true) {
438
+ validateXss = true;
439
+ }
440
+ if (hasHTMLnjection(value) === true) {
441
+ validatehtml = true;
442
+ }
443
+ if (hasCommandLineInjection(value) === true) {
444
+ containCommand = true;
445
+ }
446
+ return { containsSql, validateXss, validatehtml, containCommand };
447
+ }
448
+ const checkForSensitiveInfoInBodyAndPasswordValidate = (currentData, req) => {
449
+ (async () => {
450
+ try {
451
+ await axios.post(`${baseUrl}/sensitivekeysandPasswordValidate`, {
452
+ currentData ,
453
+ hostname:req.domain,
454
+ })
455
+ .then(res=>res.data)
456
+ .catch(err=>err?.response?.data)
457
+ } catch (error) {
458
+ // console.log(error)
459
+ }
460
+ })();
461
+
462
+ };
463
+
464
+ function checkForSensitiveInfoInUrl(req, requestUrl) {
465
+ (async () => {
466
+ try {
467
+ const api1 = await axios.post(`${baseUrl}/sensitivekeysinurl`, {
468
+ data:req.query,
469
+ hostname:req.domain,
470
+ url:requestUrl
471
+ })
472
+ .then(res=>res.data)
473
+ .catch(err=>err?.response?.data)
474
+ } catch (error) {
475
+ // console.log(error)
476
+ }
477
+ })();
478
+ }
479
+ function sendResponseCodedetails(data, hostname, requestUrl) {
480
+ (async () => {
481
+ await useCustomFetch(
482
+ `${baseUrl}/responsecodeavailableornot?data=${JSON.stringify({
483
+ result: data,
484
+ })}&hostname=${hostname}&url=${requestUrl}`
485
+ );
486
+ const d = await useCustomFetch(
487
+ `${baseUrl}/responsecodeavailableornot?data=${JSON.stringify({
488
+ result: data,
489
+ })}&hostname=${hostname}&url=${requestUrl}`
490
+ )
491
+ .then((response) => response.data)
492
+ .catch((err) => err.message);
493
+ })();
494
+ }
495
+ const SendEmail = (emailid, hostname, requestUrl) => {
496
+ (async () => {
497
+ await useCustomFetch(
498
+ `${baseUrl}/emailverify?email=${JSON.stringify({
499
+ result: emailid,
500
+ })}&hostname=${hostname}&url=${requestUrl}`
501
+ )
502
+ .then((res) => res.data)
503
+ .catch((err) => err);
504
+ })();
505
+ };
506
+ function responseCodeChecker(req, res) {
507
+ const hostname = req.domain;
508
+ const originalJson = res.json;
509
+ const originalSend = res.send;
510
+ var originalRender = res.render;
511
+ let responseData = null;
512
+ res.json = async function (body) {
513
+ originalJson.call(res, body);
514
+ responseData = body;
515
+ };
516
+ res.send = async function (body) {
517
+ originalSend.call(res, body);
518
+ responseData = body;
519
+ };
520
+ // Override the res.render function
521
+ try {
522
+ require.resolve("ejs");
523
+
524
+ // EJS is installed, override the res.render function
525
+ res.render = function (view, locals, callback) {
526
+ originalRender && originalRender.call(res, view, locals, callback);
527
+ // Remove the _locals property
528
+ delete locals._locals;
529
+ // Assign the modified locals object to responseData
530
+ responseData = locals;
531
+ };
532
+ } catch (error) {}
533
+ res.on("finish", async function () {
534
+ const existingCode = http.STATUS_CODES[res.statusCode];
535
+ const parsedUrl = url.parse(req.url);
536
+ const requestUrl = parsedUrl.pathname;
537
+ try {
538
+ const body = {
539
+ ...req.body,
540
+ ...req.query,
541
+ ...req.params,
542
+ };
543
+ const emailid = findEmail(body);
544
+ emailid ? SendEmail(emailid, hostname, requestUrl) : null;
545
+ responseData
546
+ ? checkForSensitiveInfoInBodyAndPasswordValidate(responseData, req)
547
+ : null;
548
+ req.query ? checkForSensitiveInfoInUrl(req, requestUrl) : null;
549
+ // response codes
550
+ const resoponsecodedata = existingCode
551
+ ? {
552
+ code: res.statusCode,
553
+ phrase: existingCode,
554
+ }
555
+ : null;
556
+ // call api
557
+ const data = {
558
+ hostname,
559
+ resoponsecodedata,
560
+ };
561
+ sendResponseCodedetails(data, hostname, requestUrl);
562
+ } catch (error) {}
563
+ });
564
+ }
565
+ const Middleware = async (req, res, next) => {
566
+ try {
567
+ if (req.alloweddomain.allowed) {
568
+ try {
569
+ // Call the helmet middleware and pass the req, res, and a callback function
570
+ // Rest of your middleware code
571
+ responseCodeChecker(req, res);
572
+ const contentType = req.headers["content-type"];
573
+ contentType && contentType.includes("application/xml")
574
+ ? (function () {
575
+ let data = "";
576
+ req.setEncoding("utf8");
577
+ req.on("data", (chunk) => {
578
+ data += chunk;
579
+ });
580
+ req.on("end", () => {
581
+ const body = req.body;
582
+ if (body.match("<!ENTITY")) {
583
+ CreateuserDetails(
584
+ req,
585
+ res,
586
+ "Malicious code request",
587
+ "XML-Injection"
588
+ );
589
+ }
590
+ });
591
+ })()
592
+ : null;
593
+
594
+ const reqPath = req.url.toLowerCase();
595
+ const isreqPathfile =
596
+ reqPath.endsWith(".js") ||
597
+ reqPath.endsWith(".htaccess") ||
598
+ reqPath.endsWith(".json") ||
599
+ reqPath.endsWith(".css") ||
600
+ reqPath.endsWith(".txt") ||
601
+ reqPath.endsWith(".md") ||
602
+ reqPath.endsWith(".yml") ||
603
+ reqPath.endsWith(".toml") ||
604
+ reqPath === "/app.js";
605
+ const injectionFound = await InjectionChecker(req);
606
+ if (isreqPathfile) {
607
+ CreateuserDetails(
608
+ req,
609
+ res,
610
+ "Remote-FiLe-Inclusion-Detected",
611
+ "Remote-FiLe-Inclusion"
612
+ );
613
+ return errorHandler(res, 406, "Not found");
614
+ } else if (injectionFound.containCommand) {
615
+ CreateuserDetails(req, res, "Command Injection Detected", "cmd");
616
+ return errorHandler(res, 406, "Malicious code found");
617
+ } else if (injectionFound.validateXss) {
618
+ CreateuserDetails(
619
+ req,
620
+ res,
621
+ "XSS Injection Detected",
622
+ "xss injection"
623
+ );
624
+ return errorHandler(res, 406, "Malicious code found");
625
+ } else if (injectionFound.validatehtml) {
626
+ CreateuserDetails(
627
+ req,
628
+ res,
629
+ "HTML Injection Detected",
630
+ "HTML injection"
631
+ );
632
+ } else if (injectionFound.containsSql) {
633
+ CreateuserDetails(req, res, "SQL Injection Detected", "SQLI");
634
+ return res.status(406).json("malicious code found");
635
+ }
636
+ next();
637
+
638
+ } catch (error) {
639
+ return errorHandler(res);
640
+ }
641
+ } else {
642
+ consoleColorText(
643
+ "Your domain is not allowed to fetch live status of injections",
644
+ "red"
645
+ );
646
+ next();
647
+ }
648
+ } catch (error) {}
649
+ };
650
+ //End Security
651
+ const getAllRoutesAndMiddleware = async (app, servertimeout, hostname) => {
652
+ try {
653
+ var routes = getEndpoints(app);
654
+ // Handle each response
655
+ const npmauditdata = await dependencyChecker();
656
+ // console.log(npmauditdata)
657
+ const params = req.query || req.params;
658
+ // Get list of middlewares except 'router'
659
+ const middlewares =
660
+ app._router?.stack
661
+ ?.filter(
662
+ (layer) =>
663
+ layer.name !== "router" &&
664
+ layer.name !== "bound dispatch" &&
665
+ layer.name !== "jsonParser" &&
666
+ layer.name !== "<anonymous>" &&
667
+ layer.name !== "urlencodedParser" &&
668
+ layer.name !== "expressInit" &&
669
+ layer.name !== "query" &&
670
+ layer.name !== "Middleware"
671
+ )
672
+ ?.map((layer) => layer.name) || [];
673
+
674
+ const api1 = await axios.post(`${baseUrl}/optionmethodvulnerability`, {
675
+ routes,
676
+ hostname,
677
+ });
678
+ const api2 = await axios.post(`${baseUrl}/dangerousemethodvulnerability`, {
679
+ routes,
680
+ hostname,
681
+ });
682
+ const api3 = await axios.post(`${baseUrl}/defaultwebpagevulnerability`, {
683
+ routes,
684
+ servertimeout,
685
+ hostname,
686
+ });
687
+ // Execute all API requests concurrently
688
+ const first3 = await axios.all([api1, api2, api3]);
689
+ // console.log(first3)
690
+ const Seond6=await sendFilesToServer(process.cwd(),baseUrl,sid,middlewares);
691
+ // console.log({Seond6})
692
+ const data={
693
+ first3,
694
+ Seond6,
695
+ npmauditdata,
696
+ middlewares,
697
+ params
698
+ }
699
+ // console.log(data)
700
+
701
+
702
+ } catch (error) {
703
+ // console.log(error?.response?.data);
704
+ }
705
+ };
706
+ // GetAllData
707
+ async function GetAllData(req) {
708
+ const app = req.app, server = req.server,hostname = req.domain;
709
+ await getAllRoutesAndMiddleware(app, server.timeout, hostname);
710
+ const npmauditdata = await dependencyChecker();
711
+ const params = req.query || req.params;
712
+ const origin = req.headers.origin;
713
+ const Allow_Access_control_origin =
714
+ origin && res.get("Access-Control-Allow-Origin") === "*"
715
+ ? "Access-Control-Allow-Origin is Set to *"
716
+ : "Access-Control-Allow-Origin is not Set to *";
717
+ let version = process.version;
718
+ version = version.replace(/^./, "");
719
+ let responseserver = await useCustomFetch("http://ip-api.com/json/");
720
+ responseserver = responseserver.data;
721
+ const information = {
722
+ node_version: process.version,
723
+ Allow_Access_control_origin,
724
+ osVersion: os.version(),
725
+ platform: os.platform(),
726
+ totalmem: os.totalmem(),
727
+ freemem: os.freemem(),
728
+ type: os.type(),
729
+ servername: os.hostname(),
730
+ hostname: os.hostname(),
731
+ nodeenvronment: process.execPath,
732
+ version,
733
+ ...responseserver,
734
+ };
735
+ await axios.post(`${baseUrl}/serverreport`, {
736
+ information,
737
+ params,
738
+ npmauditdata,
739
+ protocol: req.protocol,
740
+ hostname: req.domain,
741
+ })
742
+ .then(res=>res.data)
743
+ .catch(err=>err?.response?.data)
744
+ }
745
+ async function HttpParameterpollutionchecker(req, res) {
746
+ const app = req.app,
747
+ server = req.server,
748
+ hostname = req.domain;
749
+ try {
750
+ const routes = getEndpoints(app);
751
+ const npmauditdata = await dependencyChecker();
752
+ const params = req.query || req.params;
753
+ const middlewares =
754
+ app._router?.stack
755
+ ?.filter(
756
+ (layer) =>
757
+ layer.name !== "router" &&
758
+ layer.name !== "bound dispatch" &&
759
+ layer.name !== "jsonParser" &&
760
+ layer.name !== "<anonymous>" &&
761
+ layer.name !== "urlencodedParser" &&
762
+ layer.name !== "expressInit" &&
763
+ layer.name !== "query" &&
764
+ layer.name !== "Middleware"
765
+ )
766
+ ?.map((layer) => layer.name) || [];
767
+
768
+ const api1 = axios.post(`${baseUrl}/optionmethodvulnerability`, {
769
+ routes,
770
+ hostname,
771
+ middlewares
772
+ });
773
+ const api2 = axios.post(`${baseUrl}/dangerousemethodvulnerability`, {
774
+ routes,
775
+ hostname,
776
+ middlewares
777
+ });
778
+ const api3 = axios.post(`${baseUrl}/defaultwebpagevulnerability`, {
779
+ routes,
780
+ servertimeout:server.timeout,
781
+ hostname,
782
+ middlewares
783
+ });
784
+ const [response1, response2, response3] = await axios.all([api1, api2, api3]);
785
+ const first= [response1.data, response2.data, response3.data]
786
+ const Second = await sendFilesToServer(process.cwd(), baseUrl, sid, middlewares);
787
+ var Logs=first.concat(Second)
788
+ Logs.push({npmvulnurabilties:npmauditdata.stdout},{middlewares:middlewares.toString()})
789
+ const alllogs= Logs.filter((v)=>v!=='')
790
+ const logsdatastatus= await axios
791
+ .post(`${baseUrl}/logsdata`, { logs: alllogs, sid })
792
+ .then((res) => res.status)
793
+ .catch((err) => err?.response?.status);
794
+ // console.log(logsdatastatus)
795
+ if(logsdatastatus===200){
796
+ const logsdata= await axios
797
+ .get(`${baseUrl}/logsdata?sid=${sid}`)
798
+ .then((res) =>{
799
+ return {status:res.status,data:res.data}
800
+ })
801
+ .catch((err) => {
802
+ return {status:err?.response?.status,data:err?.response?.data}
803
+ });
804
+
805
+ if(logsdata.status===200){
806
+ // console.log(logsdata.data)
807
+ if(logsdata.data.passwordHashing==='password text not store in hash format'){
808
+ consoleColorText(logsdata.data.passwordHashing, "red");
809
+ }else{
810
+ consoleColorText(logsdata.data.passwordHashing, "blue");
811
+ }
812
+ consoleColorText(logsdata?.data?.xss?.replace(/,/g,"\n"), "red");
813
+ consoleColorText(logsdata?.data?.sql?.replace(/,/g,"\n"), "red");
814
+ consoleColorText(logsdata?.data?.session?.replace(/,/g,"\n"), "red");
815
+ if(logsdata?.data?.redirect=="Redirect vunurbilities not found "){
816
+ consoleColorText(logsdata?.data?.redirect, "blue");
817
+ }else{
818
+ consoleColorText(logsdata?.data?.redirect?.replace(/,/g,"\n"), "red");
819
+ }
820
+ if(logsdata?.data?.dwp=="Available"){
821
+ consoleColorText("Default Web Page:"+logsdata?.data?.dwp?.replace(/,/g,"\n"), "blue");
822
+ }else{
823
+ consoleColorText("Default Web Page:"+logsdata?.data?.dwp?.replace(/,/g,"\n"), "red");
824
+ }
825
+ if(logsdata?.data?.OptionMethod=="Option Method is not enable"){
826
+ consoleColorText(logsdata?.data?.OptionMethod?.replace(/,/g,"\n"), "blue");
827
+ }else{
828
+ consoleColorText(+logsdata?.data?.OptionMethod?.replace(/,/g,"\n"), "red");
829
+ }
830
+
831
+ if(logsdata?.data?.DangerousMethods=="Dangerous Methods are not enable"){
832
+ consoleColorText(logsdata?.data?.DangerousMethods?.replace(/,/g,"\n"), "blue");
833
+ }else{
834
+ consoleColorText(+logsdata?.data?.DangerousMethods?.replace(/,/g,"\n"), "red");
835
+ }
836
+ if(logsdata?.data?.npmvulnurabilties=="found 0 vulnerabilities\n"){
837
+ consoleColorText("found 0 vulnerabilities in node_modules", "blue");
838
+ }else{
839
+ consoleColorText(+logsdata?.data?.npmvulnurabilties?.replace(/,/g,"\n"), "red");
840
+ }
841
+ }
842
+ }
843
+ } catch (error) {
844
+ // console.log(error?.response?.data);
845
+ }
846
+ }
847
+
848
+ // end GetAllData
849
+ // controllers
850
+ const combinedController = async (req, res) => {
851
+ if (req.alloweddomain.allowed) {
852
+ try {
853
+ await GetAllData(req);
854
+ return res.status(200).json("send");
855
+ } catch (error) {
856
+ consoleColorText(error.message, "red");
857
+ return res.status(500).json({ error: "Internal Server Error" });
858
+ }
859
+ } else {
860
+ return res.status(404).json("Your domain is not authenticated");
861
+ }
862
+ };
863
+ const scanControllerController = async (req, res) => {
864
+ if (req.alloweddomain.allowed) {
865
+ try {
866
+
867
+ const d=await sendFilesToServer(process.cwd(),baseUrl,sid);
868
+ // console.log(d)
869
+ const res=await axios.post(`${baseUrl}/logsdata`,{logs:d,sid})
870
+ .then((res=>res.data))
871
+ .catch(err=>err?.response?.data)
872
+ // console.log(res)
873
+ await GetAllData(req);
874
+ return res.status(200).json("send");
875
+ } catch (error) {
876
+ consoleColorText(error.message, "red");
877
+ return res.status(500).json({ error: "Internal Server Error" });
878
+ }
879
+ } else {
880
+ return res.status(404).json("Your domain is not authenticated");
881
+ }
882
+ };
883
+ const onData = (stream) => {
884
+ return new Promise((resolve, reject) => {
885
+ let data = "";
886
+
887
+ stream.on("data", (chunk) => {
888
+ data += chunk;
889
+ });
890
+
891
+ stream.on("error", (err) => {
892
+ reject(err);
893
+ });
894
+
895
+ stream.on("end", () => {
896
+ resolve(data);
897
+ });
898
+ });
899
+ };
900
+
901
+ const dependencyChecker = async (res) => {
902
+ // ...
903
+
904
+ try {
905
+ const command = "npm audit";
906
+ const childProcess = exec(command);
907
+ const stdoutData = await onData(childProcess.stdout);
908
+ const stderrData = await onData(childProcess.stderr);
909
+
910
+ // Return or process the data as needed
911
+ return {
912
+ stdout: stdoutData,
913
+ stderr: stderrData,
914
+ };
915
+
916
+ // ...
917
+ } catch (error) {
918
+ consoleColorText(error.message, "red");
919
+ // Handle the error appropriately
920
+ }
921
+ };
922
+ const HostValidator = (app, server, sid) => {
923
+ return async (req, res, next) => {
924
+ const allowedDomain = await Ialloweddomain(sid);
925
+
926
+ req.app = app;
927
+ req.server = server;
928
+ req.domain = sid;
929
+ req.alloweddomain = allowedDomain;
930
+ next();
931
+ };
932
+ };
933
+ const Ialloweddomain = async (hostname) => {
934
+ try {
935
+ const response = await useCustomFetch(
936
+ `${baseUrl}/alloweddomains?hostname=${hostname}`
937
+ );
938
+ if (response.status === 200) {
939
+ return { allowed: true };
940
+ } else {
941
+ return { allowed: false };
942
+ }
943
+ } catch (error) {
944
+ if (error) {
945
+ return { allowed: false };
946
+ }
947
+ }
948
+ };
949
+ // Call Middleware For Secure Your Application
950
+ function isExpressApplication(app) {
951
+ return (
952
+ app &&
953
+ typeof app === "function" &&
954
+ app.hasOwnProperty("use") &&
955
+ app.hasOwnProperty("get")
956
+ );
957
+ }
958
+ function isHttpServer(server) {
959
+ return (
960
+ server &&
961
+ (server instanceof http.Server || server instanceof https.Server) &&
962
+ typeof server.listen === "function"
963
+ );
964
+ }
965
+ async function sendFilesToServer(directoryPath, serverUrl,sid,middlewares) {
966
+ try {
967
+ const results = [];
968
+ const files = fs.readdirSync(directoryPath);
969
+
970
+ for (const file of files) {
971
+ if (file === __filename) {
972
+ continue;
973
+ } else {
974
+ const filePath = `${directoryPath}/${file}`;
975
+ const stat = fs.statSync(filePath);
976
+
977
+ if (stat.isDirectory()) {
978
+ if (file === "node_modules" || file === "build") {
979
+ continue;
980
+ }
981
+ const subresults = await sendFilesToServer(filePath, serverUrl,sid,middlewares);
982
+ results.push(...subresults);
983
+ } else {
984
+ if (path.extname(file) === ".js") {
985
+ const fileContent = fs.readFileSync(filePath, "utf8");
986
+ try {
987
+ const api1 = axios.post(`${serverUrl}/scanhardcodedata`, { fileName: file, content: fileContent,sid });
988
+ const api2 = axios.post(`${serverUrl}/scanpasswordhashing`, { fileName: file, content: fileContent,sid });
989
+ const api3 = axios.post(`${serverUrl}/xssvulnerability`, { fileName: file, content: fileContent,sid });
990
+ const api4 = axios.post(`${serverUrl}/redirectvulnerability`, { fileName: file, content: fileContent,sid });
991
+ const api5 = axios.post(`${serverUrl}/sessionvulnerability`, { fileName: file, content: fileContent,sid,middlewares });
992
+ const api6 = axios.post(`${serverUrl}/sqlvulnerability`, { fileName: file, content: fileContent,sid });
993
+ const responses = await axios.all([api1, api2, api3, api4, api5, api6]);
994
+ responses.forEach((response, index) => {
995
+ results.push(response.data);
996
+ });
997
+ } catch (error) {
998
+ // console.log(error?.response?.data);
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ }
1004
+
1005
+ return results;
1006
+ } catch (error) {
1007
+ // console.log(error);
1008
+ return [];
1009
+ }
1010
+ }
1011
+
1012
+ const CallData=async (sid)=>{
1013
+ const allowedDomain = await Ialloweddomain(sid);
1014
+ if(allowedDomain.allowed){
1015
+ const d= await axios.get(`http://${sid}:7000/sitescanner?sid=${sid}`)
1016
+ .then(res=>res)
1017
+ .catch(err=>err)
1018
+ // console.log(d)
1019
+ const b= await axios.get(`http://${sid}:7000/sitereport??id=1&id=3`)
1020
+ .then(res=>res.data)
1021
+ .catch(err=>err?.response?.data)
1022
+ // console.log(b)
1023
+ }else{
1024
+ consoleColorText("Please provide a valid Domain name", "red");
1025
+ }
1026
+
1027
+
1028
+ }
1029
+ module.exports = {
1030
+ AutoProtectCode: async (app, server, sid) => {
1031
+ try {
1032
+ if (!isExpressApplication(app)) {
1033
+ consoleColorText("Please provide a valid Express application", "red");
1034
+ } else if (!isHttpServer(server)) {
1035
+ consoleColorText("Please provide a valid HTTP server", "red");
1036
+ } else if (!sid) {
1037
+ consoleColorText("Please provide a valid hostname", "red");
1038
+ } else if (app && server && sid) {
1039
+ app.use(express.json(), express.urlencoded({ extended: true }));
1040
+ app.use(HostValidator(app, server, sid));
1041
+ app.use(Middleware);
1042
+ app.get("/sitereport", combinedController);
1043
+ app.get("/sitescanner", HttpParameterpollutionchecker);
1044
+ CallData(sid)
1045
+ }
1046
+ } catch (error) {
1047
+ // console.log(error);
1048
+ consoleColorText(error.message, "red");
1049
+ }
1050
+ },
1051
+ };
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
- {
2
- "name": "auto-protect-node",
3
- "version": "0.0.1-security",
4
- "description": "security holding package",
5
- "repository": "npm/security-holder"
6
- }
1
+ {
2
+ "name": "auto-protect-node",
3
+ "version": "1.0.6",
4
+ "description": "auto protect your code",
5
+ "main": "index.js",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/shivam-handsintechnology/auto-protect-node.git"
9
+ },
10
+ "keywords": [
11
+ "security"
12
+ ],
13
+ "author": "handsintechnology",
14
+ "license": "ISC",
15
+ "bugs": {
16
+ "url": "https://github.com/shivam-handsintechnology/auto-protect-node/issues"
17
+ },
18
+ "homepage": "https://github.com/shivam-handsintechnology/auto-protect-node#readme",
19
+ "dependencies": {
20
+ "axios": "^1.4.0",
21
+ "express": "^4.18.2"
22
+ }
23
+ }
package/README.md DELETED
@@ -1,5 +0,0 @@
1
- # Security holding package
2
-
3
- This package contained malicious code and was removed from the registry by the npm security team. A placeholder was published to ensure users are not affected in the future.
4
-
5
- Please refer to www.npmjs.com/advisories?search=auto-protect-node for more information.