mirror of
https://github.com/nodejs/node.git
synced 2026-11-24 21:50:36 -05:00
crypto: add strict mode to --force-fips
Allow --force-fips to take an optional provider or strict mode. Keep provider as the current default and explicit compatibility mode. In strict mode, return failure from the OpenSSL 3.4+ FIPS indicator callback when it reports a non-approved operation. Install the callback for enforcement without implicitly enabling diagnostics; --enable-fips-indicator-events remains the independent observation opt-in. Keep the bare form mapped to provider for compatibility, allowing the default to change to strict in a future major release. Preserve the mode when forwarding flags to child test processes, and keep the parser's internal mode storage out of process.allowedNodeEnvironmentFlags. Document the callback scope limitations and cover provider compatibility, validation, synchronous crypto, WebCrypto, Workers, and opt-in event publication. Signed-off-by: Filip Skokan <panva.ip@gmail.com> PR-URL: https://github.com/nodejs/node/pull/65645 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
1 parent
54b3cdb805
commit
3fd905ea8f
11 files changed
+278
-13
No files matched your search
+18
-1
@@ -1580,15 +1580,32 @@ added: v12.12.0
|
||||
|
||||
Disable loading native addons that are not [context-aware][].
|
||||
|
||||
### `--force-fips`
|
||||
### `--force-fips[=mode]`
|
||||
|
||||
<!-- YAML
|
||||
added: v6.0.0
|
||||
changes:
|
||||
- version: REPLACEME
|
||||
pr-url: https://github.com/nodejs/node/pull/65645
|
||||
description: Added the optional `provider` and `strict` modes.
|
||||
-->
|
||||
|
||||
Enable [FIPS mode][] at startup and prevent it from being disabled from script
|
||||
code. The same OpenSSL requirements as [`--enable-fips`][] apply.
|
||||
|
||||
An optional mode can be specified using `--force-fips=mode`:
|
||||
|
||||
* `provider`: Preserve the OpenSSL FIPS provider's configured handling of
|
||||
non-approved operations. This is the current default when the mode is
|
||||
omitted.
|
||||
* `strict`: Reject non-approved operations reported through the OpenSSL FIPS
|
||||
indicator callback. This mode requires OpenSSL 3.4 or later.
|
||||
|
||||
The `strict` mode only covers operations reported through the callback for
|
||||
OpenSSL's default library context. It does not cover native addons that use
|
||||
another `OSSL_LIB_CTX` or another copy of `libcrypto`, nor operation-specific
|
||||
indicators that do not invoke the callback.
|
||||
|
||||
### `--force-node-api-uncaught-exceptions-policy`
|
||||
|
||||
<!-- YAML
|
||||
|
||||
+3
-1
@@ -7211,7 +7211,9 @@ startup. The following controls are also available:
|
||||
* [`--enable-fips`][] and [`--force-fips`][] enable the property query and
|
||||
additionally require the configured provider named `fips` to initialize and
|
||||
pass its self-test. Node.js exits if that check fails. `--force-fips` also
|
||||
prevents FIPS mode from being disabled from script code.
|
||||
prevents FIPS mode from being disabled from script code. With
|
||||
`--force-fips=strict`, Node.js also rejects non-approved operations reported
|
||||
through the OpenSSL FIPS indicator callback.
|
||||
* [`crypto.setFips()`][] changes the FIPS/property-query state. On OpenSSL 3, it
|
||||
does not install, load, initialize, or validate a provider. Implementations
|
||||
fetched before the call are not changed.
|
||||
|
||||
@@ -1583,8 +1583,7 @@ added: REPLACEME
|
||||
* `operation` {string} The provider-defined operation type.
|
||||
* `reason` {string} The provider-defined description of why the operation is
|
||||
not approved.
|
||||
* `blocked` {boolean} Whether a native indicator callback installed before
|
||||
Node.js blocked the operation.
|
||||
* `blocked` {boolean} Whether an indicator callback blocked the operation.
|
||||
* `count` {number} The number of matching pending indicator invocations
|
||||
represented by this message.
|
||||
* `dropped` {number} The number of additional indicator invocations dropped
|
||||
@@ -1602,7 +1601,10 @@ messages are published.
|
||||
|
||||
Subscribing to the channel is observation-only and never changes the result of
|
||||
an operation. Node.js preserves the result from any native indicator callback
|
||||
installed before Node.js initializes its crypto support.
|
||||
installed before Node.js initializes its crypto support. When
|
||||
[`--force-fips=strict`][] is used, Node.js rejects callback-indicated
|
||||
non-approved operations whether or not indicator events are enabled or the
|
||||
channel has subscribers.
|
||||
|
||||
Messages are published asynchronously on the main thread because OpenSSL
|
||||
indicators can originate from Workers or other threads. Only subscriptions on
|
||||
@@ -2026,6 +2028,7 @@ statement, since both are still in use while the event is being delivered; see
|
||||
[TracingChannel Channels]: #tracingchannel-channels
|
||||
[`'uncaughtException'`]: process.md#event-uncaughtexception
|
||||
[`--enable-fips-indicator-events`]: cli.md#--enable-fips-indicator-events
|
||||
[`--force-fips=strict`]: cli.md#--force-fips
|
||||
[`BoundedChannel`]: #class-boundedchannel
|
||||
[`DatabaseSync`]: sqlite.md#class-databasesync
|
||||
[`TracingChannel`]: #class-tracingchannel
|
||||
|
||||
+15
-1
@@ -847,9 +847,23 @@ Enable experimental support for the worker inspection with Chrome DevTools.
|
||||
.It Fl -force-context-aware
|
||||
Disable loading native addons that are not context-aware.
|
||||
.
|
||||
.It Fl -force-fips
|
||||
.It Fl -force-fips Ns = Ns Ar [mode]
|
||||
Enable FIPS mode at startup and prevent it from being disabled from script
|
||||
code. The same OpenSSL requirements as \fB--enable-fips\fR apply.
|
||||
An optional mode can be specified using \fB--force-fips=mode\fR:
|
||||
.Bl -bullet
|
||||
.It
|
||||
\fBprovider\fR: Preserve the OpenSSL FIPS provider's configured handling of
|
||||
non-approved operations. This is the current default when the mode is
|
||||
omitted.
|
||||
.It
|
||||
\fBstrict\fR: Reject non-approved operations reported through the OpenSSL FIPS
|
||||
indicator callback. This mode requires OpenSSL 3.4 or later.
|
||||
.El
|
||||
The \fBstrict\fR mode only covers operations reported through the callback for
|
||||
OpenSSL's default library context. It does not cover native addons that use
|
||||
another \fBOSSL_LIB_CTX\fR or another copy of \fBlibcrypto\fR, nor operation-specific
|
||||
indicators that do not invoke the callback.
|
||||
.
|
||||
.It Fl -force-node-api-uncaught-exceptions-policy
|
||||
Enforces \fBuncaughtException\fR event on Node-API asynchronous callbacks.
|
||||
|
||||
@@ -392,6 +392,9 @@ function buildAllowedFlags() {
|
||||
|
||||
const allowedNodeEnvironmentFlags = [];
|
||||
for (const { 0: name, 1: info } of options) {
|
||||
// Bracketed options are internal parser targets. They can be allowed in
|
||||
// NODE_OPTIONS so aliases expand to them, but are not public flags.
|
||||
if (name[0] === '[') continue;
|
||||
if (info.envVarSettings === kAllowedInEnvvar) {
|
||||
ArrayPrototypePush(allowedNodeEnvironmentFlags, name);
|
||||
if (info.type === kBoolean) {
|
||||
|
||||
@@ -254,6 +254,10 @@ class FipsIndicatorState final {
|
||||
}
|
||||
|
||||
void Install() {
|
||||
reject_unapproved_.store(
|
||||
per_process::cli_options->force_fips_crypto &&
|
||||
per_process::cli_options->force_fips_crypto_policy == "strict",
|
||||
std::memory_order_release);
|
||||
std::call_once(install_once_, [this]() {
|
||||
OSSL_INDICATOR_get_callback(nullptr, &previous_callback_);
|
||||
OSSL_INDICATOR_set_callback(nullptr, OnOpenSSLIndicator);
|
||||
@@ -314,9 +318,12 @@ class FipsIndicatorState final {
|
||||
previous_callback_ == nullptr
|
||||
? 1
|
||||
: previous_callback_(operation, reason, params);
|
||||
if (!active_.load(std::memory_order_acquire)) return previous_result;
|
||||
const int result = reject_unapproved_.load(std::memory_order_acquire)
|
||||
? 0
|
||||
: previous_result;
|
||||
if (!active_.load(std::memory_order_acquire)) return result;
|
||||
|
||||
const bool blocked = previous_result == 0;
|
||||
const bool blocked = result == 0;
|
||||
{
|
||||
Mutex::ScopedLock lock(mutex_);
|
||||
if (env_ != nullptr && active_.load(std::memory_order_relaxed)) {
|
||||
@@ -349,7 +356,7 @@ class FipsIndicatorState final {
|
||||
}
|
||||
}
|
||||
}
|
||||
return previous_result;
|
||||
return result;
|
||||
}
|
||||
|
||||
void Drain(Environment* env) {
|
||||
@@ -404,6 +411,7 @@ class FipsIndicatorState final {
|
||||
|
||||
std::once_flag install_once_;
|
||||
std::atomic<bool> active_{false};
|
||||
std::atomic<bool> reject_unapproved_{false};
|
||||
OSSL_INDICATOR_CALLBACK* previous_callback_ = nullptr;
|
||||
Mutex mutex_;
|
||||
Environment* env_ = nullptr;
|
||||
@@ -419,7 +427,10 @@ class FipsIndicatorState final {
|
||||
|
||||
void InstallFipsIndicatorCallback() {
|
||||
#if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 4)
|
||||
if (per_process::cli_options->enable_fips_indicator_events) {
|
||||
const auto& options = per_process::cli_options;
|
||||
const bool strict = options->force_fips_crypto &&
|
||||
options->force_fips_crypto_policy == "strict";
|
||||
if (options->enable_fips_indicator_events || strict) {
|
||||
FipsIndicatorState::Get().Install();
|
||||
}
|
||||
#endif
|
||||
|
||||
+1
-1
@@ -1254,13 +1254,13 @@ InitializeOncePerProcessInternal(const std::vector<std::string>& args,
|
||||
OPENSSL_init();
|
||||
}
|
||||
#endif
|
||||
crypto::InstallFipsIndicatorCallback();
|
||||
if (auto fips_error = crypto::ProcessFipsOptions()) {
|
||||
result->exit_code_ = ExitCode::kGenericUserError;
|
||||
result->early_return_ = true;
|
||||
result->errors_.emplace_back(std::move(*fips_error));
|
||||
return result;
|
||||
}
|
||||
crypto::InstallFipsIndicatorCallback();
|
||||
|
||||
// Ensure CSPRNG is properly seeded.
|
||||
CHECK(ncrypto::CSPRNG(nullptr, 0));
|
||||
|
||||
+22
-1
@@ -84,11 +84,21 @@ void PerProcessOptions::CheckOptions(std::vector<std::string>* errors,
|
||||
"used, not both");
|
||||
}
|
||||
|
||||
if (force_fips_crypto_policy != "provider" &&
|
||||
force_fips_crypto_policy != "strict") {
|
||||
errors->push_back(
|
||||
"invalid value for --force-fips; expected 'provider' or 'strict'");
|
||||
}
|
||||
|
||||
#if defined(OPENSSL_IS_BORINGSSL) || !OPENSSL_VERSION_PREREQ(3, 4)
|
||||
if (enable_fips_indicator_events) {
|
||||
errors->push_back(
|
||||
"--enable-fips-indicator-events requires OpenSSL 3.4 or later");
|
||||
}
|
||||
|
||||
if (force_fips_crypto && force_fips_crypto_policy == "strict") {
|
||||
errors->push_back("--force-fips=strict requires OpenSSL 3.4 or later");
|
||||
}
|
||||
#endif
|
||||
|
||||
// Any value less than 2 disables use of the secure heap.
|
||||
@@ -1503,9 +1513,14 @@ PerProcessOptionsParser::PerProcessOptionsParser(
|
||||
BOOL_FIELD(enable_fips_indicator_events),
|
||||
kAllowedInEnvvar);
|
||||
AddOption("--force-fips",
|
||||
"force FIPS crypto (cannot be disabled)",
|
||||
"force FIPS crypto (optional mode: provider or strict)",
|
||||
BOOL_FIELD(force_fips_crypto),
|
||||
kAllowedInEnvvar);
|
||||
AddOption("[force_fips_crypto_policy]",
|
||||
"",
|
||||
&PerProcessOptions::force_fips_crypto_policy,
|
||||
kAllowedInEnvvar);
|
||||
AddAlias("--force-fips=", {"[force_fips_crypto_policy]", "--force-fips"});
|
||||
#ifndef V8_ENABLE_SANDBOX
|
||||
AddOption("--secure-heap",
|
||||
"total size of the OpenSSL secure heap",
|
||||
@@ -2105,6 +2120,12 @@ void GetOptionsAsFlags(const FunctionCallbackInfo<Value>& args) {
|
||||
switch (option_info.type) {
|
||||
case kBoolean: {
|
||||
bool current_value = field->GetBool(opts);
|
||||
#if HAVE_OPENSSL
|
||||
if (option_name == "--force-fips" && current_value) {
|
||||
flags.push_back(option_name + "=" + opts->force_fips_crypto_policy);
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
// For boolean options with default_is_true, we want the opposite logic
|
||||
if (option_info.default_is_true) {
|
||||
if (!current_value) {
|
||||
|
||||
@@ -412,6 +412,7 @@ class PerProcessOptions : public Options {
|
||||
DEFINE_BOOL_FIELD(enable_fips_crypto) = false;
|
||||
DEFINE_BOOL_FIELD(enable_fips_indicator_events) = false;
|
||||
DEFINE_BOOL_FIELD(force_fips_crypto) = false;
|
||||
std::string force_fips_crypto_policy = "provider";
|
||||
#endif // HAVE_OPENSSL
|
||||
#if OPENSSL_VERSION_MAJOR >= 3
|
||||
DEFINE_BOOL_FIELD(openssl_legacy_provider) = false;
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
'use strict';
|
||||
|
||||
const common = require('../common');
|
||||
|
||||
if (!common.hasCrypto) {
|
||||
common.skip('missing crypto');
|
||||
}
|
||||
|
||||
if (process.features.openssl_is_boringssl) {
|
||||
common.skip('BoringSSL does not support FIPS');
|
||||
}
|
||||
|
||||
const assert = require('node:assert');
|
||||
const diagnosticsChannel = require('node:diagnostics_channel');
|
||||
const { once } = require('node:events');
|
||||
const { createHmac, subtle } = require('node:crypto');
|
||||
const { Worker } = require('node:worker_threads');
|
||||
const {
|
||||
spawnSyncAndExitWithoutError,
|
||||
} = require('../common/child_process');
|
||||
const { hasFIPS, hasOpenSSL } = require('../common/crypto');
|
||||
|
||||
const channelName = 'crypto.fips.indicator';
|
||||
const mode = process.env.NODE_TEST_FIPS_FORCE_MODE;
|
||||
|
||||
if (!hasOpenSSL(3, 4)) {
|
||||
common.skip('OpenSSL 3.4 or later is required');
|
||||
} else if (!hasFIPS(3, 4)) {
|
||||
common.skip('an active OpenSSL 3.4+ FIPS provider is required');
|
||||
} else if (mode === 'provider') {
|
||||
assertSerializedMode(mode);
|
||||
assert.strictEqual(
|
||||
createHmac('sha256', Buffer.alloc(13)).digest().byteLength, 32);
|
||||
} else if (mode === 'strict') {
|
||||
assertSerializedMode(mode);
|
||||
const subscriber = common.mustNotCall();
|
||||
diagnosticsChannel.subscribe(channelName, subscriber);
|
||||
assert.throws(
|
||||
() => createHmac('sha256', Buffer.alloc(13)).digest(),
|
||||
{ code: /^ERR_OSSL_/ });
|
||||
setImmediate(common.mustCall(() => {
|
||||
assert.strictEqual(
|
||||
diagnosticsChannel.unsubscribe(channelName, subscriber), true);
|
||||
}));
|
||||
} else if (mode === 'strict-events') {
|
||||
assertSerializedMode('strict');
|
||||
testStrictEvents().then(common.mustCall());
|
||||
} else {
|
||||
runParent();
|
||||
}
|
||||
|
||||
function assertSerializedMode(expected) {
|
||||
const { getOptionsAsFlagsFromBinding } = require('internal/options');
|
||||
assert.ok(getOptionsAsFlagsFromBinding().includes(`--force-fips=${expected}`));
|
||||
}
|
||||
|
||||
function nextIndicator() {
|
||||
const keepAlive = setInterval(common.mustNotCall(), 10_000);
|
||||
const { promise, resolve } = Promise.withResolvers();
|
||||
const subscriber = common.mustCall((event, name) => {
|
||||
assert.strictEqual(name, channelName);
|
||||
clearInterval(keepAlive);
|
||||
assert.strictEqual(
|
||||
diagnosticsChannel.unsubscribe(channelName, subscriber), true);
|
||||
resolve(event);
|
||||
});
|
||||
diagnosticsChannel.subscribe(channelName, subscriber);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function runParent() {
|
||||
try {
|
||||
createHmac('sha256', Buffer.alloc(13)).digest();
|
||||
} catch (error) {
|
||||
assert.match(error.code, /^ERR_OSSL_/);
|
||||
common.printSkipMessage(
|
||||
'the FIPS provider rejects unapproved operations before signaling');
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [args, childMode] of [
|
||||
[['--force-fips'], 'provider'],
|
||||
[['--force-fips=provider'], 'provider'],
|
||||
[['--force-fips=strict'], 'strict'],
|
||||
[[
|
||||
'--force-fips=strict',
|
||||
'--enable-fips-indicator-events',
|
||||
], 'strict-events'],
|
||||
]) {
|
||||
spawnSyncAndExitWithoutError(
|
||||
process.execPath, [...args, '--expose-internals', __filename], {
|
||||
env: { ...process.env, NODE_TEST_FIPS_FORCE_MODE: childMode },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function testStrictEvents() {
|
||||
const key = Buffer.alloc(13);
|
||||
|
||||
assert.throws(
|
||||
() => createHmac('sha256', key).digest(),
|
||||
{ code: /^ERR_OSSL_/ });
|
||||
|
||||
let eventPromise = nextIndicator();
|
||||
assert.throws(
|
||||
() => createHmac('sha256', key).digest(),
|
||||
{ code: /^ERR_OSSL_/ });
|
||||
assert.deepStrictEqual(await eventPromise, {
|
||||
operation: 'HMAC',
|
||||
reason: 'keysize',
|
||||
blocked: true,
|
||||
count: 1,
|
||||
dropped: 0,
|
||||
});
|
||||
|
||||
const hmacKey = await subtle.importKey(
|
||||
'raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
||||
eventPromise = nextIndicator();
|
||||
await assert.rejects(
|
||||
subtle.sign('HMAC', hmacKey, Buffer.alloc(0)),
|
||||
{ name: 'OperationError' });
|
||||
const webCryptoEvent = await eventPromise;
|
||||
assert.strictEqual(webCryptoEvent.operation, 'HMAC');
|
||||
assert.strictEqual(webCryptoEvent.reason, 'keysize');
|
||||
assert.strictEqual(webCryptoEvent.blocked, true);
|
||||
|
||||
eventPromise = nextIndicator();
|
||||
const worker = new Worker(`
|
||||
'use strict';
|
||||
const { createHmac } = require('node:crypto');
|
||||
const { workerData } = require('node:worker_threads');
|
||||
createHmac('sha256', workerData.key).digest();
|
||||
`, {
|
||||
eval: true,
|
||||
workerData: { key },
|
||||
});
|
||||
const errorPromise = once(worker, 'error');
|
||||
const exitPromise = new Promise((resolve) => worker.on('exit', resolve));
|
||||
const [[error], workerEvent] = await Promise.all([
|
||||
errorPromise,
|
||||
eventPromise,
|
||||
]);
|
||||
assert.match(error.code, /^ERR_OSSL_/);
|
||||
assert.deepStrictEqual(workerEvent, {
|
||||
operation: 'HMAC',
|
||||
reason: 'keysize',
|
||||
blocked: true,
|
||||
count: 1,
|
||||
dropped: 0,
|
||||
});
|
||||
const exitCode = await exitPromise;
|
||||
assert.strictEqual(exitCode, 1);
|
||||
}
|
||||
@@ -10,10 +10,11 @@ if (process.features.openssl_is_boringssl)
|
||||
const assert = require('assert');
|
||||
const spawnSync = require('child_process').spawnSync;
|
||||
const path = require('path');
|
||||
const { spawnSyncAndAssert } = require('../common/child_process');
|
||||
const fixtures = require('../common/fixtures');
|
||||
const { internalBinding } = require('internal/test/binding');
|
||||
const { testFipsCrypto } = internalBinding('crypto');
|
||||
const { hasOpenSSL3 } = require('../common/crypto');
|
||||
const { hasOpenSSL, hasOpenSSL3 } = require('../common/crypto');
|
||||
|
||||
const FIPS_ENABLED = 1;
|
||||
const FIPS_DISABLED = 0;
|
||||
@@ -94,6 +95,45 @@ testHelper(
|
||||
'require("crypto").getFips()',
|
||||
process.env);
|
||||
|
||||
// Explicit provider mode should preserve the behavior of bare --force-fips.
|
||||
testHelper(
|
||||
testFipsCrypto() ? 'stdout' : 'stderr',
|
||||
['--force-fips=provider'],
|
||||
testFipsCrypto() ? kNoFailure : kGenericUserError,
|
||||
testFipsCrypto() ? FIPS_ENABLED : FIPS_FORCE_ERROR_STRING,
|
||||
'require("crypto").getFips()',
|
||||
process.env);
|
||||
|
||||
{
|
||||
spawnSyncAndAssert(
|
||||
process.execPath, ['--force-fips=invalid', '-e', '0'], {
|
||||
status: 9,
|
||||
stderr: /invalid value for --force-fips; expected 'provider' or 'strict'/,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasOpenSSL(3, 4)) {
|
||||
testHelper(
|
||||
testFipsCrypto() ? 'stdout' : 'stderr',
|
||||
['--force-fips=strict'],
|
||||
testFipsCrypto() ? kNoFailure : kGenericUserError,
|
||||
testFipsCrypto() ? FIPS_ENABLED : FIPS_FORCE_ERROR_STRING,
|
||||
'require("crypto").getFips()',
|
||||
process.env);
|
||||
} else {
|
||||
spawnSyncAndAssert(
|
||||
process.execPath, ['--enable-fips-indicator-events', '-e', '0'], {
|
||||
status: 9,
|
||||
stderr: /--enable-fips-indicator-events requires OpenSSL 3\.4 or later/,
|
||||
});
|
||||
|
||||
spawnSyncAndAssert(
|
||||
process.execPath, ['--force-fips=strict', '-e', '0'], {
|
||||
status: 9,
|
||||
stderr: /--force-fips=strict requires OpenSSL 3\.4 or later/,
|
||||
});
|
||||
}
|
||||
|
||||
// By default FIPS should be off in both FIPS and non-FIPS builds
|
||||
// unless Node.js was configured using --shared-openssl in
|
||||
// which case it may be enabled by the system.
|
||||
|
||||
Reference in new issue
Block a user