-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2684 lines (2350 loc) · 76.8 KB
/
app.js
File metadata and controls
2684 lines (2350 loc) · 76.8 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const { exec, spawn } = require('child_process');
const fs = require('fs');
const https = require('https');
const crypto = require('crypto');
const path = require('path');
const vm = require('vm');
const net = require('net');
const dns = require('dns');
const os = require('os');
const serialize = require('node-serialize');
const app = express();
const PORT = process.env.PORT || 3000;
// ⚠️ CWE-798: Hardcoded credentials vulnerability
const DB_PASSWORD = 'admin123';
const API_SECRET = 'secret-key-12345';
// Middleware
// making change 1 to trigger the code QA scan
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
//test 11
// Routes
app.get('/', (req, res) => {
res.send(`
<html>
<head>
<title>Express App</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 { color: #333; }
.endpoints {
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>🚀 Express Server is Running!</h1>
<p>Welcome to your Node.js Express application.</p>
<div class="endpoints">
<h3>Available Endpoints:</h3>
<ul>
<li><strong>GET /</strong> - This home page</li>
<li><strong>GET /api/hello</strong> - Simple API endpoint</li>
<li><strong>POST /api/echo</strong> - Echo back JSON data</li>
</ul>
</div>
</div>
</body>
</html>
`);
});
app.get('/user', (req, res) => {
const userId = req.query.id;
// ⚠️ CWE-89: SQL Injection vulnerability - CodeQL should detect this
const query = `SELECT * FROM users WHERE id = ${userId}`;
res.send(`Query would execute: ${query}`);
});
app.post('/update-config', (req, res) => {
const config = {};
// ⚠️ CWE-1321: Prototype Pollution vulnerability - CodeQL should detect this
const key = req.body.key;
const value = req.body.value;
config[key] = value;
res.json({ message: 'Config updated', config });
});
app.get('/search', (req, res) => {
const searchTerm = req.query.q;
// ⚠️ CWE-79: Reflected XSS vulnerability
res.send(`<h1>Search Results for: ${searchTerm}</h1>`);
});
app.get('/ping', (req, res) => {
const host = req.query.host;
// ⚠️ CWE-78: Command Injection vulnerability
exec(`ping ${host}`, (error, stdout, stderr) => {
if (error) {
res.send(`Error: ${error.message}`);
return;
}
res.send(`<pre>${stdout}</pre>`);
});
});
// CWE-20: Incomplete hostname regexp
app.get('/validate-host', (req, res) => {
const host = req.query.host;
// ⚠️ CWE-20: js/incomplete-hostname-regexp - Incomplete regular expression for hostnames
const hostRegex = /^https?:\/\/[a-z0-9]+\.example\.com/;
if (hostRegex.test(host)) {
res.json({ valid: true, message: 'Valid hostname' });
} else {
res.json({ valid: false, message: 'Invalid hostname' });
}
});
// CWE-20: Incomplete URL scheme check
app.get('/check-url', (req, res) => {
const url = req.query.url;
// ⚠️ CWE-20: js/incomplete-url-scheme-check - Incomplete URL scheme check
if (url.startsWith('https://') || url.startsWith('http://')) {
https.get(url, (response) => {
res.json({ message: 'URL checked', status: response.statusCode });
});
}
});
// CWE-20: Incomplete URL substring sanitization
app.post('/sanitize-url', (req, res) => {
let url = req.body.url;
// ⚠️ CWE-20: js/incomplete-url-substring-sanitization
url = url.replace('javascript:', '');
res.send(`<a href="${url}">Click here</a>`);
});
// CWE-20: Incorrect suffix check
app.get('/check-file', (req, res) => {
const filename = req.query.filename;
// ⚠️ CWE-20: js/incorrect-suffix-check
if (filename.indexOf('.txt') !== -1) {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading file');
} else {
res.send(data);
}
});
}
});
// CWE-20: Missing origin check in postMessage
app.get('/postmessage-page', (req, res) => {
// ⚠️ CWE-20: js/missing-origin-check
res.send(`
<script>
window.addEventListener('message', function(event) {
// Missing origin verification
document.getElementById('result').innerHTML = event.data;
});
</script>
<div id="result"></div>
`);
});
// CWE-20: Missing regexp anchor
app.get('/validate-input', (req, res) => {
const input = req.query.input;
// ⚠️ CWE-20: js/regex/missing-regexp-anchor - Missing regular expression anchor
const pattern = /[0-9]+/;
if (pattern.test(input)) {
res.json({ valid: true });
} else {
res.json({ valid: false });
}
});
// CWE-20: Overly permissive regex range
app.get('/check-alpha', (req, res) => {
const text = req.query.text;
// ⚠️ CWE-20: js/overly-large-range - Overly permissive regular expression range
const alphaRegex = /^[A-z]+$/;
res.json({ isAlpha: alphaRegex.test(text) });
});
// CWE-20: Bad HTML filtering regexp
app.post('/filter-html', (req, res) => {
let html = req.body.html;
// ⚠️ CWE-20: js/bad-tag-filter - Bad HTML filtering regexp
html = html.replace(/<script[^>]*>.*<\/script>/gi, '');
res.send(html);
});
// CWE-20: Double escaping
app.get('/escape-data', (req, res) => {
let data = req.query.data;
// ⚠️ CWE-20: js/double-escaping - Double escaping or unescaping
data = decodeURIComponent(decodeURIComponent(data));
res.send(data);
});
// CWE-20: Incomplete HTML attribute sanitization
app.post('/sanitize-attr', (req, res) => {
let attr = req.body.attr;
// ⚠️ CWE-20: js/incomplete-html-attribute-sanitization
attr = attr.replace(/"/g, '');
res.send(`<div data-value="${attr}">Content</div>`);
});
// CWE-20: Incomplete multi-character sanitization
app.post('/clean-input', (req, res) => {
let input = req.body.input;
// ⚠️ CWE-20: js/incomplete-multi-character-sanitization
input = input.replace('../', '');
res.json({ cleaned: input });
});
// CWE-20: Incomplete string escaping
app.get('/escape-string', (req, res) => {
let str = req.query.str;
// ⚠️ CWE-20: js/incomplete-sanitization - Incomplete string escaping or encoding
str = str.replace(/'/g, "\\'");
res.send(`<script>var data = '${str}';</script>`);
});
// CWE-22/CWE-23: Path injection
app.get('/read-file', (req, res) => {
const filename = req.query.file;
// ⚠️ CWE-22/CWE-23: js/path-injection - Uncontrolled data used in path expression
const filePath = path.join(__dirname, 'uploads', filename);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error');
} else {
res.send(data);
}
});
});
// CWE-73: Template Object Injection
app.get('/render-template', (req, res) => {
const data = {};
const key = req.query.key;
// ⚠️ CWE-73: js/template-object-injection - Template Object Injection
const value = data[key];
res.json({ value });
});
// CWE-74: Disabling Electron webSecurity
app.get('/electron-config', (req, res) => {
// ⚠️ CWE-74: js/disabling-electron-websecurity
const electronConfig = {
webPreferences: {
webSecurity: false,
nodeIntegration: true
}
};
res.json(electronConfig);
});
// CWE-74: Enabling Node.js integration for Electron
app.get('/electron-node', (req, res) => {
// ⚠️ CWE-74: js/enabling-electron-renderer-node-integration
const config = {
webPreferences: {
nodeIntegration: true
}
};
res.json(config);
});
// CWE-77/CWE-78: Indirect command line injection
app.post('/indirect-exec', (req, res) => {
const command = req.body.command;
const args = req.body.args;
// ⚠️ CWE-77/CWE-78: js/indirect-command-line-injection
spawn(command, args.split(' '));
res.json({ message: 'Command executed' });
});
// CWE-78: Second order command injection
app.post('/save-command', (req, res) => {
const cmd = req.body.cmd;
// ⚠️ CWE-78: js/second-order-command-line-injection
fs.writeFileSync('command.txt', cmd);
res.json({ saved: true });
});
app.get('/run-saved', (req, res) => {
const cmd = fs.readFileSync('command.txt', 'utf8');
exec(cmd, (err, stdout) => {
res.send(stdout);
});
});
// CWE-78: Shell command from environment
app.get('/env-exec', (req, res) => {
// ⚠️ CWE-78: js/shell-command-injection-from-environment
const cmd = process.env.USER_COMMAND || 'ls';
exec(cmd, (err, stdout) => {
res.send(stdout);
});
});
// CWE-78: Unsafe shell command from library input
app.post('/library-exec', (req, res) => {
const input = req.body.input;
// ⚠️ CWE-78: js/shell-command-constructed-from-input
exec(`echo ${input}`, (err, stdout) => {
res.send(stdout);
});
});
// CWE-78: Unnecessary use of cat
app.get('/cat-file', (req, res) => {
const file = req.query.file;
// ⚠️ CWE-78: js/unnecessary-use-of-cat
exec(`cat ${file}`, (err, stdout) => {
res.send(stdout);
});
});
// CWE-79: XSS through exception
app.get('/error-page', (req, res) => {
try {
const data = JSON.parse(req.query.json);
res.json(data);
} catch (e) {
// ⚠️ CWE-79: js/xss-through-exception - Exception text reinterpreted as HTML
res.send(`<h1>Error: ${e.message}</h1>`);
}
});
// CWE-79: Reflected XSS
app.get('/reflect', (req, res) => {
const name = req.query.name;
// ⚠️ CWE-79: js/reflected-xss - Reflected cross-site scripting
res.send(`<h1>Hello ${name}</h1>`);
});
// CWE-79: Stored XSS
const comments = [];
app.post('/add-comment', (req, res) => {
const comment = req.body.comment;
// ⚠️ CWE-79: js/stored-xss - Stored cross-site scripting
comments.push(comment);
res.json({ success: true });
});
app.get('/comments', (req, res) => {
let html = '<h1>Comments</h1>';
comments.forEach(c => {
html += `<p>${c}</p>`;
});
res.send(html);
});
// CWE-79: Unsafe HTML constructed from input
app.post('/create-html', (req, res) => {
const content = req.body.content;
// ⚠️ CWE-79: js/html-constructed-from-input
const html = `<div>${content}</div>`;
res.send(html);
});
// CWE-79: Client-side XSS
app.get('/client-xss', (req, res) => {
// ⚠️ CWE-79: js/xss - Client-side cross-site scripting
res.send(`
<script>
const params = new URLSearchParams(window.location.search);
document.write(params.get('msg'));
</script>
`);
});
// CWE-79: DOM XSS
app.get('/dom-xss', (req, res) => {
// ⚠️ CWE-79: js/xss-through-dom - DOM text reinterpreted as HTML
res.send(`
<script>
const hash = window.location.hash.substring(1);
document.getElementById('content').innerHTML = hash;
</script>
<div id="content"></div>
`);
});
// CWE-79: Bad code sanitization
app.post('/sanitize-code', (req, res) => {
let code = req.body.code;
// ⚠️ CWE-79: js/bad-code-sanitization - Improper code sanitization
code = code.replace(/eval/g, '');
res.send(`<script>${code}</script>`);
});
// CWE-79: Unsafe code construction
app.post('/build-code', (req, res) => {
const userFunc = req.body.func;
// ⚠️ CWE-79: js/unsafe-code-construction
const code = `function run() { ${userFunc} }`;
res.json({ code });
});
// CWE-79: Unsafe HTML expansion
app.post('/expand-html', (req, res) => {
let html = req.body.html;
// ⚠️ CWE-79: js/unsafe-html-expansion - Unsafe expansion of self-closing HTML tag
html = html.replace(/<(\w+)\/>/, '<$1></$1>');
res.send(html);
});
// CWE-89: SQL Injection
app.get('/query-user', (req, res) => {
const username = req.query.username;
// ⚠️ CWE-89: js/sql-injection - Database query built from user-controlled sources
const query = `SELECT * FROM users WHERE username = '${username}'`;
res.json({ query });
});
// CWE-90: LDAP Injection (simulated)
app.get('/ldap-search', (req, res) => {
const filter = req.query.filter;
// ⚠️ CWE-90: js/sql-injection (LDAP query pattern)
const ldapQuery = `(uid=${filter})`;
res.json({ ldapQuery });
});
// CWE-91: XPath Injection
app.get('/xpath-query', (req, res) => {
const user = req.query.user;
// ⚠️ CWE-91: js/xpath-injection - XPath injection
const xpath = `//user[@name='${user}']`;
res.json({ xpath });
});
// CWE-93: CRLF Injection
app.get('/set-header', (req, res) => {
const value = req.query.value;
// ⚠️ CWE-93: CRLF injection through header
res.setHeader('X-Custom', value);
res.send('Header set');
});
// CWE-94: Code injection with eval
app.post('/eval-code', (req, res) => {
const code = req.body.code;
// ⚠️ CWE-94/CWE-95: js/code-injection - Code injection
const result = eval(code);
res.json({ result });
});
// CWE-94: Code injection with Function constructor
app.post('/function-inject', (req, res) => {
const code = req.body.code;
// ⚠️ CWE-94: js/code-injection
const fn = new Function('x', code);
res.json({ created: true });
});
// CWE-94: Code injection with vm
app.post('/vm-run', (req, res) => {
const code = req.body.code;
// ⚠️ CWE-94: js/code-injection
const result = vm.runInThisContext(code);
res.json({ result });
});
// CWE-94: Unsafe dynamic method access
app.get('/dynamic-method', (req, res) => {
const method = req.query.method;
const obj = { safe: () => 'safe', admin: () => 'admin' };
// ⚠️ CWE-94: js/unsafe-dynamic-method-access
const result = obj[method]();
res.json({ result });
});
// CWE-94: Code injection from dynamic import
app.get('/dynamic-import', (req, res) => {
const module = req.query.module;
// ⚠️ CWE-94: js/code-injection-dynamic-import
import(module).then(mod => {
res.json({ loaded: true });
}).catch(err => {
res.status(500).json({ error: err.message });
});
});
// CWE-94: Environment variable injection
app.post('/set-env', (req, res) => {
const key = req.body.key;
const value = req.body.value;
// ⚠️ CWE-94: js/env-key-and-value-injection
process.env[key] = value;
res.json({ set: true });
});
// CWE-94: Environment value injection
app.post('/set-env-value', (req, res) => {
const value = req.body.value;
// ⚠️ CWE-94: js/env-value-injection
process.env.USER_DATA = value;
res.json({ set: true });
});
// CWE-116: Identity replacement
app.post('/replace-text', (req, res) => {
let text = req.body.text;
// ⚠️ CWE-116: js/identity-replacement - Replacement of a substring with itself
text = text.replace('bad', 'bad');
res.json({ text });
});
// CWE-117: Log injection
app.get('/log-user', (req, res) => {
const username = req.query.username;
// ⚠️ CWE-117: js/log-injection - Log injection
console.log(`User logged in: ${username}`);
res.json({ logged: true });
});
// CWE-134: Format string injection
app.get('/format-string', (req, res) => {
const format = req.query.format;
const value = req.query.value;
// ⚠️ CWE-134: js/tainted-format-string
const result = format.replace('%s', value);
res.send(result);
});
// CWE-178: Case-sensitive middleware path
app.get('/Admin/panel', (req, res) => {
// ⚠️ CWE-178: js/case-sensitive-middleware-path
res.send('Admin panel');
});
app.get('/admin/panel', (req, res) => {
res.send('Should be the same');
});
// CWE-183: Insecure URL whitelist (Angular-style)
app.get('/angular-url', (req, res) => {
const url = req.query.url;
// ⚠️ CWE-183: js/angular/insecure-url-whitelist
const whitelist = ['http://example.com', 'http://safe.com'];
const regex = /^https?:\/\/example\.com/;
if (regex.test(url)) {
res.json({ safe: true });
}
});
// CWE-183: CORS misconfiguration for credentials
app.get('/cors-creds', (req, res) => {
const origin = req.headers.origin;
// ⚠️ CWE-183: js/cors-misconfiguration-for-credentials
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.json({ data: 'sensitive' });
});
// CWE-183: Permissive CORS configuration
app.get('/cors-permissive', (req, res) => {
// ⚠️ CWE-183: js/cors-permissive-configuration
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.json({ data: 'public' });
});
// CWE-193: Index out of bounds
app.get('/array-access', (req, res) => {
const arr = [1, 2, 3];
const index = parseInt(req.query.index);
// ⚠️ CWE-193: js/index-out-of-bounds - Off-by-one comparison against length
if (index < arr.length + 1) {
res.json({ value: arr[index] });
}
});
// CWE-197: Shift out of range
app.get('/bit-shift', (req, res) => {
const value = parseInt(req.query.value);
const shift = parseInt(req.query.shift);
// ⚠️ CWE-197: js/shift-out-of-range
const result = value << shift;
res.json({ result });
});
// CWE-200: Unsafe external link
app.get('/external-link', (req, res) => {
const url = req.query.url;
// ⚠️ CWE-200: js/unsafe-external-link
res.send(`<a href="${url}" target="_blank">External Link</a>`);
});
// CWE-200: File data in outbound request
app.get('/send-file-data', (req, res) => {
const file = req.query.file;
// ⚠️ CWE-200: js/file-access-to-http
fs.readFile(file, 'utf8', (err, data) => {
if (!err) {
https.get(`https://example.com/api?data=${data}`);
}
});
res.json({ sent: true });
});
// CWE-200: Exposure of private files
app.use('/private', express.static('private'));
// ⚠️ CWE-200: js/exposure-of-private-files
// CWE-200: Cross-window information leak
app.get('/cross-window', (req, res) => {
// ⚠️ CWE-200: js/cross-window-information-leak
res.send(`
<script>
window.opener.postMessage('sensitive-data', '*');
</script>
`);
});
// CWE-200: Stack trace exposure
app.get('/error-stack', (req, res) => {
try {
throw new Error('Something went wrong');
} catch (e) {
// ⚠️ CWE-200: js/stack-trace-exposure
res.json({ error: e.stack });
}
});
// CWE-200: Build artifact leak
app.get('/source-map', (req, res) => {
// ⚠️ CWE-200: js/build-artifact-leak
res.sendFile(path.join(__dirname, 'dist', 'app.js.map'));
});
// CWE-200: Clear-text logging
app.post('/login', (req, res) => {
const password = req.body.password;
// ⚠️ CWE-200/CWE-312: js/clear-text-logging
console.log(`Login attempt with password: ${password}`);
res.json({ success: true });
});
// CWE-200: Clear-text storage
app.post('/store-secret', (req, res) => {
const secret = req.body.secret;
// ⚠️ CWE-200/CWE-312: js/clear-text-storage-of-sensitive-data
fs.writeFileSync('secrets.txt', secret);
res.json({ stored: true });
});
// CWE-200: Sensitive GET query
app.get('/api/auth', (req, res) => {
// ⚠️ CWE-200: js/sensitive-get-query
const apiKey = req.query.apiKey;
res.json({ authenticated: true });
});
// CWE-312: Password in configuration
const config = {
// ⚠️ CWE-312: js/password-in-configuration-file
database: {
host: 'localhost',
user: 'admin',
password: 'SuperSecret123!'
}
};
// CWE-326: Insufficient key size
app.post('/encrypt-weak', (req, res) => {
const data = req.body.data;
// ⚠️ CWE-326: js/insufficient-key-size
const algorithm = 'des';
const key = crypto.randomBytes(8);
const cipher = crypto.createCipheriv(algorithm, key, Buffer.alloc(8));
const encrypted = cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
res.json({ encrypted });
});
// CWE-327: Weak cryptographic algorithm
app.post('/hash-md5', (req, res) => {
const data = req.body.data;
// ⚠️ CWE-327/CWE-328: js/weak-cryptographic-algorithm
const hash = crypto.createHash('md5').update(data).digest('hex');
res.json({ hash });
});
// CWE-327: Biased cryptographic random
app.get('/random-biased', (req, res) => {
// ⚠️ CWE-327: js/biased-cryptographic-random
const random = crypto.randomBytes(16).readUInt32BE(0) % 100;
res.json({ random });
});
// CWE-327: Insufficient password hash
app.post('/hash-password', (req, res) => {
const password = req.body.password;
// ⚠️ CWE-327: js/insufficient-password-hash
const hash = crypto.createHash('sha256').update(password).digest('hex');
res.json({ hash });
});
// CWE-330/CWE-338: Insecure randomness
app.get('/generate-token', (req, res) => {
// ⚠️ CWE-330/CWE-338: js/insecure-randomness
const token = Math.random().toString(36).substring(7);
res.json({ token });
});
// CWE-330: Hardcoded credentials
const JWT_SECRET = 'hardcoded-secret-key-12345';
// ⚠️ CWE-330: js/hardcoded-credentials
// CWE-340: Predictable token
app.get('/session-token', (req, res) => {
// ⚠️ CWE-340: js/predictable-token
const timestamp = Date.now();
const token = crypto.createHash('md5').update(timestamp.toString()).digest('hex');
res.json({ token });
});
// CWE-345: JWT missing verification
app.post('/verify-jwt', (req, res) => {
const token = req.body.token;
// ⚠️ CWE-345/CWE-347: js/jwt-missing-verification
const decoded = Buffer.from(token.split('.')[1], 'base64').toString();
res.json({ user: JSON.parse(decoded) });
});
// CWE-345: Decode JWT without verification
app.get('/decode-jwt', (req, res) => {
const token = req.query.token;
// ⚠️ CWE-345/CWE-347: js/decode-jwt-without-verification
const parts = token.split('.');
const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
res.json(payload);
});
// CWE-352: Missing CSRF middleware
app.post('/update-profile', (req, res) => {
// ⚠️ CWE-352: js/missing-token-validation - Missing CSRF protection
const email = req.body.email;
res.json({ updated: true, email });
});
// CWE-359: Clear-text cookie
app.post('/set-cookie', (req, res) => {
const sessionId = req.body.sessionId;
// ⚠️ CWE-359: js/clear-text-cookie
res.cookie('sessionId', sessionId, { httpOnly: false, secure: false });
res.json({ set: true });
});
// CWE-367: File system race condition
app.post('/check-and-write', (req, res) => {
const filename = req.body.filename;
const content = req.body.content;
// ⚠️ CWE-367: js/file-system-race
if (!fs.existsSync(filename)) {
fs.writeFileSync(filename, content);
}
res.json({ written: true });
});
// CWE-377/378: Insecure temporary file
app.post('/create-temp', (req, res) => {
const data = req.body.data;
// ⚠️ CWE-377/378: js/insecure-temporary-file
const tmpFile = `/tmp/temp-${Date.now()}.txt`;
fs.writeFileSync(tmpFile, data);
res.json({ file: tmpFile });
});
// CWE-400: Polynomial ReDoS
app.get('/validate-email', (req, res) => {
const email = req.query.email;
// ⚠️ CWE-400/CWE-1333: js/polynomial-redos
const regex = /^([a-zA-Z0-9]+)+@example\.com$/;
const isValid = regex.test(email);
res.json({ isValid });
});
// CWE-400: Inefficient regular expression
app.get('/match-pattern', (req, res) => {
const input = req.query.input;
// ⚠️ CWE-400/CWE-1333: js/redos
const regex = /(a+)+b/;
const matches = regex.test(input);
res.json({ matches });
});
// CWE-400: Resource exhaustion from deep traversal
app.post('/deep-traverse', (req, res) => {
const obj = req.body.obj;
// ⚠️ CWE-400: js/resource-exhaustion-from-deep-object-traversal
function traverse(o, depth = 0) {
if (depth > 1000) return;
for (let key in o) {
if (typeof o[key] === 'object') traverse(o[key], depth + 1);
}
}
traverse(obj);
res.json({ traversed: true });
});
// CWE-400: Remote property injection
app.post('/set-property', (req, res) => {
const target = {};
const prop = req.body.prop;
const value = req.body.value;
// ⚠️ CWE-400: js/remote-property-injection
target[prop] = value;
res.json({ set: true });
});
// CWE-400: Regex injection
app.get('/regex-search', (req, res) => {
const pattern = req.query.pattern;
const text = 'Sample text to search';
// ⚠️ CWE-400: js/regex-injection
const regex = new RegExp(pattern);
const found = regex.test(text);
res.json({ found });
});
// CWE-400: Missing rate limiting
app.post('/api/expensive', (req, res) => {
// ⚠️ CWE-400/CWE-307: js/missing-rate-limiting
const result = crypto.pbkdf2Sync(req.body.data, 'salt', 100000, 64, 'sha512');
res.json({ result: result.toString('hex') });
});
// CWE-400: Resource exhaustion
app.post('/allocate-memory', (req, res) => {
const size = parseInt(req.body.size);
// ⚠️ CWE-400: js/resource-exhaustion
const buffer = Buffer.alloc(size);
res.json({ allocated: size });
});
// CWE-400: XML bomb
app.post('/parse-xml', (req, res) => {
const xml = req.body.xml;
// ⚠️ CWE-400: js/xml-bomb - XML internal entity expansion
res.json({ parsed: true });
});
// CWE-434: HTTP to file access
app.post('/download-and-save', (req, res) => {
const url = req.body.url;
const filename = req.body.filename;
// ⚠️ CWE-434: js/http-to-file-access
https.get(url, (response) => {
const file = fs.createWriteStream(filename);
response.pipe(file);
res.json({ downloaded: true });
});
});
// CWE-441: Client-side request forgery
app.get('/fetch-url', (req, res) => {
// ⚠️ CWE-441: js/client-side-request-forgery
res.send(`
<script>
const url = new URLSearchParams(window.location.search).get('url');
fetch(url).then(r => r.text()).then(data => console.log(data));
</script>
`);
});
// CWE-441: Server-side request forgery
app.get('/ssrf', (req, res) => {
const url = req.query.url;
// ⚠️ CWE-441: js/request-forgery - Server-side request forgery
https.get(url, (response) => {
let data = '';
response.on('data', chunk => data += chunk);
response.on('end', () => res.send(data));
});
});
// CWE-451: Missing X-Frame-Options
app.get('/frameable', (req, res) => {
// ⚠️ CWE-451: js/missing-x-frame-options
res.send('<h1>This page can be framed</h1>');
});
// CWE-502: Unsafe deserialization
app.post('/deserialize', (req, res) => {
const data = req.body.data;
// ⚠️ CWE-502: js/unsafe-deserialization
const obj = serialize.unserialize(data);
res.json({ obj });
});
// CWE-610: Client-side URL redirect
app.get('/client-redirect', (req, res) => {
const target = req.query.target;
// ⚠️ CWE-610: js/client-side-unvalidated-url-redirection
res.send(`
<script>
window.location.href = '${target}';
</script>
`);
});
// CWE-610: Server-side URL redirect
app.get('/redirect', (req, res) => {
const url = req.query.url;
// ⚠️ CWE-610: js/server-side-unvalidated-url-redirection
res.redirect(url);
});
// CWE-610: XXE - XML external entity
app.post('/parse-xml-xxe', (req, res) => {
const xml = req.body.xml;
// ⚠️ CWE-610: js/xxe - XML external entity expansion
// Simulated XXE vulnerability
res.json({ parsed: true });
});
// CWE-614: Insecure cookie
app.get('/insecure-cookie', (req, res) => {
// ⚠️ CWE-614: Cookie without secure flag
res.cookie('auth', 'token123', { secure: false });
res.json({ set: true });
});
// CWE-640: Host header poisoning
app.post('/send-email', (req, res) => {
const host = req.headers.host;
const email = req.body.email;
// ⚠️ CWE-640: js/host-header-forgery-in-email-generation
const resetLink = `http://${host}/reset-password?token=abc`;
console.log(`Sending email to ${email} with link: ${resetLink}`);
res.json({ sent: true });
});
// CWE-643: XPath Injection (duplicate for emphasis)
app.get('/xpath-lookup', (req, res) => {
const username = req.query.username;
// ⚠️ CWE-643: XPath injection
const query = `/users/user[username='${username}']`;
res.json({ query });
});
// CWE-664: User-controlled bypass
app.get('/admin-check', (req, res) => {
const isAdmin = req.query.isAdmin;
// ⚠️ CWE-664: js/user-controlled-bypass
if (isAdmin === 'true') {
res.json({ message: 'Admin access granted' });
} else {
res.status(403).json({ message: 'Access denied' });
}
});
// CWE-664: Comparison of different kinds
app.post('/authenticate', (req, res) => {
const userRole = req.body.role;
// ⚠️ CWE-664: js/different-kinds-comparison-bypass
if (userRole == 'admin') {
res.json({ authenticated: true });
}
});
// CWE-664: Insecure download
app.get('/download-script', (req, res) => {
// ⚠️ CWE-664: js/insecure-download
const scriptUrl = 'http://cdn.example.com/script.js';
res.send(`<script src="${scriptUrl}"></script>`);
});
// CWE-664: Functionality from untrusted domain
app.get('/load-external', (req, res) => {
const domain = req.query.domain;
// ⚠️ CWE-664: js/functionality-from-untrusted-domain
res.send(`<script src="http://${domain}/script.js"></script>`);
});
// CWE-664: Functionality from untrusted source
app.get('/load-script', (req, res) => {
const src = req.query.src;
// ⚠️ CWE-664: js/functionality-from-untrusted-source
res.send(`<script src="${src}"></script>`);
});
// CWE-664: Type confusion through parameter tampering
app.post('/process-data', (req, res) => {
const data = req.body.data;
// ⚠️ CWE-664: js/type-confusion-through-parameter-tampering
if (typeof data === 'string') {
res.json({ length: data.length });
} else if (typeof data === 'number') {
res.json({ value: data });
}
});