emailengine-app 2.72.1 → 2.72.3

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/lib/smtp-auth.js CHANGED
@@ -10,6 +10,7 @@ const { redis } = require('./db');
10
10
  const { Account } = require('./account');
11
11
  const getSecret = require('./get-secret');
12
12
  const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
13
+ const { constantTimeEqual } = require('./tools');
13
14
 
14
15
  /**
15
16
  * Builds the SMTP server onAuth handler.
@@ -28,7 +29,7 @@ function createSmtpAuthHandler({ accountCache, call }) {
28
29
  let account = auth.username;
29
30
 
30
31
  let smtpPassword = await settings.get('smtpServerPassword');
31
- if (!smtpPassword || auth.password !== smtpPassword) {
32
+ if (!smtpPassword || !constantTimeEqual(auth.password, smtpPassword)) {
32
33
  // fall back to API token authentication
33
34
  let result = await validateAuthToken({
34
35
  password: auth.password,
package/lib/sub-script.js CHANGED
@@ -1,5 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ // SECURITY WARNING: SubScript runs operator-authored fn/map/pre-processing code through
4
+ // Node's `vm` module. `vm` is NOT a security sandbox - code executed here can reach the
5
+ // host realm (e.g. via `someHostValue.constructor.constructor('return process')()`) and
6
+ // therefore runs with full server privileges (process env/secrets, host modules, fs).
7
+ // Only trusted operators may author these scripts; never expose script authoring to
8
+ // untrusted principals. Replacing this with a real isolate (isolated-vm) or out-of-process
9
+ // execution is a tracked follow-up (see security review finding C1).
10
+
3
11
  const crypto = require('crypto');
4
12
  const vm = require('vm');
5
13
  const logger = require('./logger');
@@ -73,9 +81,12 @@ class SubScript {
73
81
  }
74
82
 
75
83
  // Allow callers (and tests) to shorten the execution timeout, but never
76
- // raise it above SUBSCRIPT_RUNTIME_TIMEOUT - the sandbox cap is a hard
77
- // ceiling. A falsy override (including 0, which vm treats as "no limit")
78
- // falls back to the default so the cap can never be disabled.
84
+ // raise it above SUBSCRIPT_RUNTIME_TIMEOUT. A falsy override (including 0,
85
+ // which vm treats as "no limit") falls back to the default so the limit can
86
+ // never be disabled. NOTE: vm's `timeout` only interrupts SYNCHRONOUS
87
+ // execution - it does not bound async work, so a script that awaits (or spins
88
+ // the microtask queue) can still run past this limit. It is a coarse guard,
89
+ // not a hard ceiling (see security review finding M8).
79
90
  let runtimeTimeout = options && options.timeout ? Math.min(options.timeout, SUBSCRIPT_RUNTIME_TIMEOUT) : SUBSCRIPT_RUNTIME_TIMEOUT;
80
91
 
81
92
  let start = Date.now();
package/lib/tokens.js CHANGED
@@ -5,6 +5,7 @@ const crypto = require('crypto');
5
5
  const msgpack = require('msgpack5')();
6
6
  const logger = require('./logger');
7
7
  const { REDIS_PREFIX } = require('./consts');
8
+ const { constantTimeEqual } = require('./tools');
8
9
 
9
10
  const SESS_PREFIX = 'sess_';
10
11
 
@@ -64,7 +65,7 @@ module.exports = {
64
65
 
65
66
  const [storedSignature, storedAccount] = storedSignatureValue.split(':');
66
67
 
67
- if (!storedSignature || storedSignature !== expectedSignature) {
68
+ if (!storedSignature || !constantTimeEqual(storedSignature, expectedSignature)) {
68
69
  // Delete invalid tokens
69
70
  await redis.del(key);
70
71
  return false;
package/lib/tools.js CHANGED
@@ -11,7 +11,7 @@ const settings = require('./settings');
11
11
  const { brotliDecompress } = require('zlib');
12
12
  const util = require('util');
13
13
  const brotliDecompressAsync = util.promisify(brotliDecompress);
14
- const { createPublicKey, createVerify, randomBytes, createHmac } = require('crypto');
14
+ const { createPublicKey, createVerify, randomBytes, createHmac, createHash, timingSafeEqual } = require('crypto');
15
15
  const logger = require('./logger');
16
16
  const Boom = require('@hapi/boom');
17
17
  const { ImapFlow } = require('imapflow');
@@ -812,6 +812,26 @@ module.exports = {
812
812
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
813
813
  },
814
814
 
815
+ // Escape Redis glob metacharacters (\ * ? [ ]) so a user-controlled identifier interpolated into
816
+ // a SCAN/KEYS MATCH pattern matches literally and cannot widen the match across the key namespace
817
+ // (security review H2). Intended wildcards in the surrounding pattern are added by the caller and
818
+ // are not passed through here.
819
+ escapeRedisGlob(value) {
820
+ return String(value === null || value === undefined ? '' : value).replace(/[\\*?[\]]/g, '\\$&');
821
+ },
822
+
823
+ // Constant-time comparison of two secret / MAC strings. Both sides are hashed to a fixed-length
824
+ // digest first so timingSafeEqual never sees unequal lengths (which would throw and would leak
825
+ // length via the exception). Returns false for null/undefined (security review L1).
826
+ constantTimeEqual(a, b) {
827
+ if (a === null || a === undefined || b === null || b === undefined) {
828
+ return false;
829
+ }
830
+ const ha = createHash('sha256').update(String(a)).digest();
831
+ const hb = createHash('sha256').update(String(b)).digest();
832
+ return timingSafeEqual(ha, hb);
833
+ },
834
+
815
835
  getRendezvousScore(key, shardId) {
816
836
  return murmurhash(`${(shardId || '').toString()}\x00${key}`);
817
837
  },
@@ -984,6 +1004,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
984
1004
  },
985
1005
 
986
1006
  async verifyAccountInfo(redis, accountData, logger) {
1007
+ // By design this connects to whatever imap/smtp host it is given, with no private/loopback/
1008
+ // reserved-IP filtering: EmailEngine routinely talks to mail servers on any address (incl.
1009
+ // self-hosted boxes on RFC1918 / 127.0.0.1), and it is normally deployed as an isolated
1010
+ // instance with no sensitive internal services to reach. Callers that expose this to
1011
+ // untrusted input gate it upstream (e.g. the hosted form's signed-blob check), and network
1012
+ // isolation - not host filtering here - is the intended SSRF boundary. Do not add an
1013
+ // IP blocklist here without making it opt-in; it would break legitimate local-mail setups.
987
1014
  let response = {};
988
1015
 
989
1016
  let proxyUrl = await settings.get('proxyUrl');
@@ -1679,8 +1706,22 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1679
1706
  async getServiceSecret() {
1680
1707
  let serviceSecret = await settings.get('serviceSecret');
1681
1708
  if (!serviceSecret) {
1709
+ // Mint atomically (HSETNX): unauthenticated tracking/form requests can race to generate
1710
+ // a missing secret, and a plain read-then-write would let the last writer invalidate
1711
+ // whatever the first writer already signed. The loser adopts the winner's secret.
1682
1712
  serviceSecret = randomBytes(16).toString('hex');
1683
- await settings.set('serviceSecret', serviceSecret);
1713
+ let created = await settings.setIfMissing('serviceSecret', serviceSecret);
1714
+ if (!created) {
1715
+ let stored = await settings.get('serviceSecret');
1716
+ if (stored) {
1717
+ serviceSecret = stored;
1718
+ } else {
1719
+ // The field exists but reads back empty/undecryptable (e.g. explicitly blanked
1720
+ // via the settings API): HSETNX cannot heal it, so overwrite - same healing the
1721
+ // previous read-then-write implementation performed.
1722
+ await settings.set('serviceSecret', serviceSecret);
1723
+ }
1724
+ }
1684
1725
  }
1685
1726
  return serviceSecret;
1686
1727
  },
@@ -1732,26 +1773,95 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1732
1773
  return { data: data.toString('base64url'), signature };
1733
1774
  },
1734
1775
 
1735
- async parseSignedFormData(redis, payload, gt) {
1736
- let data = Buffer.from(payload.data, 'base64url').toString();
1737
- let serviceSecret = await settings.get('serviceSecret');
1738
- if (serviceSecret) {
1739
- let hmac = createHmac('sha256', serviceSecret);
1740
- hmac.update(data);
1741
- if (hmac.digest('base64url') !== payload.sig) {
1742
- let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
1743
- throw error;
1776
+ // Fail-closed HMAC check for service-secret-signed blobs, shared by every verification site.
1777
+ // getServiceSecret() generates and persists a secret when missing, so verification is never
1778
+ // silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
1779
+ // only when `sig` matches `data`.
1780
+ //
1781
+ // Reviewed compat note (accepted, do not revert to skip-when-empty): fail-closed means an install
1782
+ // whose stored serviceSecret is currently blank will 403 tracking/unsubscribe links in
1783
+ // already-delivered mail (the old code skipped verification and resolved them, which also accepted
1784
+ // FORGED blobs - the hole this closes). This is documented in the release notes; an operator can
1785
+ // restore the previous secret via the settings API to revive old links. The separate hazard of an
1786
+ // undecryptable-but-present secret being overwritten is PRE-EXISTING (server.js startApplication
1787
+ // re-mints a null-reading secret at boot, before any request), not introduced by this change - so
1788
+ // do not treat it as a regression of this refactor.
1789
+ async verifyServiceSignature(data, sig) {
1790
+ const serviceSecret = await module.exports.getServiceSecret();
1791
+ const hmac = createHmac('sha256', serviceSecret);
1792
+ hmac.update(data);
1793
+ return module.exports.constantTimeEqual(hmac.digest('base64url'), sig);
1794
+ },
1795
+
1796
+ // Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
1797
+ // the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
1798
+ // (lib/ui-routes/account-routes.js) and the OAuth callback claim (workers/api.js) - cannot drift.
1799
+ formNonceKey(n) {
1800
+ return `${REDIS_PREFIX}account:form:${n}`;
1801
+ },
1802
+
1803
+ // Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
1804
+ // claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
1805
+ // - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
1806
+ // Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
1807
+ // guard cannot drift between the two arms; each caller keeps its own Boom 403/500 messages.
1808
+ async claimFormNonce(redis, n, t) {
1809
+ const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
1810
+ return !!claimed;
1811
+ },
1812
+
1813
+ // Release a claimed nonce (best-effort) so the caller can let the user retry after a failed create.
1814
+ // Never throws - a lost release just leaves the nonce consumed for its TTL (the accepted residual of
1815
+ // claim-before-create). Pair with claimFormNonce.
1816
+ async releaseFormNonce(redis, n, logger) {
1817
+ const nonceKey = module.exports.formNonceKey(n);
1818
+ try {
1819
+ await redis.del(nonceKey);
1820
+ } catch (err) {
1821
+ if (logger) {
1822
+ logger.error({ msg: 'Failed to release claimed form nonce', nonceKey, err });
1744
1823
  }
1745
1824
  }
1825
+ },
1826
+
1827
+ async parseSignedFormData(redis, payload, gt, opts) {
1828
+ opts = opts || {};
1829
+
1830
+ let data = Buffer.from(payload.data, 'base64url').toString();
1831
+ if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
1832
+ let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
1833
+ throw error;
1834
+ }
1746
1835
 
1747
1836
  data = JSON.parse(data);
1748
1837
 
1838
+ // Connection-driving / account-creating callers (the IMAP test + server endpoints) require a
1839
+ // single-use nonce so a signed blob cannot be replayed. Blobs issued without n/t (the
1840
+ // unsubscribe and tracking links) are verified by signature only and skip this gate.
1841
+ // NB! this also rejects hosted-form links generated by EmailEngine before v2.39 (those blobs
1842
+ // carry no n/t and never expire) BY DESIGN - a never-expiring signed setup link is exactly
1843
+ // the vulnerability this gate closes. Do not add a legacy bypass; issue a fresh setup link
1844
+ // instead. Warn so support can tell a legacy link from a forgery (the HMAC check above has
1845
+ // already passed at this point).
1846
+ //
1847
+ // Reviewed compat note (kept deliberately, do not "fix"): only the IMAP-arm endpoints pass
1848
+ // requireNonce, so a pre-v2.39 link dead-ends at those POSTs after the user enters credentials -
1849
+ // the accepted cost of closing the replay hole; recovery is re-issuing the link. The OAuth
1850
+ // re-auth path (POST /accounts/new -> accountFormHandler) intentionally does NOT pass
1851
+ // requireNonce, so rolling-upgrade re-auth and legacy OAuth links keep working; that arm's replay
1852
+ // safety is the atomic nonce claim in the OAuth callback (workers/api.js), not this gate.
1853
+ if (opts.requireNonce && (!data.n || !data.t)) {
1854
+ logger.warn({ msg: 'Rejected legacy signed form blob without a nonce (pre-v2.39 setup link)', account: data.account });
1855
+ let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1856
+ throw error;
1857
+ }
1858
+
1749
1859
  if (data.n && data.t) {
1750
1860
  if (data.t < Date.now() - (MAX_FORM_TTL - 60 * 1000)) {
1751
1861
  let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1752
1862
  throw error;
1753
1863
  }
1754
- const nonceSeen = await redis.exists(`${REDIS_PREFIX}account:form:${data.n}`);
1864
+ const nonceSeen = await redis.exists(module.exports.formNonceKey(data.n));
1755
1865
  if (nonceSeen) {
1756
1866
  let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1757
1867
  throw error;