-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
344 lines (304 loc) · 11 KB
/
server.js
File metadata and controls
344 lines (304 loc) · 11 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
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { execSync } = require('child_process');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const moment = require('moment');
const axios = require('axios');
const axios = require('axios');
const helmet = require('helmet');
const cors = require('cors');
const serialize = require('serialize-javascript');
const app = express();
const PORT = process.env.PORT || 3000;
// Security middleware (minimal for demo purposes)
app.use(helmet({
contentSecurityPolicy: false // Intentionally disabled for demo
}));
app.use(cors());
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: 'globomantics-secret-key', // Intentionally weak for demo
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Intentionally insecure for demo
}));
// Set view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Static files
app.use(express.static(path.join(__dirname, 'public')));
// Mock database (in-memory for demo)
let robots = [
{
id: 1,
name: 'Atlas-Prime',
model: 'GX-2000',
status: 'Active',
location: 'Warehouse A',
batteryLevel: 87,
lastMaintenance: '2023-12-01',
assignedTask: 'Package Sorting'
},
{
id: 2,
name: 'Beta-Unit',
model: 'GX-1500',
status: 'Maintenance',
location: 'Service Bay 1',
batteryLevel: 23,
lastMaintenance: '2023-11-28',
assignedTask: 'Under Repair'
},
{
id: 3,
name: 'Charlie-Loader',
model: 'HL-3000',
status: 'Active',
location: 'Loading Dock B',
batteryLevel: 95,
lastMaintenance: '2023-12-03',
assignedTask: 'Heavy Lifting'
}
];
let users = [
{
id: 1,
username: 'admin',
password: '$2b$10$rOFLC.b8.TaEZQZlpJo.h.D8J8J1J.1J', // 'password123'
role: 'Administrator'
}
];
// Routes
app.get('/', (req, res) => {
res.render('dashboard', {
title: 'Globomantics Robot Fleet Manager',
robots: robots,
totalRobots: robots.length,
activeRobots: robots.filter(r => r.status === 'Active').length,
moment: moment
});
});
app.get('/robots', (req, res) => {
res.render('robots', {
title: 'Robot Fleet - Globomantics',
robots: robots,
moment: moment
});
});
app.get('/robot/:id', (req, res) => {
const robotId = parseInt(req.params.id);
const robot = robots.find(r => r.id === robotId);
if (!robot) {
return res.status(404).render('error', {
title: 'Robot Not Found',
message: 'The requested robot could not be found.'
});
}
res.render('robot-detail', {
title: `${robot.name} - Globomantics`,
robot: robot,
moment: moment
});
});
app.post('/robot/:id/update', (req, res) => {
const robotId = parseInt(req.params.id);
const robot = robots.find(r => r.id === robotId);
if (robot) {
// Intentionally using unsafe merge for demo purposes
_.merge(robot, req.body);
res.redirect(`/robot/${robotId}`);
} else {
res.status(404).send('Robot not found');
}
});
app.get('/maintenance', (req, res) => {
const maintenanceRobots = robots.filter(r => r.status === 'Maintenance');
res.render('maintenance', {
title: 'Maintenance Schedule - Globomantics',
robots: maintenanceRobots,
moment: moment
});
});
app.get('/api/robots', (req, res) => {
res.json(robots);
});
// Export endpoint
app.get('/api/export/:format', (req, res) => {
const format = req.params.format;
try {
const message = `Exporting data as ${format}`;
res.json({ message });
} catch (error) {
res.status(400).json({ error: 'Invalid format' });
}
});
// =====================================================================
// ADDITIONAL INTENTIONAL VULNERABILITIES (for Semgrep / CodeQL demos)
// These exist on purpose — do NOT fix unless specifically asked.
// =====================================================================
// --- Command Injection (CWE-78) ---
// Semgrep: javascript.lang.security.audit.child-process-injection
app.get('/api/diagnostics/:robotName', (req, res) => {
const robotName = req.params.robotName;
try {
const result = execSync(`ping -c 1 ${robotName}.globomantics.local`);
res.json({ output: result.toString() });
} catch (error) {
res.status(500).json({ error: 'Diagnostics failed' });
}
});
// --- Path Traversal (CWE-22) ---
// Semgrep: javascript.lang.security.audit.path-traversal
app.get('/api/logs/:filename', (req, res) => {
const filename = req.params.filename;
const logPath = path.join(__dirname, 'logs', filename);
res.sendFile(logPath);
});
// --- SSRF (CWE-918) ---
// Semgrep: javascript.lang.security.audit.request-ssrf
// Allow-list of robot health check endpoints. The query parameter selects a key here,
// rather than allowing arbitrary URLs to be requested.
const ALLOWED_HEALTH_ENDPOINTS = {
// Example entries; adjust to match actual robot identifiers and URLs.
robot1: 'http://robot1.internal/health',
robot2: 'http://robot2.internal/health'
};
app.get('/api/robot-health', async (req, res) => {
const targetKey = req.query.url;
const endpoint = ALLOWED_HEALTH_ENDPOINTS[targetKey];
if (!endpoint) {
return res.status(400).json({ error: 'Invalid robot health endpoint' });
}
try {
const response = await axios.get(endpoint);
res.json(response.data);
} catch (error) {
res.status(502).json({ error: 'Health check failed' });
}
});
// --- Hardcoded JWT Secret (CWE-798) ---
// Semgrep: javascript.lang.security.audit.hardcoded-jwt-secret
const JWT_SECRET = 'super-secret-globomantics-key-2024';
app.post('/api/auth/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (user) {
const token = jwt.sign(
{ userId: user.id, role: user.role },
JWT_SECRET,
{ expiresIn: '24h' }
);
res.json({ token });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// --- SQL Injection Pattern (CWE-89) ---
// Semgrep: javascript.lang.security.audit.sqli
app.get('/api/search', (req, res) => {
const query = req.query.q;
// Intentionally unsafe string concatenation for demo
const sql = "SELECT * FROM robots WHERE name LIKE '%" + query + "%'";
// Mock response (no real DB) — the pattern is what scanners flag
res.json({ query: sql, results: robots.filter(r =>
r.name.toLowerCase().includes((query || '').toLowerCase())
)});
});
// --- NoSQL Injection Pattern (CWE-943) ---
// Semgrep: javascript.lang.security.audit.nosql-injection
app.post('/api/robots/find', (req, res) => {
const filter = req.body;
// Directly using user input as a query filter — NoSQL injection
const results = robots.filter(r => {
return Object.keys(filter).every(key => r[key] === filter[key]);
});
res.json(results);
});
// --- Regex DoS / ReDoS (CWE-1333) ---
// Semgrep: javascript.lang.security.audit.detect-regex-dos
app.post('/api/validate-serial', (req, res) => {
const serial = req.body.serial;
// Vulnerable regex — catastrophic backtracking
const pattern = /^(([a-z])+.)+[A-Z]([a-z])+$/;
const isValid = pattern.test(serial);
res.json({ serial, valid: isValid });
});
// --- Insecure Randomness (CWE-330) ---
// Semgrep: javascript.lang.security.audit.insecure-random
app.get('/api/token/generate', (req, res) => {
// Math.random() is not cryptographically secure
const token = Math.random().toString(36).substring(2) +
Math.random().toString(36).substring(2);
res.json({ resetToken: token });
});
// --- XSS via innerHTML Pattern (CWE-79) ---
// Semgrep: javascript.browser.security.audit.innerHTML
app.get('/api/robot-label/:id', (req, res) => {
const robotId = parseInt(req.params.id);
const robot = robots.find(r => r.id === robotId);
const name = req.query.customName || (robot ? robot.name : 'Unknown');
// Reflected user input in HTML response — XSS
res.send(`<html><body><h1>Robot: ${name}</h1><p>Status: ${robot ? robot.status : 'N/A'}</p></body></html>`);
});
// --- Deserialization / Unsafe Serialize (CWE-502) ---
app.get('/api/config/export', (req, res) => {
const config = {
robots: robots,
generatedAt: new Date(),
version: '2.0.0'
};
// serialize-javascript with unsafe option
const serialized = serialize(config, { unsafe: true });
res.type('application/javascript').send(`window.__CONFIG__ = ${serialized}`);
});
// --- Weak Crypto (CWE-327) ---
// Semgrep: javascript.lang.security.audit.weak-crypto
app.post('/api/robot/verify', (req, res) => {
const { robotId, checksum } = req.body;
// MD5 is cryptographically broken
const hash = crypto.createHash('md5').update(String(robotId)).digest('hex');
res.json({ match: hash === checksum, hash });
});
// --- Open Redirect (CWE-601) ---
// Semgrep: javascript.lang.security.audit.open-redirect
app.get('/redirect', (req, res) => {
const target = req.query.url;
res.redirect(target);
});
// --- Prototype Pollution via Object.assign (CWE-1321) ---
app.post('/api/robot/:id/settings', (req, res) => {
const robotId = parseInt(req.params.id);
const robot = robots.find(r => r.id === robotId);
if (robot) {
// Prototype pollution via Object.assign with user input
const settings = Object.assign({}, robot, req.body);
res.json(settings);
} else {
res.status(404).json({ error: 'Robot not found' });
}
});
// --- Hardcoded API Credentials (CWE-798) ---
const TELEMETRY_API_KEY = 'sk-globo-prod-4f8a2b1c9d3e7f6a5b4c3d2e1f0a9b8c';
const DATABASE_PASSWORD = 'Gl0bomantics_Pr0d_2024!';
const AWS_ACCESS_KEY = 'AKIAIOSFODNN7GLOBOMAN';
app.get('/api/telemetry/config', (req, res) => {
res.json({
endpoint: 'https://telemetry.globomantics.com/v2',
apiKey: TELEMETRY_API_KEY,
region: 'us-east-1'
});
});
app.listen(PORT, () => {
console.log(`🤖 Globomantics Robot Fleet Manager running on http://localhost:${PORT}`);
console.log('📊 Internal LOB Application - Authorized Personnel Only');
});