-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
548 lines (480 loc) · 19.5 KB
/
server.js
File metadata and controls
548 lines (480 loc) · 19.5 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
const express = require('express');
const path = require('path');
const fs = require('fs');
const { execFileSync } = require('child_process');
const app = express();
const PORT = process.env.PORT || 3000;
const CERT_DIR = path.join(__dirname, 'data');
const PRIVATE_FILE = path.join(CERT_DIR, 'root-key.pem');
const PUBLIC_FILE = path.join(CERT_DIR, 'root-crt.pem');
const DER_FILE = path.join(CERT_DIR, 'root-crt.der');
const CERTS_JSON = path.join(CERT_DIR, 'certs.json');
// Body parsing for JSON requests (parse application/json and application/x-www-form-urlencoded)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// delivers /public/certgen.html under /certgen
app.get('/certgen', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'certgen.html'));
});
// Helper functions
// Check whether the CA private key and public certificate files exist
function caExists() {
try {
return fs.existsSync(PRIVATE_FILE) && fs.existsSync(PUBLIC_FILE);
} catch (e) {
return false;
}
}
// sanitize common name to filename base: lowercase, only letters+digits
function sanitizeName(name) {
if (!name) return 'certificate';
return String(name).toLowerCase().replace(/[^a-z0-9]/g, '');
}
function ensureCertDir() {
// Ensure the certificate storage directory exists and set secure permissions (0700)
if (!fs.existsSync(CERT_DIR)) {
fs.mkdirSync(CERT_DIR, { mode: 0o700, recursive: true });
}
}
// read certs.json or return base structure
function readCertsJson() {
try {
ensureCertDir();
if (!fs.existsSync(CERTS_JSON)) {
return { certificates: [] };
}
const raw = fs.readFileSync(CERTS_JSON, 'utf8');
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.certificates)) {
return { certificates: [] };
}
return parsed;
} catch (e) {
// invalid JSON -> start fresh
return { certificates: [] };
}
} catch (e) {
return { certificates: [] };
}
}
function writeCertsJson(obj) {
try {
ensureCertDir();
fs.writeFileSync(CERTS_JSON, JSON.stringify(obj, null, 2), { mode: 0o644 });
} catch (e) {
console.error('Failed to write certs.json', e);
throw e;
}
}
// generate unique filename in CERT_DIR with given base and suffix
function uniqueFilename(base, suffix) {
let name = `${base}${suffix}`;
let full = path.join(CERT_DIR, name);
let counter = 1;
while (fs.existsSync(full)) {
name = `${base}-${counter}${suffix}`;
full = path.join(CERT_DIR, name);
counter += 1;
}
return name;
}
// format expiry date as DD.MM.YYYY (de-DE)
function formatExpiryDate(days) {
const dt = new Date(Date.now() + (days * 24 * 60 * 60 * 1000));
return dt.toLocaleDateString('de-DE');
}
// Function to convert PEM to DER format
function convertPemToDer(pemFilePath, derFilePath) {
const pemData = fs.readFileSync(pemFilePath, 'utf8');
const derData = Buffer.from(pemData.replace(/-----BEGIN CERTIFICATE-----/g, '')
.replace(/-----END CERTIFICATE-----/g, '')
.replace(/\n/g, ''), 'base64');
fs.writeFileSync(derFilePath, derData);
}
// CA status: return whether a Root CA is present
// NOTE: endpoint name corrected from "exsists" to "exists"
app.get('/api/root-ca/exists', (req, res) => {
res.json({ exists: caExists() });
});
// Import a regular expression to check for IP addresses
const isIpAddress = (value) => /^(\d{1,3}\.){3}\d{1,3}$/.test(value);
// Generate a self-signed Root CA pair using openssl instead of the selfsigned library.
// Accepts options via JSON body: commonName, days (validity), keySize.
// If "force" query flag is not set and CA exists, respond with 409 Conflict.
app.post('/api/root-ca/generate', (req, res) => {
const force = req.query.force === '1' || req.query.force === 'true';
if (caExists() && !force) {
return res.status(409).json({ error: 'CA already exists' });
}
const { commonName = 'SimpleCA Root', days = 3650, keySize = 2048 } = req.body || {};
const daysNum = parseInt(days, 10);
const keySizeNum = parseInt(keySize, 10);
if (!Number.isFinite(daysNum) || daysNum <= 0 || daysNum > 36500) {
return res.status(400).json({ error: 'Invalid days value' });
}
if (![1024, 2048, 4096].includes(keySizeNum)) {
return res.status(400).json({ error: 'Invalid keySize. Allowed: 1024, 2048, 4096' });
}
// Build SAN entries: include CN as first SAN
const sanEntries = [];
if (commonName) {
if (isIpAddress(commonName)) sanEntries.push({ type: 'IP', value: commonName });
else sanEntries.push({ type: 'DNS', value: commonName });
}
// prepare files
try {
ensureCertDir();
// create temporary openssl config for root CA with SANs and CA extensions
let altNamesSection = '';
let dnsCount = 0;
let ipCount = 0;
for (const entry of sanEntries) {
if (entry.type === 'DNS') {
dnsCount += 1;
altNamesSection += `DNS.${dnsCount} = ${entry.value}\n`;
} else {
ipCount += 1;
altNamesSection += `IP.${ipCount} = ${entry.value}\n`;
}
}
const cfgFile = path.join(CERT_DIR, `root-openssl.cnf`);
const cfg = `
[ req ]
default_bits = ${keySizeNum}
distinguished_name = req_distinguished_name
x509_extensions = v3_ca
prompt = no
default_md = sha256
[ req_distinguished_name ]
CN = ${commonName}
[ v3_ca ]
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, cRLSign, keyCertSign
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer:always
subjectAltName = @alt_names
[ alt_names ]
${altNamesSection}
`.trim();
fs.writeFileSync(cfgFile, cfg, { mode: 0o600 });
// generate private key and self-signed root cert using openssl
try {
// generate private key
execFileSync('openssl', ['genrsa', '-out', PRIVATE_FILE, String(keySizeNum)], { cwd: CERT_DIR });
// generate self-signed cert (x509) with extensions from config
execFileSync('openssl', [
'req', '-new', '-x509',
'-key', PRIVATE_FILE,
'-out', PUBLIC_FILE,
'-days', String(daysNum),
'-sha256',
'-subj', `/CN=${commonName}`,
'-config', cfgFile,
'-extensions', 'v3_ca'
], { cwd: CERT_DIR });
} catch (e) {
// cleanup on error
try { if (fs.existsSync(PRIVATE_FILE)) fs.unlinkSync(PRIVATE_FILE); } catch (_) {}
try { if (fs.existsSync(PUBLIC_FILE)) fs.unlinkSync(PUBLIC_FILE); } catch (_) {}
try { if (fs.existsSync(cfgFile)) fs.unlinkSync(cfgFile); } catch (_) {}
console.error('OpenSSL root CA generation failed', e && e.message ? e.message : e);
return res.status(500).json({ error: 'Failed to generate Root CA (openssl error)', details: String(e && e.message ? e.message : e) });
} finally {
// remove config file
try { if (fs.existsSync(cfgFile)) fs.unlinkSync(cfgFile); } catch (_) {}
}
// set file permissions
try { fs.chmodSync(PRIVATE_FILE, 0o600); } catch (_) {}
try { fs.chmodSync(PUBLIC_FILE, 0o644); } catch (_) {}
// Convert to DER
try {
convertPemToDer(PUBLIC_FILE, DER_FILE);
} catch (e) {
console.error('Failed to convert PEM to DER', e);
}
return res.json({ message: 'Root CA generated', commonName: commonName, days: daysNum, keySize: keySizeNum });
} catch (err) {
console.error('Root CA generation failed', err);
return res.status(500).json({ error: 'Failed to generate CA', details: String(err && err.message ? err.message : err) });
}
});
// Upload existing PEM-formatted private key and certificate.
// Performs simple format checks and writes the files with secure permissions.
app.post('/api/root-ca/upload', (req, res) => {
const { private: privatePem, public: publicPem } = req.body || {};
if (!privatePem || !publicPem) {
return res.status(400).json({ error: 'Both private and public PEM must be provided' });
}
// simple validation
if (!privatePem.includes('-----END RSA PRIVATE KEY-----') || !publicPem.includes('-----END CERTIFICATE-----')) {
return res.status(400).json({ error: 'Invalid PEM format' });
}
try {
ensureCertDir();
fs.writeFileSync(PRIVATE_FILE, privatePem, { mode: 0o600 });
fs.writeFileSync(PUBLIC_FILE, publicPem, { mode: 0o644 });
return res.json({ message: 'CA uploaded' });
} catch (err) {
console.error(err);
return res.status(500).json({ error: 'Failed to save CA' });
}
});
// Generate a new leaf certificate (self-signed for now), save cert+key and update certs.json
app.post('/api/leaf/generate', (req, res) => {
try {
const { commonName = 'localhost', sans = '', days = 365, keySize = 2048 } = req.body || {};
const daysNum = parseInt(days, 10);
const keySizeNum = parseInt(keySize, 10);
if (!Number.isFinite(daysNum) || daysNum <= 0 || daysNum > 36500) {
return res.status(400).json({ error: 'Invalid days value' });
}
if (![1024, 2048, 4096].includes(keySizeNum)) {
return res.status(400).json({ error: 'Invalid keySize. Allowed: 1024, 2048, 4096' });
}
// require root CA to exist
if (!caExists()) {
return res.status(400).json({ error: 'Root CA not present. Generate/upload root CA first.' });
}
// Check for existing cert in certs.json ---
const certsObj = readCertsJson();
const normalizedNewName = String(commonName).trim().toLowerCase();
const exists = (certsObj.certificates || []).some(c => String(c.name || '').trim().toLowerCase() === normalizedNewName);
if (exists) {
return res.status(409).json({ error: 'Certificate with that name already exists' });
}
// Build SAN entries: include CN as first SAN, then any additional SANs
const sanEntries = [];
if (commonName) {
if (isIpAddress(commonName)) sanEntries.push({ type: 'IP', value: commonName });
else sanEntries.push({ type: 'DNS', value: commonName });
}
if (sans) {
const parts = String(sans).split(',').map(s => s.trim()).filter(Boolean);
for (const p of parts) {
if (isIpAddress(p)) sanEntries.push({ type: 'IP', value: p });
else sanEntries.push({ type: 'DNS', value: p });
}
}
// prepare filenames
ensureCertDir();
const base = sanitizeName(commonName || 'certificate');
const certFile = uniqueFilename(base, '-cert.pem');
const keyFile = uniqueFilename(base, '-key.pem');
const certPath = path.join(CERT_DIR, certFile);
const keyPath = path.join(CERT_DIR, keyFile);
// temporary files (CSR and openssl config) placed in CERT_DIR
const csrFile = path.join(CERT_DIR, `${base}-req.csr`);
const cfgFile = path.join(CERT_DIR, `${base}-openssl.cnf`);
// Build openssl config with SANs
let altNamesSection = '';
let dnsCount = 0;
let ipCount = 0;
for (const entry of sanEntries) {
if (entry.type === 'DNS') {
dnsCount += 1;
altNamesSection += `DNS.${dnsCount} = ${entry.value}\n`;
} else {
ipCount += 1;
altNamesSection += `IP.${ipCount} = ${entry.value}\n`;
}
}
const cfg = `
[ req ]
default_bits = ${keySizeNum}
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no
[ req_distinguished_name ]
CN = ${commonName}
[ v3_req ]
subjectAltName = @alt_names
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
[ alt_names ]
${altNamesSection}
`.trim();
fs.writeFileSync(cfgFile, cfg, { mode: 0o600 });
try {
// generate key
execFileSync('openssl', ['genrsa', '-out', keyPath, String(keySizeNum)], { cwd: CERT_DIR });
// generate CSR using config (adds SANs)
execFileSync('openssl', ['req', '-new', '-key', keyPath, '-subj', `/CN=${commonName}`, '-config', cfgFile, '-reqexts', 'v3_req', '-out', csrFile], { cwd: CERT_DIR });
// sign CSR with Root CA (uses v3_req from the config to add SANs and usages)
execFileSync('openssl', [
'x509', '-req',
'-in', csrFile,
'-CA', PUBLIC_FILE,
'-CAkey', PRIVATE_FILE,
'-CAcreateserial',
'-out', certPath,
'-days', String(daysNum),
'-sha256',
'-extfile', cfgFile,
'-extensions', 'v3_req'
], { cwd: CERT_DIR });
} catch (e) {
// cleanup possible partial files
try { if (fs.existsSync(keyPath)) fs.unlinkSync(keyPath); } catch (_) {}
try { if (fs.existsSync(certPath)) fs.unlinkSync(certPath); } catch (_) {}
try { if (fs.existsSync(csrFile)) fs.unlinkSync(csrFile); } catch (_) {}
try { if (fs.existsSync(cfgFile)) fs.unlinkSync(cfgFile); } catch (_) {}
console.error('OpenSSL step failed', e && e.message ? e.message : e);
return res.status(500).json({ error: 'Failed to create or sign certificate (openssl error)', details: String(e && e.message ? e.message : e) });
} finally {
// remove csr and config (keep serial file created by CA if any)
try { if (fs.existsSync(csrFile)) fs.unlinkSync(csrFile); } catch (_) {}
try { if (fs.existsSync(cfgFile)) fs.unlinkSync(cfgFile); } catch (_) {}
}
// Create a fullchain (leaf cert followed by root CA) so webservers can use it directly
const chainFile = uniqueFilename(base, '-fullchain.pem');
const chainPath = path.join(CERT_DIR, chainFile);
try {
const leafPem = fs.readFileSync(certPath, 'utf8');
const caPem = fs.readFileSync(PUBLIC_FILE, 'utf8');
fs.writeFileSync(chainPath, leafPem + '\n' + caPem, { mode: 0o644 });
} catch (e) {
console.error('Failed to write fullchain', e);
// non-fatal: continue but inform user
}
// set file permissions
try { fs.chmodSync(keyPath, 0o600); } catch (_) {}
try { fs.chmodSync(certPath, 0o644); } catch (_) {}
// update certs.json
const expiry = formatExpiryDate(daysNum);
certsObj.certificates = certsObj.certificates || [];
certsObj.certificates.push({
name: String(commonName),
expiry: expiry,
cert_file: certFile,
key_file: keyFile,
chain_file: typeof chainFile !== 'undefined' ? chainFile : null
});
writeCertsJson(certsObj);
return res.json({
message: 'Leaf certificate generated and signed by Root CA',
name: commonName,
expiry,
cert_file: certFile,
key_file: keyFile,
chain_file: typeof chainFile !== 'undefined' ? chainFile : null,
download_cert: `/data/${certFile}`,
download_key: `/data/${keyFile}`,
download_chain: typeof chainFile !== 'undefined' ? `/data/${chainFile}` : null
});
} catch (err) {
console.error('Leaf generation failed', err);
return res.status(500).json({ error: 'Failed to generate leaf certificate', details: String(err && err.message ? err.message : err) });
}
});
// delete helper: searches certs.json entry by name, deletes files (cert_file, key_file, optional chain_file)
// and removes entry only if no I/O errors occurred.
// Returns: { status: 'ok'|'notfound'|'error', details: { deleted:[], missing:[], errors:[] }, entry? }
function deleteCertificateByName(name) {
if (!name) return { status: 'notfound' };
const certsObj = readCertsJson();
certsObj.certificates = certsObj.certificates || [];
const idx = certsObj.certificates.findIndex(c => c.name === String(name));
if (idx === -1) {
console.log(`[delete] Entry with name="${name}" not found in certs.json`);
return { status: 'notfound' };
}
const entry = certsObj.certificates[idx];
console.log('[delete] Found entry:', entry);
const dirResolved = path.resolve(CERT_DIR) + path.sep;
const resolveFilename = (filename) => {
if (!filename) return { ok: false, reason: 'no filename', filename: null };
const full = path.join(CERT_DIR, filename);
const resolved = path.resolve(full);
if (!resolved.startsWith(dirResolved)) return { ok: false, reason: 'path outside cert dir', filename };
return { ok: true, resolved, filename };
};
// Prepare checks for cert, key and optional chain file
const certCheck = resolveFilename(entry.cert_file);
const keyCheck = resolveFilename(entry.key_file);
const chainCheck = entry.chain_file ? resolveFilename(entry.chain_file) : null;
const deleted = [];
const missing = [];
const errors = [];
const attemptUnlink = (check) => {
if (!check) return; // nothing to delete (e.g. no chain file)
if (!check.ok) {
errors.push({ file: check.filename, reason: check.reason });
return;
}
try {
if (fs.existsSync(check.resolved)) {
fs.unlinkSync(check.resolved);
deleted.push(check.filename);
} else {
// file already missing -> note as "missing", but not a fatal error
missing.push(check.filename);
}
} catch (e) {
errors.push({ file: check.filename, error: String(e) });
}
};
attemptUnlink(certCheck);
attemptUnlink(keyCheck);
attemptUnlink(chainCheck); // also attempts to delete the fullchain file if present
if (errors.length > 0) {
// On real errors, do not modify certs.json
return { status: 'error', details: { deleted, missing, errors }, entry };
}
// If no severe error occurred, remove entry and persist changes
certsObj.certificates.splice(idx, 1);
try {
writeCertsJson(certsObj);
console.log(`[delete] certs.json updated, entry "${name}" removed`);
} catch (e) {
console.error('[delete] Failed to write certs.json after deletion', e);
return { status: 'error', details: { deleted, missing, writeError: String(e) }, entry };
}
return { status: 'ok', details: { deleted, missing }, entry };
}
// Compatibility: provide POST endpoint to delete by JSON body { name }
// This keeps frontend (which sends POST) working while GET handler (query param) remains available.
app.post('/api/leaf/delete', (req, res) => {
try {
const name = req.body && req.body.name;
console.log('[api] POST /api/leaf/delete body.name=', name);
if (!name) return res.status(400).json({ error: 'Missing "name" in request body' });
const result = deleteCertificateByName(name);
if (result.status === 'notfound') {
return res.status(404).json({ error: 'Certificate not found' });
}
if (result.status === 'error') {
return res.status(500).json({ error: 'Failed to delete certificate', details: result.details });
}
return res.json({ message: 'Certificate deleted', name, details: result.details });
} catch (err) {
console.error('POST delete failed', err);
return res.status(500).json({ error: 'Failed to delete certificate', details: String(err && err.message ? err.message : err) });
}
});
// keep older GET-based delete endpoint for backward compatibility
app.get('/api/leaf/delete', (req, res) => {
try {
const name = req.query.name;
console.log('[api] GET /api/leaf/delete?name=', name);
if (!name) return res.status(400).send('Missing "name" query parameter');
const result = deleteCertificateByName(name);
if (result.status === 'notfound') {
return res.status(404).send('Certificate not found');
}
if (result.status === 'error') {
return res.status(500).json({ error: 'Failed to delete certificate', details: result.details });
}
return res.json({ message: 'Certificate deleted', name, details: result.details });
} catch (err) {
console.error('GET delete failed', err);
return res.status(500).json({ error: 'Failed to delete certificate', details: String(err && err.message ? err.message : err) });
}
});
// --- ensure static file serving is registered after API routes ---
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, 'data')));
app.listen(PORT, () => {
console.log(`App is running at http://localhost:${PORT}`);
});