emailengine-app 2.79.9 → 2.80.1
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 +73 -0
- package/README.md +6 -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 +101 -1
- package/lib/api-routes/blocklist-routes.js +24 -0
- package/lib/api-routes/delivery-test-routes.js +6 -0
- package/lib/api-routes/gateway-routes.js +30 -0
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/license-routes.js +10 -0
- package/lib/api-routes/mcp-oauth-routes.js +3 -3
- package/lib/api-routes/mcp-routes.js +39 -21
- package/lib/api-routes/oauth2-app-routes.js +38 -1
- package/lib/api-routes/outbox-routes.js +6 -0
- package/lib/api-routes/permission-map.js +208 -43
- package/lib/api-routes/pubsub-routes.js +8 -0
- package/lib/api-routes/route-helpers.js +58 -11
- package/lib/api-routes/settings-routes.js +67 -6
- package/lib/api-routes/stats-routes.js +6 -0
- package/lib/api-routes/template-routes.js +21 -0
- package/lib/api-routes/token-routes.js +34 -2
- package/lib/api-routes/webhook-route-routes.js +13 -0
- 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 +238 -67
- package/lib/email-client/credential-errors.js +122 -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/login-failure.js +52 -0
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +17 -12
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +139 -101
- 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/enum-descriptions.js +12 -2
- 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/mcp/oauth.js +46 -8
- package/lib/mcp/protocol.js +78 -35
- package/lib/mcp/tools.js +53 -17
- package/lib/privileged-settings.js +147 -0
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +92 -16
- package/lib/security-headers.js +15 -0
- package/lib/settings.js +13 -0
- package/lib/tls/catalog.js +428 -0
- package/lib/tls/context.js +302 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/listeners.js +62 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +480 -0
- package/lib/tls/store.js +667 -0
- package/lib/token-permission-view.js +252 -102
- package/lib/token-permissions.js +176 -26
- package/lib/tokens.js +7 -6
- package/lib/tools.js +73 -27
- package/lib/ui-routes/account-routes.js +43 -30
- package/lib/ui-routes/admin-config-routes.js +63 -22
- package/lib/ui-routes/admin-entities-routes.js +23 -13
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +72 -31
- package/lib/ui-routes/network-config-routes.js +54 -45
- package/lib/ui-routes/tls-config-routes.js +628 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/package.json +12 -12
- package/sbom.json +1 -1
- package/server.js +23 -1
- 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 +97 -61
- package/static/licenses.html +341 -1252
- package/translations/messages.pot +62 -56
- package/views/account/login-redirect.hbs +22 -0
- package/views/account/passkeys.hbs +2 -2
- package/views/accounts/account.hbs +2 -2
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +88 -52
- package/views/config/network.hbs +1 -1
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +593 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +6 -6
- package/views/layout/login.hbs +5 -5
- package/views/layout/main.hbs +2 -2
- package/views/layout/prompt.hbs +3 -3
- package/views/layout/public.hbs +1 -1
- package/views/mcp/authorize.hbs +47 -45
- package/views/partials/ace_assets.hbs +1 -1
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/mcp_access_levels.hbs +16 -9
- package/views/partials/mcp_tool_count.hbs +15 -14
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +1 -1
- package/views/partials/theme_init.hbs +1 -1
- 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/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/index.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/reference/tag.hbs +1 -1
- package/views/reference/token.hbs +1 -1
- package/views/templates/template.hbs +1 -1
- package/views/tokens/new.hbs +175 -74
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +1 -1
- package/workers/api.js +102 -142
- 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,302 @@
|
|
|
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
|
+
// Which certificate answers which name, and which one is the listener's default, is decided by
|
|
17
|
+
// lib/tls/catalog.js (listenerView()); this module only turns that view into secure contexts.
|
|
18
|
+
//
|
|
19
|
+
// Everything a handshake needs is computed in refresh(): the certificates are parsed once there,
|
|
20
|
+
// not per connection. The SNI callback is on the accept path of the SMTP server, the IMAP proxy
|
|
21
|
+
// and the API's HTTPS listener, so anything it does is done once per client.
|
|
22
|
+
|
|
23
|
+
const tls = require('tls');
|
|
24
|
+
const config = require('@zone-eu/wild-config');
|
|
25
|
+
|
|
26
|
+
const settings = require('../settings');
|
|
27
|
+
const { hasEnvValue, readEnvValue, getBoolean } = require('../tools');
|
|
28
|
+
const { hostnamesFrom, getSelfSignedCertificate, parseCertificate, describeX509 } = require('./store');
|
|
29
|
+
const { TLS_CERTIFICATE_SETTINGS, SELF_SIGNED_ID, listenerByKey } = require('./listeners');
|
|
30
|
+
const { sourcesFor, listCertificates, entryForName, listenerView } = require('./catalog');
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The certificate plus whatever chain came with it, which is what a TLS context wants.
|
|
34
|
+
*
|
|
35
|
+
* @param {Object} material Resolved material
|
|
36
|
+
* @returns {string} PEM bundle, leaf first
|
|
37
|
+
*/
|
|
38
|
+
function fullChain(material) {
|
|
39
|
+
return material.ca && material.ca.length ? [material.cert].concat(material.ca).join('\n') : material.cert;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Whether, and how, the API listener serves TLS: EENGINE_API_TLS and `[api.tls]`.
|
|
44
|
+
*
|
|
45
|
+
* Read from the environment and the config file, which every process shares, so the API worker
|
|
46
|
+
* (which builds its listener from it) and the certificate reconciler (which asks whether any
|
|
47
|
+
* listener would serve a certificate) cannot answer differently.
|
|
48
|
+
*
|
|
49
|
+
* @returns {Object|false} The `[api.tls]` options to build the listener from, or false when the
|
|
50
|
+
* API serves plain HTTP
|
|
51
|
+
*/
|
|
52
|
+
function apiTlsConfig() {
|
|
53
|
+
return hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// How a listener negotiates, as opposed to what it serves. These belong to the listener rather
|
|
57
|
+
// than to any one certificate, and they travel with the resolved options because installing a
|
|
58
|
+
// context replaces it whole: tls.Server.setSecureContext() reverts everything absent from its
|
|
59
|
+
// argument to Node's default, so a reload carrying nothing but a certificate and a key dropped an
|
|
60
|
+
// operator's mTLS `ca` and version bounds at the first renewal. Every context built here is built
|
|
61
|
+
// from the same set, so what a listener installs and what the SNI callback hands back cannot drift.
|
|
62
|
+
//
|
|
63
|
+
// The names are the tls.createSecureContext() ones, which is what lib/tools.js loadTlsConfig()
|
|
64
|
+
// fills in from EENGINE_{API,SMTP,IMAPPROXY}_TLS_* and [api.tls]. `requestCert` and
|
|
65
|
+
// `rejectUnauthorized` are deliberately absent: they are listener options, not context options.
|
|
66
|
+
const HANDSHAKE_KEYS = ['ca', 'ciphers', 'ecdhCurve', 'dhparam', 'minVersion', 'maxVersion', 'honorCipherOrder', 'secureOptions', 'sigalgs', 'crl'];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Picks the handshake settings out of a listener's TLS options.
|
|
70
|
+
*
|
|
71
|
+
* @param {Object} [source] Listener TLS options
|
|
72
|
+
* @returns {Object} Just the settings a secure context understands
|
|
73
|
+
*/
|
|
74
|
+
function handshakeOptionsFrom(source) {
|
|
75
|
+
const options = {};
|
|
76
|
+
|
|
77
|
+
for (const key of HANDSHAKE_KEYS) {
|
|
78
|
+
if (source && typeof source[key] !== 'undefined' && source[key] !== null) {
|
|
79
|
+
options[key] = source[key];
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return options;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Builds a listener's TLS material and keeps it refreshable.
|
|
88
|
+
*
|
|
89
|
+
* @param {Object} opts
|
|
90
|
+
* @param {Object} [opts.certs] @postalsys/certs handler
|
|
91
|
+
* @param {Object} opts.logger Worker logger
|
|
92
|
+
* @param {string} [opts.listener] Which listener this is (`api`, `smtp`, `imapProxy`): whose
|
|
93
|
+
* environment material is its own, and which setting holds the
|
|
94
|
+
* certificate it presents by default
|
|
95
|
+
* @param {Object} [opts.listenerOptions] The listener's own TLS options, for the handshake
|
|
96
|
+
* settings (ciphers, version bounds, a client CA). The
|
|
97
|
+
* certificate material in them is read from the environment
|
|
98
|
+
* by the catalog instead, so every worker sees the same bytes
|
|
99
|
+
* @returns {Promise<Object>} `{ options, active, source, refresh() }`
|
|
100
|
+
*/
|
|
101
|
+
async function createTlsContext(opts) {
|
|
102
|
+
const { certs, logger } = opts || {};
|
|
103
|
+
const listener = (opts && listenerByKey(opts.listener)) || null;
|
|
104
|
+
|
|
105
|
+
// Snapshotted here rather than read per refresh: a listener writes the resolved options back
|
|
106
|
+
// into the same object it passed in, so re-reading it later would mean reading this module's
|
|
107
|
+
// own output back as if the operator had configured it.
|
|
108
|
+
const handshake = handshakeOptionsFrom((opts && opts.listenerOptions) || null);
|
|
109
|
+
|
|
110
|
+
// The state the SNI callback reads. Replaced wholesale by refresh(), so a handshake either sees
|
|
111
|
+
// the previous set or the new one, never a half-built one.
|
|
112
|
+
let state = { hostnames: [], entries: [], fallback: null, options: {} };
|
|
113
|
+
|
|
114
|
+
// What one certificate is served with. The passphrase only ever comes from the environment:
|
|
115
|
+
// everything EmailEngine stores is decrypted before it reaches here, and an operator's
|
|
116
|
+
// encrypted key without it fails to load, which used to leave the listener quietly serving the
|
|
117
|
+
// self-signed fallback instead of the certificate it was configured with. It is always set,
|
|
118
|
+
// even when there is none - tls.createSecureContext() treats undefined as absent, and merging
|
|
119
|
+
// this into a listener's own options has to clear a passphrase belonging to material it no
|
|
120
|
+
// longer serves.
|
|
121
|
+
const secureContextOptions = material =>
|
|
122
|
+
Object.assign({}, handshake, { cert: fullChain(material), key: material.privateKey, passphrase: material.passphrase });
|
|
123
|
+
|
|
124
|
+
// A catalog entry with a context built for it. The self-signed entry is listed without
|
|
125
|
+
// material until something needs it, and generated material may be newer than what the
|
|
126
|
+
// catalog peeked, so the material is parsed again here rather than taken off the entry.
|
|
127
|
+
const buildEntry = (entry, material) => {
|
|
128
|
+
try {
|
|
129
|
+
return {
|
|
130
|
+
id: entry.id,
|
|
131
|
+
material,
|
|
132
|
+
x509: parseCertificate(material.cert),
|
|
133
|
+
context: tls.createSecureContext(secureContextOptions(material))
|
|
134
|
+
};
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (logger) {
|
|
137
|
+
logger.error({ msg: 'Failed to build a TLS context', id: entry.id, source: material.source, err });
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// Stable across refreshes, so the options object handed to a listener stays valid while the
|
|
144
|
+
// material behind it is replaced. The rule is entryForName(): the default certificate for
|
|
145
|
+
// every name it covers and for a client that names none, otherwise the certificate resolved
|
|
146
|
+
// for the name, otherwise the default again.
|
|
147
|
+
const contextFor = servername => {
|
|
148
|
+
const entry = entryForName(servername, state);
|
|
149
|
+
return entry ? entry.context : null;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const sniCallback = (servername, cb) => {
|
|
153
|
+
const context = contextFor(servername);
|
|
154
|
+
return typeof cb === 'function' ? cb(null, context) : context;
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const refresh = async () => {
|
|
158
|
+
const values = await settings.getMulti('serviceUrl', 'tlsHostnames', 'tlsProvisioning', ...TLS_CERTIFICATE_SETTINGS);
|
|
159
|
+
|
|
160
|
+
const hostnames = hostnamesFrom(values);
|
|
161
|
+
|
|
162
|
+
// Everything the instance holds, with keys: this is the one read of the stores per
|
|
163
|
+
// refresh, and it runs before the listener binds its port
|
|
164
|
+
const catalog = await listCertificates({ certs, hostnames, logger, withPrivateKey: true });
|
|
165
|
+
|
|
166
|
+
const view = listenerView({
|
|
167
|
+
catalog,
|
|
168
|
+
hostnames,
|
|
169
|
+
sources: sourcesFor(values.tlsProvisioning),
|
|
170
|
+
listener: listener && listener.key,
|
|
171
|
+
requested: listener ? values[listener.settingKey] : null
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
if (view.selection === 'missing' && logger) {
|
|
175
|
+
logger.warn({
|
|
176
|
+
msg: 'The certificate this listener was told to present no longer exists, presenting the automatic choice',
|
|
177
|
+
listener: listener && listener.key,
|
|
178
|
+
requested: view.requested,
|
|
179
|
+
fallback: view.fallback && view.fallback.id
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Generated only when something needs it - as the default, or for a name nothing else
|
|
184
|
+
// covers: once every name has a certificate of its own there is nothing for it to answer
|
|
185
|
+
// for, and generating it anyway would put a certificate on the page that no listener
|
|
186
|
+
// serves. The store hands back what it holds, or replaces one that no longer covers the
|
|
187
|
+
// configured names.
|
|
188
|
+
let selfSigned = view.needsSelfSigned ? await getSelfSignedCertificate(hostnames, logger) : null;
|
|
189
|
+
const materialOf = entry => (entry.id === SELF_SIGNED_ID ? selfSigned : entry.material);
|
|
190
|
+
|
|
191
|
+
const built = new Map();
|
|
192
|
+
const build = entry => {
|
|
193
|
+
if (!entry || !materialOf(entry)) {
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
if (!built.has(entry.id)) {
|
|
197
|
+
built.set(entry.id, buildEntry(entry, materialOf(entry)));
|
|
198
|
+
}
|
|
199
|
+
return built.get(entry.id);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
let fallback = build(view.fallback);
|
|
203
|
+
|
|
204
|
+
// A default whose context cannot be built - an encrypted operator key with no passphrase
|
|
205
|
+
// - has been reported above; the listener still starts, on the fallback, rather than
|
|
206
|
+
// refusing to bind with nothing to serve
|
|
207
|
+
if (!fallback) {
|
|
208
|
+
selfSigned = selfSigned || (await getSelfSignedCertificate(hostnames, logger));
|
|
209
|
+
fallback = build(catalog.find(entry => entry.id === SELF_SIGNED_ID));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const entries = view.entries.map(build).filter(entry => entry);
|
|
213
|
+
|
|
214
|
+
state = {
|
|
215
|
+
hostnames,
|
|
216
|
+
entries,
|
|
217
|
+
fallback,
|
|
218
|
+
// Built here rather than per read: `cert` and `key` are still set because both mail
|
|
219
|
+
// server libraries assert on them before a handshake happens, and a client that sends
|
|
220
|
+
// no SNI never reaches the callback. The handshake settings come along because a
|
|
221
|
+
// listener installing this replaces its context whole.
|
|
222
|
+
options: fallback ? Object.assign(secureContextOptions(fallback.material), { SNICallback: sniCallback }) : {}
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
return state;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
await refresh();
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
refresh,
|
|
232
|
+
|
|
233
|
+
get options() {
|
|
234
|
+
return state.options;
|
|
235
|
+
},
|
|
236
|
+
|
|
237
|
+
get source() {
|
|
238
|
+
return (state.fallback && state.fallback.material.source) || null;
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
// What the listener is serving by default, for the admin UI's listener table and the state
|
|
242
|
+
// payload. The store's own shape rather than a hand-picked subset of it: the page that
|
|
243
|
+
// renders this reports a certificate that is not valid yet and lists the names it covers.
|
|
244
|
+
get active() {
|
|
245
|
+
if (!state.fallback) {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const material = state.fallback.material;
|
|
250
|
+
return Object.assign(
|
|
251
|
+
{
|
|
252
|
+
id: state.fallback.id,
|
|
253
|
+
source: material.source,
|
|
254
|
+
// What the id is made of, so a page can name the certificate without the store
|
|
255
|
+
listener: material.listener || null,
|
|
256
|
+
hostname: material.hostname || null
|
|
257
|
+
},
|
|
258
|
+
describeX509(state.fallback.x509) || {}
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Installs whatever the context now resolves to on a running listener.
|
|
266
|
+
*
|
|
267
|
+
* Every TLS listener does the same four things on a reload - refresh, check there is something to
|
|
268
|
+
* serve, hand it over, say what happened - and the last time each of them carried its own copy of a
|
|
269
|
+
* certificate step, the renewal path reloaded the SMTP server and forgot the IMAP proxy for months.
|
|
270
|
+
*
|
|
271
|
+
* @param {Object} opts
|
|
272
|
+
* @param {Object} opts.context Result of createTlsContext(); null when the listener serves no TLS
|
|
273
|
+
* @param {Function} opts.apply Receives the full option set (certificate, key and handshake settings) and installs it
|
|
274
|
+
* @param {Object} opts.logger Worker logger
|
|
275
|
+
* @returns {Promise<Object>} `{ updated, tls }`
|
|
276
|
+
*/
|
|
277
|
+
async function applyTlsContext(opts) {
|
|
278
|
+
const { context, apply, logger } = opts;
|
|
279
|
+
|
|
280
|
+
if (!context) {
|
|
281
|
+
return { updated: false, tls: null };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
await context.refresh();
|
|
285
|
+
|
|
286
|
+
const options = context.options;
|
|
287
|
+
if (!options.cert || !options.key) {
|
|
288
|
+
logger.error({ msg: 'Refusing to reload TLS certificates, nothing to serve' });
|
|
289
|
+
return { updated: false, tls: null };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Everything, not just the certificate and key: a listener that installs a context from those
|
|
293
|
+
// two alone drops whatever the operator configured for the handshake.
|
|
294
|
+
apply(options);
|
|
295
|
+
|
|
296
|
+
const active = context.active;
|
|
297
|
+
logger.info({ msg: 'Reloaded TLS certificates', source: active && active.source, fingerprint: active && active.fingerprint });
|
|
298
|
+
|
|
299
|
+
return { updated: true, tls: active };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
module.exports = { createTlsContext, applyTlsContext, 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
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The listeners that terminate TLS, and the grammar of a certificate id. Nothing else: this is
|
|
4
|
+
// required by lib/tools.js (the reload contract), lib/schemas.js (the settings schema) and
|
|
5
|
+
// lib/tls/catalog.js alike, so it must not require any of them back.
|
|
6
|
+
//
|
|
7
|
+
// Ids are stable strings, because they are stored in settings and posted by forms:
|
|
8
|
+
//
|
|
9
|
+
// env:api, env:smtp, env:imapProxy material from that listener's environment prefix or the
|
|
10
|
+
// config file
|
|
11
|
+
// manual the certificate uploaded through the admin UI
|
|
12
|
+
// acme:<hostname> the Let's Encrypt certificate for that configured name
|
|
13
|
+
// self-signed the generated fallback covering every configured name
|
|
14
|
+
//
|
|
15
|
+
// `auto` is not an id: it is what a listener's setting holds when EmailEngine is to decide.
|
|
16
|
+
|
|
17
|
+
// In the order the page lists them. `settingKey` holds the id of the certificate that listener
|
|
18
|
+
// presents by default; `envPrefix` is where its own operator-supplied material comes from.
|
|
19
|
+
const LISTENERS = Object.freeze([
|
|
20
|
+
Object.freeze({
|
|
21
|
+
key: 'api',
|
|
22
|
+
name: 'Admin UI and API',
|
|
23
|
+
// No page of its own: TLS for this listener is an environment switch, not a setting
|
|
24
|
+
configuredAt: null,
|
|
25
|
+
envPrefix: 'EENGINE_API_TLS_',
|
|
26
|
+
envNote: 'EENGINE_API_TLS_* or [api.tls] in the config file',
|
|
27
|
+
settingKey: 'apiTLSCertificate'
|
|
28
|
+
}),
|
|
29
|
+
Object.freeze({
|
|
30
|
+
key: 'smtp',
|
|
31
|
+
name: 'SMTP server',
|
|
32
|
+
configuredAt: '/admin/config/smtp',
|
|
33
|
+
envPrefix: 'EENGINE_SMTP_TLS_',
|
|
34
|
+
envNote: 'EENGINE_SMTP_TLS_*',
|
|
35
|
+
settingKey: 'smtpServerTLSCertificate'
|
|
36
|
+
}),
|
|
37
|
+
Object.freeze({
|
|
38
|
+
key: 'imapProxy',
|
|
39
|
+
name: 'IMAP proxy',
|
|
40
|
+
configuredAt: '/admin/config/imap-proxy',
|
|
41
|
+
envPrefix: 'EENGINE_IMAPPROXY_TLS_',
|
|
42
|
+
envNote: 'EENGINE_IMAPPROXY_TLS_*',
|
|
43
|
+
settingKey: 'imapProxyServerTLSCertificate'
|
|
44
|
+
})
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
// The settings that name each listener's default certificate
|
|
48
|
+
const TLS_CERTIFICATE_SETTINGS = Object.freeze(LISTENERS.map(listener => listener.settingKey));
|
|
49
|
+
|
|
50
|
+
const AUTO = 'auto';
|
|
51
|
+
const MANUAL_ID = 'manual';
|
|
52
|
+
const SELF_SIGNED_ID = 'self-signed';
|
|
53
|
+
|
|
54
|
+
// What a setting may hold. The acme part is a hostname the way the certificate stores spell one,
|
|
55
|
+
// lower-cased; the listener part is case-sensitive because the ids are, and a form never types them.
|
|
56
|
+
const CERTIFICATE_ID_PATTERN = /^(auto|manual|self-signed|env:(api|smtp|imapProxy)|acme:[a-z0-9._:-]+)$/;
|
|
57
|
+
|
|
58
|
+
function listenerByKey(key) {
|
|
59
|
+
return LISTENERS.find(listener => listener.key === key) || null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { LISTENERS, TLS_CERTIFICATE_SETTINGS, AUTO, MANUAL_ID, SELF_SIGNED_ID, CERTIFICATE_ID_PATTERN, listenerByKey };
|