lib/crypto: Add FIPS self-tests for SHA-1 and SHA-2

Add FIPS cryptographic algorithm self-tests for all SHA-1 and SHA-2
algorithms.  Following the "Implementation Guidance for FIPS 140-3"
document, to achieve this it's sufficient to just test a single test
vector for each of HMAC-SHA1, HMAC-SHA256, and HMAC-SHA512.

Just run these tests in the initcalls, following the example of e.g.
crypto/kdf_sp800108.c.  Note that this should meet the FIPS self-test
requirement even in the built-in case, given that the initcalls run
before userspace, storage, network, etc. are accessible.

This does not fix a regression, seeing as lib/ has had SHA-1 support
since 2005 and SHA-256 support since 2018.  Neither ever had FIPS
self-tests.  Moreover, fips=1 support has always been an unfinished
feature upstream.  However, with lib/ now being used more widely, it's
now seeing more scrutiny and people seem to want these now [1][2].

[1] https://lore.kernel.org/r/3226361.1758126043@warthog.procyon.org.uk/
[2] https://lore.kernel.org/r/f31dbb22-0add-481c-aee0-e337a7731f8e@oracle.com/

Reviewed-by: Ard Biesheuvel <ardb@kernel.org>
Link: https://lore.kernel.org/r/20251011001047.51886-1-ebiggers@kernel.org
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
This commit is contained in:
Eric Biggers
2025-10-10 17:10:47 -07:00
parent dcb6fa37fd
commit 04cadb4fe0
5 changed files with 128 additions and 6 deletions

View File

@@ -0,0 +1,32 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Script that generates lib/crypto/fips.h
#
# Copyright 2025 Google LLC
import hmac
fips_test_data = b"fips test data\0\0"
fips_test_key = b"fips test key\0\0\0"
def print_static_u8_array_definition(name, value):
print('')
print(f'static const u8 {name}[] __initconst __maybe_unused = {{')
for i in range(0, len(value), 8):
line = '\t' + ''.join(f'0x{b:02x}, ' for b in value[i:i+8])
print(f'{line.rstrip()}')
print('};')
print('/* SPDX-License-Identifier: GPL-2.0-or-later */')
print(f'/* This file was generated by: gen-fips-testvecs.py */')
print()
print('#include <linux/fips.h>')
print_static_u8_array_definition("fips_test_data", fips_test_data)
print_static_u8_array_definition("fips_test_key", fips_test_key)
for alg in 'sha1', 'sha256', 'sha512':
ctx = hmac.new(fips_test_key, digestmod=alg)
ctx.update(fips_test_data)
print_static_u8_array_definition(f'fips_test_hmac_{alg}_value', ctx.digest())