-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathca.js
More file actions
169 lines (161 loc) · 4.9 KB
/
ca.js
File metadata and controls
169 lines (161 loc) · 4.9 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
import { generateKeyPairSync } from 'node:crypto';
import { wildcardAllowed } from './util.js';
import fs from 'node:fs';
import forge from 'node-forge';
const pki = forge.pki;
const CAAttrs = [
{
name: 'countryName',
value: 'XX',
},
{
shortName: 'ST',
value: process.env.CA_ATTR_STATE || 'XX',
},
{
name: 'localityName',
value: process.env.CA_ATTR_LOCALITY || 'XX',
},
{
name: 'organizationName',
value: process.env.CA_ATTR_ORGANISATION || 'XX',
},
{
shortName: 'OU',
value: process.env.CA_ATTR_ORGANISATIONAL_UNIT || 'XX',
},
];
let RootCAPrivateKey = null
, RootCAPublicKey = null
, RootCACertificate = null;
function generateCAKeyPair() {
return generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
// cipher: 'aes-256-cbc',
// passphrase: 'changeme'
}
});
}
function generateCertificate(privateKey, publicKey) {
const prKey = pki.privateKeyFromPem(privateKey);
const pubKey = pki.publicKeyFromPem(publicKey);
const cert = pki.createCertificate();
cert.publicKey = pubKey;
cert.serialNumber = `00${Math.floor(Math.random()*1000)}`;
//TODO: shorter/customisable
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10);
cert.setSubject(CAAttrs);
cert.setIssuer(CAAttrs);
cert.setExtensions([
{
name: 'basicConstraints',
cA: true,
},
{
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true,
},
]);
cert.sign(prKey, forge.md.sha256.create());
return pki.certificateToPem(cert);
}
export function verifyCSR(csrPem, allowedDomains, serialNumber) {
const csr = pki.certificationRequestFromPem(csrPem);
const subject = csr.subject.getField('CN').value;
// const isWildcard = subject.startsWith('*.');
if (subject.startsWith('*.')) {
if (!wildcardAllowed(subject, allowedDomains)) {
throw new Error(`No permission for subject "${subject}"`);
}
} else if (!allowedDomains.includes(subject)) {
throw new Error(`No permission for subject "${subject}"`);
}
const exts = csr.getAttribute({ name: 'extensionRequest' });
let altNamesExt;
if (exts && exts.extensions) {
altNamesExt = exts.extensions.find(ext => ext.name === 'subjectAltName');
if (altNamesExt) {
const badAltNames = altNamesExt.altNames.filter(altName => {
if (altName.value.startsWith('*.')) {
return !wildcardAllowed(altName.value, allowedDomains);
}
return !allowedDomains.includes(altName.value);
});
if (badAltNames && badAltNames.length > 0) {
const badAltNamesString = badAltNames.map(x => x.value).join(', ');
throw new Error(`No permission for altname(s): [${badAltNamesString}]`);
}
}
}
const caCert = RootCACertificate;
const caKey = RootCAPrivateKey;
if (!csr.verify()) {
throw new Error('Signature verification failed, please contact support.');
}
const cert = pki.createCertificate();
cert.serialNumber = `00${serialNumber}${Math.floor(Math.random()*100)}`;
//TODO: shorter/customisable
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 10);
cert.setSubject(csr.subject.attributes); //CSR subject (user sets domain)
cert.setIssuer(caCert.subject.attributes); //CA issuer
const certExtensions = [
{
name: 'basicConstraints',
cA: false,
},
{
name: 'keyUsage',
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true,
},
];
if (altNamesExt && altNamesExt.altNames) {
certExtensions.push({
name: 'subjectAltName',
altNames: altNamesExt.altNames.map(an => ({
type: 2, // DNS
value: an.value
}))
});
}
cert.setExtensions(certExtensions);
cert.publicKey = csr.publicKey;
cert.sign(caKey, forge.md.sha256.create());
return pki.certificateToPem(cert);
}
try {
RootCAPrivateKey = pki.privateKeyFromPem(fs.readFileSync('./ca/ca-private-key.pem'));
RootCAPublicKey = pki.publicKeyFromPem(fs.readFileSync('./ca/ca-public-key.pem'));
RootCACertificate = pki.certificateFromPem(fs.readFileSync('./ca/ca-cert.pem'));
} catch (e) {
console.warn('CA cert not loaded:', e);
}
if (!RootCAPrivateKey || !RootCAPublicKey || !RootCACertificate) {
console.log('Generating root CA Keys');
const Keys = generateCAKeyPair();
RootCAPrivateKey = Keys.privateKey;
RootCAPublicKey = Keys.publicKey;
fs.writeFileSync('./ca/ca-private-key.pem', RootCAPrivateKey, { encoding: 'utf-8' });
fs.writeFileSync('./ca/ca-public-key.pem', RootCAPublicKey, { encoding: 'utf-8' });
console.log('Generating root CA Cert');
const CACert = generateCertificate(RootCAPrivateKey, RootCAPublicKey);
RootCACertificate = pki.certificateFromPem(CACert);
fs.writeFileSync('./ca/ca-cert.pem', CACert, { encoding: 'utf-8' });
}