emailengine-app 2.79.9 → 2.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +49 -0
- package/config/default.toml +5 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +34 -2
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/autodetect-imap-settings.js +349 -47
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +50 -6
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +21 -9
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/imap-proxy-auth.js +58 -3
- package/lib/imapproxy/imap-server.js +53 -62
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +32 -0
- package/lib/security-headers.js +15 -0
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +72 -27
- package/lib/ui-routes/account-routes.js +43 -30
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/network-config-routes.js +54 -45
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/package.json +4 -4
- package/sbom.json +1 -1
- package/server.js +16 -0
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/app.js +34 -0
- package/static/js/public.js +6 -2
- package/static/js/ui.js +8 -25
- package/static/licenses.html +328 -1257
- package/translations/messages.pot +87 -87
- package/views/account/login-redirect.hbs +22 -0
- package/views/config/imap-proxy.hbs +0 -3
- package/views/config/smtp.hbs +0 -3
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/workers/api.js +93 -134
- package/workers/imap-proxy.js +4 -1
- package/workers/smtp.js +51 -44
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Turns the sources in lib/tls/store.js into something a TLS listener can be handed, and lets a
|
|
4
|
+
// listener swap what it serves without being restarted.
|
|
5
|
+
//
|
|
6
|
+
// Both problems are the same problem. A listener used to bake `cert` and `key` into its options at
|
|
7
|
+
// startup, so a renewed certificate only reached clients when the worker was terminated and
|
|
8
|
+
// respawned - every SMTP submission and every IMAP session in flight was cut for a certificate that
|
|
9
|
+
// had another thirty days on it. A secure context built here can be replaced in place, and the
|
|
10
|
+
// SNI callback reads whatever the latest refresh produced.
|
|
11
|
+
//
|
|
12
|
+
// The same callback is what serves more than one hostname. EmailEngine's admin URL and its mail
|
|
13
|
+
// hostname are usually different names, and a client connecting to smtp.example.com has to be
|
|
14
|
+
// offered a certificate for smtp.example.com, not for the admin UI's.
|
|
15
|
+
//
|
|
16
|
+
// Everything a handshake needs is computed in refresh(): the certificates are parsed once there,
|
|
17
|
+
// not per connection. The SNI callback is on the accept path of the SMTP server, the IMAP proxy
|
|
18
|
+
// and the API's HTTPS listener, so anything it does is done once per client.
|
|
19
|
+
|
|
20
|
+
const tls = require('tls');
|
|
21
|
+
const config = require('@zone-eu/wild-config');
|
|
22
|
+
|
|
23
|
+
const settings = require('../settings');
|
|
24
|
+
const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
|
|
25
|
+
const {
|
|
26
|
+
getCertificateHostnames,
|
|
27
|
+
getManualCertificate,
|
|
28
|
+
getSelfSignedCertificate,
|
|
29
|
+
getAcmeCertificate,
|
|
30
|
+
parseCertificate,
|
|
31
|
+
coversHostname,
|
|
32
|
+
describeX509,
|
|
33
|
+
normalizeHostname
|
|
34
|
+
} = require('./store');
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The certificate plus whatever chain came with it, which is what a TLS context wants.
|
|
38
|
+
*
|
|
39
|
+
* @param {Object} material Resolved material
|
|
40
|
+
* @returns {string} PEM bundle, leaf first
|
|
41
|
+
*/
|
|
42
|
+
function fullChain(material) {
|
|
43
|
+
return material.ca && material.ca.length ? [material.cert].concat(material.ca).join('\n') : material.cert;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
|
|
48
|
+
*
|
|
49
|
+
* Read from the environment and the config file, which every process shares, so the API worker
|
|
50
|
+
* (which builds its listener from it) and the certificate reconciler (which asks whether any
|
|
51
|
+
* listener would serve a certificate) cannot answer differently.
|
|
52
|
+
*
|
|
53
|
+
* @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
|
|
54
|
+
* API serves plain HTTP
|
|
55
|
+
*/
|
|
56
|
+
function apiTlsConfig() {
|
|
57
|
+
return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// How a listener negotiates, as opposed to what it serves. These belong to the listener rather
|
|
61
|
+
// than to any one certificate, and they travel with the resolved options because installing a
|
|
62
|
+
// context replaces it whole: tls.Server.setSecureContext() reverts everything absent from its
|
|
63
|
+
// argument to Node's default, so a reload carrying nothing but a certificate and a key dropped an
|
|
64
|
+
// operator's mTLS `ca` and version bounds at the first renewal. Every context built here is built
|
|
65
|
+
// from the same set, so what a listener installs and what the SNI callback hands back cannot drift.
|
|
66
|
+
//
|
|
67
|
+
// The names are the tls.createSecureContext() ones, which is what lib/tools.js loadTlsConfig()
|
|
68
|
+
// fills in from EENGINE_{API,SMTP,IMAPPROXY}_TLS_* and [api.tls]. `requestCert` and
|
|
69
|
+
// `rejectUnauthorized` are deliberately absent: they are listener options, not context options.
|
|
70
|
+
const HANDSHAKE_KEYS = ['ca', 'ciphers', 'ecdhCurve', 'dhparam', 'minVersion', 'maxVersion', 'honorCipherOrder', 'secureOptions', 'sigalgs', 'crl'];
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Picks the handshake settings out of a listener's TLS options.
|
|
74
|
+
*
|
|
75
|
+
* @param {Object} [source] Listener TLS options
|
|
76
|
+
* @returns {Object} Just the settings a secure context understands
|
|
77
|
+
*/
|
|
78
|
+
function handshakeOptionsFrom(source) {
|
|
79
|
+
const options = {};
|
|
80
|
+
|
|
81
|
+
for (const key of HANDSHAKE_KEYS) {
|
|
82
|
+
if (source && typeof source[key] !== 'undefined' && source[key] !== null) {
|
|
83
|
+
options[key] = source[key];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return options;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Which stored sources the operator's choice admits. The setting is the certificate SOURCE, so it
|
|
91
|
+
// has to decide what is served and not only whether an order is placed: picking "self-signed only"
|
|
92
|
+
// while a Let's Encrypt certificate was still being served is the same class of bug this rework
|
|
93
|
+
// exists to remove - the UI describing behaviour the code does not have.
|
|
94
|
+
//
|
|
95
|
+
// Material from the environment is admitted by every mode. It is not a source EmailEngine chose.
|
|
96
|
+
const MODE_SOURCES = {
|
|
97
|
+
acme: { manual: true, acme: true },
|
|
98
|
+
manual: { manual: true, acme: false },
|
|
99
|
+
'self-signed': { manual: false, acme: false }
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
function sourcesFor(mode) {
|
|
103
|
+
return MODE_SOURCES[mode] || MODE_SOURCES.acme;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Material for one name, in the precedence order lib/tls/store.js documents. The self-signed
|
|
108
|
+
* fallback is not here: it covers every configured name at once and is resolved by the caller when
|
|
109
|
+
* nothing else answered.
|
|
110
|
+
*
|
|
111
|
+
* @param {Object} opts
|
|
112
|
+
* @param {Object} [opts.certs] @postalsys/certs handler, or null to skip the ACME source
|
|
113
|
+
* @param {string} opts.hostname Name being resolved
|
|
114
|
+
* @param {Object} [opts.sources] Which stored sources the configured mode admits
|
|
115
|
+
* @param {Object} [opts.env] Material from the environment or config file
|
|
116
|
+
* @param {Object} [opts.envX509] That certificate, parsed once
|
|
117
|
+
* @param {Object} [opts.manual] Pre-loaded uploaded certificate, so one lookup serves every name
|
|
118
|
+
* @param {Object} [opts.manualX509] That certificate, parsed once
|
|
119
|
+
* @param {Object} [opts.logger] Logger for a stored certificate that could not be read
|
|
120
|
+
* @returns {Promise<Object|false>} Material, or false when only the fallback is left
|
|
121
|
+
*/
|
|
122
|
+
async function resolveHostname(opts) {
|
|
123
|
+
const { certs, hostname, env, envX509, manual, manualX509, logger } = opts;
|
|
124
|
+
const sources = opts.sources || sourcesFor('acme');
|
|
125
|
+
|
|
126
|
+
// An explicit instruction from the operator, and the only source not stored in Redis. Applied
|
|
127
|
+
// per name like every other source: a listener told to serve one certificate should still
|
|
128
|
+
// offer a second configured hostname the certificate that actually covers it.
|
|
129
|
+
if (env && coversHostname(envX509, hostname)) {
|
|
130
|
+
return env;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (sources.manual && manual && coversHostname(manualX509, hostname)) {
|
|
134
|
+
return manual;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (sources.acme) {
|
|
138
|
+
return (await getAcmeCertificate(certs, hostname, logger)) || false;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Builds a listener's TLS material and keeps it refreshable.
|
|
146
|
+
*
|
|
147
|
+
* @param {Object} opts
|
|
148
|
+
* @param {Object} [opts.certs] @postalsys/certs handler
|
|
149
|
+
* @param {Object} opts.logger Worker logger
|
|
150
|
+
* @param {Object} [opts.listenerOptions] The listener's own TLS options: its handshake settings, and
|
|
151
|
+
* the material the environment or config file supplied
|
|
152
|
+
* @param {Object} [opts.envMaterial] That material stated explicitly, when it is not on the listener
|
|
153
|
+
* options: `{ cert, key, ca, passphrase }`
|
|
154
|
+
* @returns {Promise<Object>} `{ options, active, source, refresh() }`
|
|
155
|
+
*/
|
|
156
|
+
async function createTlsContext(opts) {
|
|
157
|
+
const { certs, logger } = opts || {};
|
|
158
|
+
const listenerOptions = (opts && opts.listenerOptions) || null;
|
|
159
|
+
|
|
160
|
+
// Both snapshotted here rather than read per refresh: a listener writes the resolved options
|
|
161
|
+
// back into the same object it passed in, so re-reading it later would mean reading this
|
|
162
|
+
// module's own output back as if the operator had configured it.
|
|
163
|
+
const handshake = handshakeOptionsFrom(listenerOptions);
|
|
164
|
+
const envMaterial =
|
|
165
|
+
(opts && opts.envMaterial) ||
|
|
166
|
+
(listenerOptions ? { cert: listenerOptions.cert, key: listenerOptions.key, ca: listenerOptions.ca, passphrase: listenerOptions.passphrase } : null);
|
|
167
|
+
|
|
168
|
+
// The state the SNI callback reads. Replaced wholesale by refresh(), so a handshake either sees
|
|
169
|
+
// the previous set or the new one, never a half-built one.
|
|
170
|
+
let state = { hostnames: [], entries: [], fallback: null, options: {} };
|
|
171
|
+
|
|
172
|
+
// What one certificate is served with. The passphrase only ever comes from the environment:
|
|
173
|
+
// everything EmailEngine stores is decrypted before it reaches here, and an operator's
|
|
174
|
+
// encrypted key without it fails to load, which used to leave the listener quietly serving the
|
|
175
|
+
// self-signed fallback instead of the certificate it was configured with. It is always set,
|
|
176
|
+
// even when there is none - tls.createSecureContext() treats undefined as absent, and merging
|
|
177
|
+
// this into a listener's own options has to clear a passphrase belonging to material it no
|
|
178
|
+
// longer serves.
|
|
179
|
+
const secureContextOptions = material =>
|
|
180
|
+
Object.assign({}, handshake, { cert: fullChain(material), key: material.privateKey, passphrase: material.passphrase });
|
|
181
|
+
|
|
182
|
+
const buildEntry = (hostname, material) => {
|
|
183
|
+
try {
|
|
184
|
+
return {
|
|
185
|
+
hostname,
|
|
186
|
+
material,
|
|
187
|
+
x509: parseCertificate(material.cert),
|
|
188
|
+
context: tls.createSecureContext(secureContextOptions(material))
|
|
189
|
+
};
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (logger) {
|
|
192
|
+
logger.error({ msg: 'Failed to build a TLS context', hostname, source: material.source, err });
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// Stable across refreshes, so the options object handed to a listener stays valid while the
|
|
199
|
+
// material behind it is replaced.
|
|
200
|
+
const contextFor = servername => {
|
|
201
|
+
const name = normalizeHostname(servername);
|
|
202
|
+
|
|
203
|
+
if (name) {
|
|
204
|
+
const match = state.entries.find(entry => coversHostname(entry.x509, name));
|
|
205
|
+
if (match) {
|
|
206
|
+
return match.context;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return state.fallback && state.fallback.context;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const sniCallback = (servername, cb) => {
|
|
214
|
+
const context = contextFor(servername);
|
|
215
|
+
return typeof cb === 'function' ? cb(null, context) : context;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const refresh = async () => {
|
|
219
|
+
const env =
|
|
220
|
+
envMaterial && envMaterial.cert && envMaterial.key
|
|
221
|
+
? {
|
|
222
|
+
source: 'env',
|
|
223
|
+
cert: envMaterial.cert,
|
|
224
|
+
ca: [].concat(envMaterial.ca || []).filter(entry => entry),
|
|
225
|
+
privateKey: envMaterial.key,
|
|
226
|
+
passphrase: envMaterial.passphrase
|
|
227
|
+
}
|
|
228
|
+
: null;
|
|
229
|
+
const envX509 = env ? parseCertificate(env.cert) : null;
|
|
230
|
+
|
|
231
|
+
// The uploaded certificate is loaded whether or not the environment supplied one: both are
|
|
232
|
+
// applied per name, so a listener pinned to one certificate still has to offer a second
|
|
233
|
+
// configured hostname the uploaded certificate that covers it.
|
|
234
|
+
const [hostnames, mode, manual] = await Promise.all([getCertificateHostnames(), settings.get('tlsProvisioning'), getManualCertificate()]);
|
|
235
|
+
|
|
236
|
+
const sources = sourcesFor(mode);
|
|
237
|
+
const manualX509 = manual ? parseCertificate(manual.cert) : null;
|
|
238
|
+
|
|
239
|
+
// Resolved concurrently: each hostname is an independent pair of Redis reads and a key
|
|
240
|
+
// decrypt, and this runs before the listener binds its port in every worker that serves
|
|
241
|
+
// TLS. Order is preserved, which is what makes entries[0] the primary name.
|
|
242
|
+
const resolved = await Promise.all(hostnames.map(hostname => resolveHostname({ certs, hostname, sources, env, envX509, manual, manualX509, logger })));
|
|
243
|
+
|
|
244
|
+
const entries = [];
|
|
245
|
+
for (let i = 0; i < hostnames.length; i++) {
|
|
246
|
+
if (!resolved[i]) {
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const entry = buildEntry(hostnames[i], resolved[i]);
|
|
250
|
+
if (entry) {
|
|
251
|
+
entries.push(entry);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// The default context answers a client that sent no SNI, and every name nothing else covers.
|
|
256
|
+
// In order: the certificate for the primary name; then material the operator supplied, even
|
|
257
|
+
// when it covers none of the configured names, because they configured this listener with
|
|
258
|
+
// it on purpose; then any certificate at all; then the self-signed fallback, because a
|
|
259
|
+
// listener that has been switched on has to start. Decided before the self-signed entry
|
|
260
|
+
// joins the list, so it stays the last resort for the default context too.
|
|
261
|
+
let fallback = entries.find(entry => coversHostname(entry.x509, hostnames[0])) || null;
|
|
262
|
+
|
|
263
|
+
if (!fallback && env) {
|
|
264
|
+
fallback = buildEntry(hostnames[0] || null, env);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!fallback) {
|
|
268
|
+
fallback = entries[0] || null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The fourth source. The self-signed certificate covers every configured name, and it is
|
|
272
|
+
// the entry for the ones no stored source answers for - not whichever certificate came
|
|
273
|
+
// first, which fails the client's name check just the same and is not what the page says
|
|
274
|
+
// the name has. Generated only when some name needs it: once every name has a certificate
|
|
275
|
+
// of its own there is nothing for it to answer for, and generating it anyway would put a
|
|
276
|
+
// certificate on the page that no listener serves. Material from the environment answers
|
|
277
|
+
// for those names itself, as the default context above: the operator pinned it on purpose.
|
|
278
|
+
const uncovered = env ? [] : hostnames.filter(hostname => !entries.some(entry => coversHostname(entry.x509, hostname)));
|
|
279
|
+
|
|
280
|
+
if (uncovered.length || !fallback) {
|
|
281
|
+
const selfSigned = buildEntry(uncovered[0] || hostnames[0] || null, await getSelfSignedCertificate(hostnames, logger));
|
|
282
|
+
if (selfSigned) {
|
|
283
|
+
entries.push(selfSigned);
|
|
284
|
+
fallback = fallback || selfSigned;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
state = {
|
|
289
|
+
hostnames,
|
|
290
|
+
entries,
|
|
291
|
+
fallback,
|
|
292
|
+
// Built here rather than per read: `cert` and `key` are still set because both mail
|
|
293
|
+
// server libraries assert on them before a handshake happens, and a client that sends
|
|
294
|
+
// no SNI never reaches the callback. The handshake settings come along because a
|
|
295
|
+
// listener installing this replaces its context whole.
|
|
296
|
+
options: fallback ? Object.assign(secureContextOptions(fallback.material), { SNICallback: sniCallback }) : {}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
return state;
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
await refresh();
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
refresh,
|
|
306
|
+
|
|
307
|
+
get options() {
|
|
308
|
+
return state.options;
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
get source() {
|
|
312
|
+
return (state.fallback && state.fallback.material.source) || null;
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
// What the listener is serving, for the admin UI's listener table and the state payload.
|
|
316
|
+
get active() {
|
|
317
|
+
if (!state.fallback) {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// The store's own shape rather than a hand-picked subset of it: the page that renders
|
|
322
|
+
// this reports a certificate that is not valid yet and lists the names it covers, and
|
|
323
|
+
// neither field was here to report.
|
|
324
|
+
return Object.assign(
|
|
325
|
+
{
|
|
326
|
+
source: state.fallback.material.source,
|
|
327
|
+
// Env material is per listener and per process, so the listener is the only
|
|
328
|
+
// thing that knows which of the configured names it serves from it, and the
|
|
329
|
+
// TLS page reads that off this report.
|
|
330
|
+
envHostnames: state.entries.filter(entry => entry.material.source === 'env').map(entry => entry.hostname)
|
|
331
|
+
},
|
|
332
|
+
describeX509(state.fallback.x509) || {}
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Installs whatever the context now resolves to on a running listener.
|
|
340
|
+
*
|
|
341
|
+
* Every TLS listener does the same four things on a reload - refresh, check there is something to
|
|
342
|
+
* serve, hand it over, say what happened - and the last time each of them carried its own copy of a
|
|
343
|
+
* certificate step, the renewal path reloaded the SMTP server and forgot the IMAP proxy for months.
|
|
344
|
+
*
|
|
345
|
+
* @param {Object} opts
|
|
346
|
+
* @param {Object} opts.context Result of createTlsContext(); null when the listener serves no TLS
|
|
347
|
+
* @param {Function} opts.apply Receives the full option set (certificate, key and handshake settings) and installs it
|
|
348
|
+
* @param {Object} opts.logger Worker logger
|
|
349
|
+
* @returns {Promise<Object>} `{ updated, tls }`
|
|
350
|
+
*/
|
|
351
|
+
async function applyTlsContext(opts) {
|
|
352
|
+
const { context, apply, logger } = opts;
|
|
353
|
+
|
|
354
|
+
if (!context) {
|
|
355
|
+
return { updated: false, tls: null };
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
await context.refresh();
|
|
359
|
+
|
|
360
|
+
const options = context.options;
|
|
361
|
+
if (!options.cert || !options.key) {
|
|
362
|
+
logger.error({ msg: 'Refusing to reload TLS certificates, nothing to serve' });
|
|
363
|
+
return { updated: false, tls: null };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Everything, not just the certificate and key: a listener that installs a context from those
|
|
367
|
+
// two alone drops whatever the operator configured for the handshake.
|
|
368
|
+
apply(options);
|
|
369
|
+
|
|
370
|
+
const active = context.active;
|
|
371
|
+
logger.info({ msg: 'Reloaded TLS certificates', source: active && active.source, fingerprint: active && active.fingerprint });
|
|
372
|
+
|
|
373
|
+
return { updated: true, tls: active };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
module.exports = { createTlsContext, applyTlsContext, resolveHostname, sourcesFor, apiTlsConfig };
|
package/lib/tls/der.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Minimal DER writer for the self-signed certificate builder in lib/tls/self-signed.js.
|
|
4
|
+
//
|
|
5
|
+
// EmailEngine needs to mint one X.509 certificate: a short-lived, self-signed leaf that lets a TLS
|
|
6
|
+
// listener start when no real certificate is available. Node's crypto can generate the key pair and
|
|
7
|
+
// produce the signature but cannot assemble a certificate, and every library that can is either
|
|
8
|
+
// unmaintained or several megabytes of ASN.1 machinery for the one structure we emit. This is the
|
|
9
|
+
// subset that structure needs, written so each function maps to a line of RFC 5280.
|
|
10
|
+
//
|
|
11
|
+
// Encoding only. Nothing here parses attacker-controlled input; the one reader (readTlv) walks a
|
|
12
|
+
// SubjectPublicKeyInfo that Node itself produced a moment earlier.
|
|
13
|
+
|
|
14
|
+
const net = require('net');
|
|
15
|
+
const ipaddr = require('ipaddr.js');
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* DER length octets: short form below 128, long form above it.
|
|
19
|
+
*
|
|
20
|
+
* @param {number} length Content length in bytes
|
|
21
|
+
* @returns {Buffer} Encoded length
|
|
22
|
+
*/
|
|
23
|
+
function encodeLength(length) {
|
|
24
|
+
if (length < 0x80) {
|
|
25
|
+
return Buffer.from([length]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const bytes = [];
|
|
29
|
+
let value = length;
|
|
30
|
+
while (value > 0) {
|
|
31
|
+
bytes.unshift(value & 0xff);
|
|
32
|
+
value = Math.floor(value / 256);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return Buffer.from([0x80 | bytes.length, ...bytes]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Tag-length-value, the shape every DER element has.
|
|
40
|
+
*
|
|
41
|
+
* @param {number} tag Identifier octet
|
|
42
|
+
* @param {Buffer|Buffer[]} content Content octets, concatenated when an array
|
|
43
|
+
* @returns {Buffer} Encoded element
|
|
44
|
+
*/
|
|
45
|
+
function tlv(tag, content) {
|
|
46
|
+
const body = Buffer.isBuffer(content) ? content : Buffer.concat(content);
|
|
47
|
+
return Buffer.concat([Buffer.from([tag]), encodeLength(body.length), body]);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const sequence = content => tlv(0x30, content);
|
|
51
|
+
const set = content => tlv(0x31, content);
|
|
52
|
+
const octetString = content => tlv(0x04, content);
|
|
53
|
+
const bitString = content => tlv(0x03, Buffer.concat([Buffer.from([0]), Buffer.isBuffer(content) ? content : Buffer.concat(content)]));
|
|
54
|
+
const boolean = value => tlv(0x01, Buffer.from([value ? 0xff : 0x00]));
|
|
55
|
+
const nullValue = () => tlv(0x05, Buffer.alloc(0));
|
|
56
|
+
const utf8String = value => tlv(0x0c, Buffer.from(value, 'utf-8'));
|
|
57
|
+
|
|
58
|
+
// Constructed context-specific tag, the [n] EXPLICIT of the ASN.1 modules.
|
|
59
|
+
const explicit = (tagNumber, content) => tlv(0xa0 | tagNumber, content);
|
|
60
|
+
|
|
61
|
+
// Primitive context-specific tag, the [n] IMPLICIT that GeneralName uses for its choices.
|
|
62
|
+
const implicit = (tagNumber, content) => tlv(0x80 | tagNumber, content);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A non-negative INTEGER. DER integers are signed, so a value whose top bit is set gains a leading
|
|
66
|
+
* zero octet, and leading zero octets that are not needed are stripped.
|
|
67
|
+
*
|
|
68
|
+
* @param {Buffer|number} value Magnitude, big-endian when a Buffer
|
|
69
|
+
* @returns {Buffer} Encoded INTEGER
|
|
70
|
+
*/
|
|
71
|
+
function integer(value) {
|
|
72
|
+
let bytes;
|
|
73
|
+
|
|
74
|
+
if (typeof value === 'number') {
|
|
75
|
+
bytes = [];
|
|
76
|
+
let remaining = value;
|
|
77
|
+
do {
|
|
78
|
+
bytes.unshift(remaining & 0xff);
|
|
79
|
+
remaining = Math.floor(remaining / 256);
|
|
80
|
+
} while (remaining > 0);
|
|
81
|
+
bytes = Buffer.from(bytes);
|
|
82
|
+
} else {
|
|
83
|
+
bytes = Buffer.from(value);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let start = 0;
|
|
87
|
+
while (start < bytes.length - 1 && bytes[start] === 0 && !(bytes[start + 1] & 0x80)) {
|
|
88
|
+
start++;
|
|
89
|
+
}
|
|
90
|
+
bytes = bytes.subarray(start);
|
|
91
|
+
|
|
92
|
+
if (bytes[0] & 0x80) {
|
|
93
|
+
bytes = Buffer.concat([Buffer.from([0]), bytes]);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return tlv(0x02, bytes);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* An OBJECT IDENTIFIER from its dotted form. The first two arcs share one octet; every later arc is
|
|
101
|
+
* base-128 with the continuation bit set on all but its last octet.
|
|
102
|
+
*
|
|
103
|
+
* @param {string} dotted e.g. "2.5.29.17"
|
|
104
|
+
* @returns {Buffer} Encoded OID
|
|
105
|
+
*/
|
|
106
|
+
function oid(dotted) {
|
|
107
|
+
const arcs = dotted.split('.').map(Number);
|
|
108
|
+
const bytes = [40 * arcs[0] + arcs[1]];
|
|
109
|
+
|
|
110
|
+
for (let i = 2; i < arcs.length; i++) {
|
|
111
|
+
const chunk = [arcs[i] & 0x7f];
|
|
112
|
+
let remaining = Math.floor(arcs[i] / 128);
|
|
113
|
+
while (remaining > 0) {
|
|
114
|
+
chunk.unshift((remaining & 0x7f) | 0x80);
|
|
115
|
+
remaining = Math.floor(remaining / 128);
|
|
116
|
+
}
|
|
117
|
+
bytes.push(...chunk);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return tlv(0x06, Buffer.from(bytes));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A Time, in the representation RFC 5280 requires for the year: UTCTime through 2049,
|
|
125
|
+
* GeneralizedTime from 2050.
|
|
126
|
+
*
|
|
127
|
+
* @param {Date} date The instant to encode
|
|
128
|
+
* @returns {Buffer} Encoded Time
|
|
129
|
+
*/
|
|
130
|
+
function time(date) {
|
|
131
|
+
const pad = value => String(value).padStart(2, '0');
|
|
132
|
+
const year = date.getUTCFullYear();
|
|
133
|
+
const rest = `${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;
|
|
134
|
+
|
|
135
|
+
if (year >= 1950 && year < 2050) {
|
|
136
|
+
return tlv(0x17, Buffer.from(`${pad(year % 100)}${rest}`, 'latin1'));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return tlv(0x18, Buffer.from(`${year}${rest}`, 'latin1'));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A BIT STRING carrying named bits, as KeyUsage does. Trailing unused bits are counted, and DER
|
|
144
|
+
* requires the trailing zero bits to be dropped.
|
|
145
|
+
*
|
|
146
|
+
* @param {number[]} bits Bit numbers to set, counted from the most significant bit of the first octet
|
|
147
|
+
* @returns {Buffer} Encoded BIT STRING
|
|
148
|
+
*/
|
|
149
|
+
function namedBits(bits) {
|
|
150
|
+
const highest = Math.max(...bits);
|
|
151
|
+
const octets = Buffer.alloc(Math.floor(highest / 8) + 1);
|
|
152
|
+
|
|
153
|
+
for (const bit of bits) {
|
|
154
|
+
octets[Math.floor(bit / 8)] |= 0x80 >> (bit % 8);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const unused = 7 - (highest % 8);
|
|
158
|
+
return tlv(0x03, Buffer.concat([Buffer.from([unused]), octets]));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* An IP address as the octet string an iPAddress GeneralName carries: four octets for IPv4, sixteen
|
|
163
|
+
* for IPv6. `::` expansion and IPv4-mapped tails are ipaddr.js's problem, not ours - it is already
|
|
164
|
+
* a dependency and already the address parser everywhere else in the tree.
|
|
165
|
+
*
|
|
166
|
+
* @param {string} address Textual address
|
|
167
|
+
* @returns {Buffer|false} Address octets, or false when the address does not parse
|
|
168
|
+
*/
|
|
169
|
+
function ipToBuffer(address) {
|
|
170
|
+
if (!net.isIP(address)) {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
return Buffer.from(ipaddr.parse(address).toByteArray());
|
|
176
|
+
} catch (err) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Reads one DER element. Used on a SubjectPublicKeyInfo that Node produced, to reach the public key
|
|
183
|
+
* bits the subject key identifier is computed over.
|
|
184
|
+
*
|
|
185
|
+
* @param {Buffer} buf Buffer to read from
|
|
186
|
+
* @param {number} [offset] Where the element starts
|
|
187
|
+
* @returns {Object} `{ tag, contentStart, contentLength, end }`
|
|
188
|
+
*/
|
|
189
|
+
function readTlv(buf, offset = 0) {
|
|
190
|
+
const tag = buf[offset];
|
|
191
|
+
let pos = offset + 1;
|
|
192
|
+
let length = buf[pos++];
|
|
193
|
+
|
|
194
|
+
if (length & 0x80) {
|
|
195
|
+
const count = length & 0x7f;
|
|
196
|
+
length = 0;
|
|
197
|
+
for (let i = 0; i < count; i++) {
|
|
198
|
+
length = length * 256 + buf[pos++];
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return { tag, contentStart: pos, contentLength: length, end: pos + length };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
module.exports = {
|
|
206
|
+
encodeLength,
|
|
207
|
+
tlv,
|
|
208
|
+
sequence,
|
|
209
|
+
set,
|
|
210
|
+
octetString,
|
|
211
|
+
bitString,
|
|
212
|
+
boolean,
|
|
213
|
+
nullValue,
|
|
214
|
+
utf8String,
|
|
215
|
+
explicit,
|
|
216
|
+
implicit,
|
|
217
|
+
integer,
|
|
218
|
+
oid,
|
|
219
|
+
time,
|
|
220
|
+
namedBits,
|
|
221
|
+
ipToBuffer,
|
|
222
|
+
readTlv
|
|
223
|
+
};
|