Skip to content

Commit 7fc7465

Browse files
committed
feat(express): add default domain-scoped CA trust for BitGo connections
Restrict outbound HTTPS connections to official BitGo domains (*.bitgo.com, *.bitgo-test.com, *.bitgo-staging.com, *.bitgo-dev.com, and their apex domains) to a bundled multi-provider root CA store (Google Trust Services, Amazon Trust Services, DigiCert, Let's Encrypt/ISRG, and Sectigo) while keeping the system trust store for all non-BitGo destinations: - sdk-api: add createBitGoTlsPolicy({ ca, hosts }) and enforce it in BitGoAPI.getAgentRequest (refusing redirects and plain http on covered hosts) - express: enable the bundled 18-root CA policy by default at startup, with a single opt-out flag (--disablepincerts / BITGO_DISABLE_PIN_CERTS) and automatic proxy fallback when BITGO_USE_PROXY is set - scripts/verify-bitgo-policy-data.sh: CI check verifying all bundled roots are self-signed, valid (>30d), and cover all BitGo domains (plus --live handshake verification) TICKET: WCN-3731
1 parent 42039fb commit 7fc7465

17 files changed

Lines changed: 1173 additions & 4 deletions

‎modules/express/.env.example‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,4 @@ BITGO_EXTERNAL_SIGNER_WALLET_IDS=
3737

3838
# Examples
3939
# BITGO_EXTERNAL_SIGNER_WALLET_IDS="{"tbtc":[{"walletId":"xxx","walletPassword":"xxx","secret":"xxx"}],"hteth":["walletId":"xxx","walletPassword":"xxx"]}"
40+
BITGO_DISABLE_PIN_CERTS=

‎modules/express/README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,19 @@ BitGo Express currently supports the following proxy protocols:
196196
- SOCKSv5
197197
- PAC
198198

199+
### Domain-scoped CA trust for BitGo connections
200+
201+
By default, BitGo Express restricts outbound HTTPS connections to official BitGo domains (`*.bitgo.com`, `*.bitgo-test.com`, `*.bitgo-staging.com`, `*.bitgo-dev.com`, and their apex domains) to a bundled set of root certificate authorities (`modules/express/bitgo-ca.pem`: Google Trust Services, Amazon Trust Services, DigiCert, Let's Encrypt/ISRG, and Sectigo). Every other outbound destination (external signer, block explorers, webhooks, KMS) continues to use the Node.js / system trust store.
202+
203+
This is **enabled by default** to shrink the blast radius of a compromise of any unrelated CA in the global trust store without requiring manual certificate-pin maintenance across routine BitGo certificate renewals or CA migrations.
204+
205+
- To opt out, pass `--disablepincerts` or set `BITGO_DISABLE_PIN_CERTS=true`.
206+
- When `BITGO_USE_PROXY` is set, Express logs a startup warning and skips the bundled CA policy because the proxy agent owns the TLS connection.
207+
- Redirects are not followed on covered BitGo hostnames so a redirect cannot move a request outside the domain policy; plain `http://` to a covered BitGo hostname is refused.
208+
- At startup, Express warns if any root CA in `bitgo-ca.pem` expires within 30 days.
209+
210+
> The underlying policy helper (`createBitGoTlsPolicy` in `@bitgo/sdk-api`) is Node-only: it relies on the Node `crypto` and `tls` modules and refuses to build in a browser bundle.
211+
199212
### External Signing Mode
200213

201214
BitGo Express can be run in an external signing mode, where the signing of transactions is performed in a separate instance of BitGo Express that has access to the private keys.
@@ -239,6 +252,7 @@ BitGo Express is able to take configuration options from either command line arg
239252
| N/A | --lightningSignerFileSystemPath | `BITGO_LIGHTNING_SIGNER_FILE_SYSTEM_PATH` | N/A | Local path specifying how to contact the lightning signer node. |
240253
| N/A | --keepalivetimeout | `BITGO_KEEP_ALIVE_TIMEOUT` | N/A | BitGo Express server KeepAliveTimeout node. |
241254
| N/A | --headerstimeout | `BITGO_HEADERS_TIMEOUT` | N/A | BitGo Express server HeadersTimeout node. |
255+
| N/A | --disablepincerts | `BITGO_DISABLE_PIN_CERTS` <sup>0</sup> | false | Disable the default domain-scoped CA bundle restriction for BitGo hostnames. See [Domain-scoped CA trust for BitGo connections](#domain-scoped-ca-trust-for-bitgo-connections). |
242256

243257
\[0]: BitGo will also check the additional environment variables for some options for backwards compatibility, but these environment variables should be considered deprecated:
244258

‎modules/express/bitgo-ca.pem‎

Lines changed: 381 additions & 0 deletions
Large diffs are not rendered by default.

‎modules/express/package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
},
2222
"scripts": {
2323
"test": "yarn unit-test",
24-
"unit-test": "yarn nyc -- mocha",
24+
"unit-test": "yarn test:data && yarn nyc -- mocha",
2525
"integration-test": "yarn nyc -- mocha \"test/integration/**/*.ts\"",
2626
"clean": "rm -rf dist/*",
2727
"prepare": "yarn build",
@@ -34,7 +34,8 @@
3434
"build-docker": "cd ../../ && yarn update-dockerfile && ./scripts/build-docker-express.sh",
3535
"check-fmt": "yarn prettier --check '{src,test}/**/*.{ts,js,json}'",
3636
"unprettied": "grep -R -L --include '*.ts' --include '*.js' --include '*.json' '@prettier' src test",
37-
"fmt": "yarn prettier --write '{src,test}/**/*.{ts,js,json}'"
37+
"fmt": "yarn prettier --write '{src,test}/**/*.{ts,js,json}'",
38+
"test:data": "bash ../../scripts/verify-bitgo-policy-data.sh"
3839
},
3940
"dependencies": {
4041
"@api-ts/io-ts-http": "^3.2.1",

‎modules/express/src/args.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ parser.addArgument(['--disableenvcheck'], {
8484
help: 'disable checking for proper NODE_ENV when running in prod environment',
8585
});
8686

87+
parser.addArgument(['--disablepincerts'], {
88+
action: 'storeConst',
89+
constant: true,
90+
help: 'disable the default domain-scoped CA bundle restriction for BitGo hostnames',
91+
});
92+
8793
parser.addArgument(['-t', '--timeout'], {
8894
help: 'Proxy server timeout in milliseconds',
8995
});

‎modules/express/src/clientRoutes.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import {
6666
import { handlePayLightningInvoice } from './lightning/lightningInvoiceRoutes';
6767
import { handleUpdateLightningWalletCoinSpecific } from './lightning/lightningWalletRoutes';
6868
import { ProxyAgent } from 'proxy-agent';
69+
import { getBitGoTlsPolicy } from './tlsPolicy';
6970
import { isLightningCoinName } from '@bitgo/abstract-lightning';
7071
import { handleLightningWithdraw } from './lightning/lightningWithdrawRoutes';
7172
import createExpressRouter from './typedRoutes';
@@ -1807,6 +1808,7 @@ function parseBody(req: express.Request, res: express.Response, next: express.Ne
18071808
*/
18081809
function prepareBitGo(config: Config) {
18091810
const { env, customRootUri, customBitcoinNetwork } = config;
1811+
const tlsPolicy = getBitGoTlsPolicy(config);
18101812

18111813
return function prepBitGo(req: express.Request, res: express.Response, next: express.NextFunction) {
18121814
// Get access token
@@ -1828,6 +1830,7 @@ function prepareBitGo(config: Config) {
18281830
customBitcoinNetwork,
18291831
accessToken,
18301832
userAgent,
1833+
tlsPolicy,
18311834
...(useProxyUrl
18321835
? {
18331836
customProxyAgent: new ProxyAgent({

‎modules/express/src/config.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export interface Config {
3333
disableSSL: boolean;
3434
disableProxy: boolean;
3535
disableEnvCheck: boolean;
36+
disablePinCerts?: boolean;
3637
timeout: number;
3738
customRootUri?: string;
3839
customBitcoinNetwork?: V1Network;
@@ -59,6 +60,7 @@ export const ArgConfig = (args): Partial<Config> => ({
5960
disableSSL: args.disablessl,
6061
disableProxy: args.disableproxy,
6162
disableEnvCheck: args.disableenvcheck,
63+
disablePinCerts: args.disablepincerts,
6264
timeout: args.timeout,
6365
customRootUri: args.customrooturi,
6466
customBitcoinNetwork: args.custombitcoinnetwork,
@@ -85,6 +87,7 @@ export const EnvConfig = (): Partial<Config> => ({
8587
disableSSL: readEnvVar('BITGO_DISABLE_SSL', 'BITGO_DISABLESSL', 'DISABLESSL', 'DISABLE_SSL') ? true : undefined,
8688
disableProxy: readEnvVar('BITGO_DISABLE_PROXY', 'DISABLE_PROXY') ? true : undefined,
8789
disableEnvCheck: readEnvVar('BITGO_DISABLE_ENV_CHECK', 'DISABLE_ENV_CHECK') ? true : undefined,
90+
disablePinCerts: readEnvVar('BITGO_DISABLE_PIN_CERTS', 'DISABLE_PIN_CERTS') ? true : undefined,
8891
timeout: Number(readEnvVar('BITGO_TIMEOUT')),
8992
customRootUri: readEnvVar('BITGO_CUSTOM_ROOT_URI'),
9093
customBitcoinNetwork: readEnvVar('BITGO_CUSTOM_BITCOIN_NETWORK') as V1Network,
@@ -108,6 +111,7 @@ export const DefaultConfig: Config = {
108111
// BG-9584: temporarily disable env check while we give users time to react to change in runtime behavior
109112
// This will require a major version bump, since this is a breaking change to default behavior.
110113
disableEnvCheck: true,
114+
disablePinCerts: false,
111115
timeout: 305 * 1000,
112116
authVersion: 2,
113117
};
@@ -171,6 +175,7 @@ function mergeConfigs(...configs: Partial<Config>[]): Config {
171175
disableSSL,
172176
disableProxy: get('disableProxy'),
173177
disableEnvCheck: get('disableEnvCheck'),
178+
disablePinCerts: get('disablePinCerts'),
174179
timeout: get('timeout'),
175180
customRootUri: customRootUri || undefined,
176181
customBitcoinNetwork: get('customBitcoinNetwork'),

‎modules/express/src/expressApp.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828

2929
import { Environments } from 'bitgo';
3030
import * as clientRoutes from './clientRoutes';
31+
import { getBitGoTlsPolicy } from './tlsPolicy';
3132

3233
/**
3334
* Set up the logging middleware provided by morgan
@@ -267,6 +268,9 @@ function checkPreconditions(config: Config) {
267268
if (lightningSignerFileSystemPath !== undefined) {
268269
checkJsonFilePath(lightningSignerFileSystemPath);
269270
}
271+
272+
// Fail fast on TLS policy misconfiguration before the server listens.
273+
getBitGoTlsPolicy(config);
270274
}
271275

272276
export function setupRoutes(app: express.Application, config: Config): void {

‎modules/express/src/tlsPolicy.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import * as fs from 'fs';
2+
import * as path from 'path';
3+
import debugLib from 'debug';
4+
import { BitGoTlsPolicy, createBitGoTlsPolicy, getCaExpiries } from 'bitgo';
5+
import { Config } from './config';
6+
import { TlsConfigurationError } from './errors';
7+
8+
const debug = debugLib('bitgo:express');
9+
10+
/**
11+
* Official BitGo domain patterns covered by the default CA bundle restriction.
12+
* Covers apex and all subdomains (`app.*`, `admin.*`, `cdn.*`, etc.) across prod, test, staging, and dev.
13+
*/
14+
export const BITGO_DEFAULT_TLS_HOSTS: string[] = [
15+
'bitgo.com',
16+
'.bitgo.com',
17+
'bitgo-test.com',
18+
'.bitgo-test.com',
19+
'bitgo-staging.com',
20+
'.bitgo-staging.com',
21+
'bitgo-dev.com',
22+
'.bitgo-dev.com',
23+
];
24+
25+
function resolveBundledCaPath(): string {
26+
const candidates = [path.resolve(__dirname, '../bitgo-ca.pem'), path.resolve(__dirname, '../../bitgo-ca.pem')];
27+
const found = candidates.find((p) => fs.existsSync(p));
28+
if (!found) {
29+
throw new TlsConfigurationError(`Bundled BitGo CA file not found (searched: ${candidates.join(', ')})`);
30+
}
31+
return found;
32+
}
33+
34+
// Read the baked-in bundle once at module load so we don't re-read from disk on every config
35+
// or collide with unit tests that stub fs.readFileSync for signer config files.
36+
const BUNDLED_CA_PEM = fs.readFileSync(resolveBundledCaPath(), 'utf8');
37+
38+
const policies = new WeakMap<Config, BitGoTlsPolicy | undefined>();
39+
40+
/**
41+
* Logs the policy summary to debug, plus a console.warn per bundle CA expiring within 30 days, so an operator
42+
* can update Express before a bundled root CA expiry breaks connections.
43+
*/
44+
function logPolicyStatus(hosts: string[], ca: string | Buffer | Array<string | Buffer>): void {
45+
const expiries = getCaExpiries(ca);
46+
debug('BitGo TLS policy enabled for %d host pattern(s), %d CA(s)', hosts.length, expiries.length);
47+
for (const expiry of expiries) {
48+
if (expiry.daysRemaining < 30) {
49+
const when =
50+
expiry.daysRemaining < 0
51+
? `expired ${-expiry.daysRemaining} day(s) ago`
52+
: `expires in ${expiry.daysRemaining} day(s)`;
53+
console.warn(
54+
`BitGo TLS policy CA '${
55+
expiry.subject
56+
}' ${when} (${expiry.validTo.toISOString()}); update @bitgo/express to refresh the bundled CA roots`
57+
);
58+
}
59+
}
60+
}
61+
62+
/**
63+
* Builds (once per config) the default outbound TLS policy for BitGo hostnames using the bundled multi-provider
64+
* CA store (`bitgo-ca.pem`), or returns undefined when disabled via `disablePinCerts` (`--disablepincerts` /
65+
* `BITGO_DISABLE_PIN_CERTS`) or when `BITGO_USE_PROXY` is set.
66+
*/
67+
export function getBitGoTlsPolicy(config: Config, caBundlePath?: string): BitGoTlsPolicy | undefined {
68+
if (!caBundlePath && policies.has(config)) {
69+
return policies.get(config);
70+
}
71+
72+
if (config.disablePinCerts) {
73+
policies.set(config, undefined);
74+
return undefined;
75+
}
76+
77+
if (process.env.BITGO_USE_PROXY) {
78+
console.warn(
79+
'warning: BitGo TLS CA pinning is skipped because BITGO_USE_PROXY is set; the proxy agent owns the TLS connection.'
80+
);
81+
policies.set(config, undefined);
82+
return undefined;
83+
}
84+
85+
let policy: BitGoTlsPolicy;
86+
try {
87+
const ca = caBundlePath ? fs.readFileSync(caBundlePath) : BUNDLED_CA_PEM;
88+
policy = createBitGoTlsPolicy({ ca, hosts: BITGO_DEFAULT_TLS_HOSTS });
89+
logPolicyStatus(BITGO_DEFAULT_TLS_HOSTS, ca);
90+
} catch (err) {
91+
throw err instanceof TlsConfigurationError ? err : new TlsConfigurationError((err as Error).message);
92+
}
93+
94+
if (!caBundlePath) {
95+
policies.set(config, policy);
96+
}
97+
return policy;
98+
}

‎modules/express/test/unit/config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ describe('Config:', () => {
119119
BITGO_DISABLE_SSL: 'envdisableSSL',
120120
BITGO_DISABLE_PROXY: 'envdisableProxy',
121121
BITGO_DISABLE_ENV_CHECK: 'envdisableEnvCheck',
122+
BITGO_DISABLE_PIN_CERTS: 'envdisablePinCerts',
122123
BITGO_TIMEOUT: 'envtimeout',
123124
BITGO_CUSTOM_ROOT_URI: 'envcustomRootUri',
124125
BITGO_CUSTOM_BITCOIN_NETWORK: 'envcustomBitcoinNetwork',
@@ -145,6 +146,7 @@ describe('Config:', () => {
145146
disablessl: 'argdisableSSL',
146147
disableproxy: 'argdisableProxy',
147148
disableenvcheck: 'argdisableEnvCheck',
149+
disablepincerts: 'argdisablePinCerts',
148150
timeout: 'argtimeout',
149151
customrooturi: 'argcustomRootUri',
150152
custombitcoinnetwork: 'argcustomBitcoinNetwork',
@@ -174,6 +176,7 @@ describe('Config:', () => {
174176
disableSSL: 'argdisableSSL',
175177
disableProxy: 'argdisableProxy',
176178
disableEnvCheck: 'argdisableEnvCheck',
179+
disablePinCerts: 'argdisablePinCerts',
177180
timeout: 'argtimeout',
178181
customRootUri: 'https://argcustomRootUri',
179182
customBitcoinNetwork: 'argcustomBitcoinNetwork',
@@ -278,6 +281,7 @@ describe('Config:', () => {
278281
should.not.exist(parsed.disablessl);
279282
should.not.exist(parsed.disableenvcheck);
280283
should.not.exist(parsed.disableproxy);
284+
should.not.exist(parsed.disablepincerts);
281285
argvStub.restore();
282286
});
283287
});

0 commit comments

Comments
 (0)