-
Notifications
You must be signed in to change notification settings - Fork 84
/
tls.ts
206 lines (170 loc) · 6.38 KB
/
tls.ts
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
/**
* @module TLS
*/
import * as _ from 'lodash';
import * as uuid from 'uuid/v4';
import * as forge from 'node-forge';
const { pki, md, util: { encode64 } } = forge;
import * as fs from './fs';
export type CAOptions = (HttpsOptions | HttpsPathOptions);
export type HttpsOptions = {
key: string;
cert: string;
keyLength?: number;
};
export type HttpsPathOptions = {
keyPath: string;
certPath: string;
keyLength?: number;
}
export type PEM = string | string[] | Buffer | Buffer[];
export type GeneratedCertificate = {
key: string,
cert: string,
ca: string
};
/**
* Generate a CA certificate for mocking HTTPS.
*
* Returns a promise, for an object with key and cert properties,
* containing the generated private key and certificate in PEM format.
*
* These can be saved to disk, and their paths passed
* as HTTPS options to a Mockttp server.
*/
export async function generateCACertificate(options: { commonName?: string, bits?: number } = {}) {
options = _.defaults({}, options, {
commonName: 'Mockttp Testing CA - DO NOT TRUST - TESTING ONLY',
bits: 2048
});
const keyPair = await new Promise<forge.pki.rsa.KeyPair>((resolve, reject) => {
pki.rsa.generateKeyPair({ bits: options.bits }, (error, keyPair) => {
if (error) reject(error);
else resolve(keyPair);
});
});
const cert = pki.createCertificate();
cert.publicKey = keyPair.publicKey;
cert.serialNumber = uuid().replace(/-/g, '');
cert.validity.notBefore = new Date();
// Make it valid for the last 24h - helps in cases where clocks slightly disagree
cert.validity.notBefore.setDate(cert.validity.notBefore.getDate() - 1);
cert.validity.notAfter = new Date();
// Valid for the next year by default.
cert.validity.notAfter.setFullYear(cert.validity.notAfter.getFullYear() + 1);
cert.setSubject([{ name: 'commonName', value: options.commonName }]);
cert.setExtensions([{
name: 'basicConstraints',
cA: true
}]);
// Self-issued too
cert.setIssuer(cert.subject.attributes);
// Self-sign the certificate - we're the root
cert.sign(keyPair.privateKey, md.sha256.create());
return {
key: pki.privateKeyToPem(keyPair.privateKey),
cert: pki.certificateToPem(cert)
};
}
export function generateSPKIFingerprint(certPem: PEM) {
let cert = pki.certificateFromPem(certPem.toString('utf8'));
return encode64(
pki.getPublicKeyFingerprint(cert.publicKey, {
type: 'SubjectPublicKeyInfo',
md: md.sha256.create(),
encoding: 'binary'
})
);
}
export async function getCA(options: CAOptions): Promise<CA> {
let httpsOptions: HttpsOptions;
if ((<any>options).key && (<any>options).cert) {
httpsOptions = <HttpsOptions> options;
}
else if ((<any>options).keyPath && (<any>options).certPath) {
let pathOptions = <HttpsPathOptions> options;
httpsOptions = await Promise.all([
fs.readFile(pathOptions.keyPath, 'utf8'),
fs.readFile(pathOptions.certPath, 'utf8')
]).then(([ keyContents, certContents ]) => ({
key: keyContents,
cert: certContents,
keyLength: pathOptions.keyLength
}));
}
else {
throw new Error('Unrecognized https options: you need to provide either a keyPath & certPath, or a key & cert.')
}
return new CA(httpsOptions.key, httpsOptions.cert, httpsOptions.keyLength || 1024);
}
// We share a single keypair across all certificates in this process, and
// instantiate it once when the first CA is created, because it can be
// expensive (depending on the key length).
// This would be a terrible idea for a real server, but for a mock server
// it's ok - if anybody can steal this, they can steal the CA cert anyway.
let KEY_PAIR: {
publicKey: forge.pki.rsa.PublicKey,
privateKey: forge.pki.rsa.PrivateKey,
length: number
} | undefined;
export class CA {
private caCert: forge.pki.Certificate;
private caKey: forge.pki.PrivateKey;
private certCache: { [domain: string]: GeneratedCertificate };
constructor(
caKey: PEM,
caCert: PEM,
keyLength: number
) {
this.caKey = pki.privateKeyFromPem(caKey.toString('utf8'));
this.caCert = pki.certificateFromPem(caCert.toString('utf8'));
this.certCache = {};
if (!KEY_PAIR || KEY_PAIR.length < keyLength) {
// If we have no key, or not a long enough one, generate one.
KEY_PAIR = Object.assign(
pki.rsa.generateKeyPair(keyLength),
{ length: keyLength }
);
}
}
generateCertificate(domain: string): GeneratedCertificate {
// TODO: Expire domains from the cache? Based on their actual expiry?
if (this.certCache[domain]) return this.certCache[domain];
let cert = pki.createCertificate();
cert.publicKey = KEY_PAIR!.publicKey;
cert.serialNumber = uuid().replace(/-/g, '');
cert.validity.notBefore = new Date();
// Make it valid for the last 24h - helps in cases where clocks slightly disagree.
cert.validity.notBefore.setDate(cert.validity.notBefore.getDate() - 1);
cert.validity.notAfter = new Date();
// Valid for the next year by default. TODO: Shorten (and expire the cache) automatically.
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
cert.setSubject([
{ name: 'commonName', value: domain },
{ name: 'organizationName', value: 'Mockttp Cert - DO NOT TRUST' }
]);
cert.setIssuer(this.caCert.subject.attributes);
cert.setExtensions([{
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
}, {
name: 'subjectAltName',
altNames: [{
type: 2,
value: domain
}]
}]);
cert.sign(this.caKey, md.sha256.create());
const generatedCertificate = {
key: pki.privateKeyToPem(KEY_PAIR!.privateKey),
cert: pki.certificateToPem(cert),
ca: pki.certificateToPem(this.caCert)
};
this.certCache[domain] = generatedCertificate;
return generatedCertificate;
}
}