Files
kernel_arpi/tools/crypto/gen_fips140_testvecs.py
Ard Biesheuvel 2db9143a1b ANDROID: fips140: add kernel crypto module
To meet FIPS 140 requirements, add support for building a kernel module
"fips140.ko" that contains various cryptographic algorithms built from
existing kernel source files.  At load time, the module checks its own
integrity and self-tests its algorithms, then registers the algorithms
with the crypto API to supersede the original algorithms provided by the
kernel itself.

[ebiggers: this commit originated from "ANDROID: crypto: fips140 -
 perform load time integrity check", but I've folded many later commits
 into it to make forward porting easier.  See below]

Original commits from android12-5.10:
  * 6be141eb36 ("ANDROID: crypto: fips140 - perform load time integrity check")
  * 868be244bb ("ANDROID: inject correct HMAC digest into fips140.ko at build time")
  * 091338cb39 ("ANDROID: fips140: add missing static keyword to fips140_init()")
  * c799c6644b ("ANDROID: fips140: adjust some log messages")
  * 92de53472e ("ANDROID: fips140: log already-live algorithms")
  * 0af06624ea ("ANDROID: fips140: check for errors from initcalls")
  * 634445a640 ("ANDROID: fips140: fix deadlock in unregister_existing_fips140_algos()")
  * e886dd4c33 ("ANDROID: fips140: unregister existing DRBG algorithms")
  * b7397e89db ("ANDROID: fips140: add power-up cryptographic self-tests")
  * 50661975be ("ANDROID: fips140: add/update module help text")
  * b397a0387c ("ANDROID: fips140: test all implementations")
  * 17ccefe140 ("ANDROID: fips140: use full 16-byte IV")
  * 1be58af077 ("ANDROID: fips140: remove non-prediction-resistant DRBG test")
  * 2b5843ae2d ("ANDROID: fips140: add AES-CBC-CTS")
  * 2ee56aad31 ("ANDROID: fips140: add AES-CMAC")
  * 960ebb2b56 ("ANDROID: fips140: add jitterentropy to fips140 module")
  * e5b14396f9 ("ANDROID: fips140: take into account AES-GCM not being approvable")
  * 52b70d491b ("ANDROID: fips140: use FIPS140_CFLAGS when compiling fips140-selftests.c")
  * 6b995f5a54 ("ANDROID: fips140: preserve RELA sections without relying on the module loader")
  * e45108ecff ("ANDROID: fips140: block crypto operations until tests complete")
  * ecf9341134 ("ANDROID: fips140: remove in-place updating of live algorithms")
  * 482b0323cf ("ANDROID: fips140: zeroize temporary values from integrity check")
  * 64d769e53f ("ANDROID: fips140: add service indicators")
  * 8d7f609cda ("ANDROID: fips140: add name and version, and a function to retrieve them")
  * 6b7c37f6c4 ("ANDROID: fips140: use UTS_RELEASE as FIPS version")
  * 903e97a0ca ("ANDROID: fips140: refactor evaluation testing support")
  * 97fb2104fe ("ANDROID: fips140: add support for injecting integrity error")
  * 109f31ac23 ("ANDROID: fips140: add userspace interface for evaluation testing")

Bug: 153614920
Bug: 188620248
Test: tested that the module builds and can be loaded on raven.
Change-Id: I3fde49dbc3d16b149b072a27ba5b4c6219015c94
Signed-off-by: Ard Biesheuvel <ardb@google.com>
Signed-off-by: Eric Biggers <ebiggers@google.com>
2022-03-15 21:24:22 +00:00

126 lines
4.3 KiB
Python
Executable File

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
#
# Copyright 2021 Google LLC
#
# Generate most of the test vectors for the FIPS 140 cryptographic self-tests.
#
# Usage:
# tools/crypto/gen_fips140_testvecs.py > crypto/fips140-generated-testvecs.h
#
# Prerequisites:
# Debian: apt-get install python3-pycryptodome python3-cryptography
# Arch Linux: pacman -S python-pycryptodomex python-cryptography
import hashlib
import hmac
import os
import Cryptodome.Cipher.AES
import Cryptodome.Util.Counter
import cryptography.hazmat.primitives.ciphers
import cryptography.hazmat.primitives.ciphers.algorithms
import cryptography.hazmat.primitives.ciphers.modes
scriptname = os.path.basename(__file__)
message = bytes('This is a 32-byte test message.\0', 'ascii')
aes_key = bytes('128-bit AES key\0', 'ascii')
aes_xts_key = bytes('This is an AES-128-XTS key.\0\0\0\0\0', 'ascii')
aes_iv = bytes('ABCDEFGHIJKLMNOP', 'ascii')
assoc = bytes('associated data string', 'ascii')
hmac_key = bytes('128-bit HMAC key', 'ascii')
def warn_generated():
print(f'''/*
* This header was automatically generated by {scriptname}.
* Don't edit it directly.
*/''')
def is_string_value(value):
return (value.isascii() and
all(c == '\x00' or c.isprintable() for c in str(value, 'ascii')))
def format_value(value, is_string):
if is_string:
return value
hexstr = ''
for byte in value:
hexstr += f'\\x{byte:02x}'
return hexstr
def print_value(name, value):
is_string = is_string_value(value)
hdr = f'static const u8 fips_{name}[{len(value)}] __initconst ='
print(hdr, end='')
if is_string:
value = str(value, 'ascii').rstrip('\x00')
chars_per_byte = 1
else:
chars_per_byte = 4
bytes_per_line = 64 // chars_per_byte
if len(hdr) + (chars_per_byte * len(value)) + 4 <= 80:
print(f' "{format_value(value, is_string)}"', end='')
else:
for chunk in [value[i:i+bytes_per_line]
for i in range(0, len(value), bytes_per_line)]:
print(f'\n\t"{format_value(chunk, is_string)}"', end='')
print(';')
print('')
def generate_aes_testvecs():
print_value('aes_key', aes_key)
print_value('aes_iv', aes_iv)
cbc = Cryptodome.Cipher.AES.new(aes_key, Cryptodome.Cipher.AES.MODE_CBC,
iv=aes_iv)
print_value('aes_cbc_ciphertext', cbc.encrypt(message))
ecb = Cryptodome.Cipher.AES.new(aes_key, Cryptodome.Cipher.AES.MODE_ECB)
print_value('aes_ecb_ciphertext', ecb.encrypt(message))
ctr = Cryptodome.Cipher.AES.new(aes_key, Cryptodome.Cipher.AES.MODE_CTR,
nonce=bytes(), initial_value=aes_iv)
print_value('aes_ctr_ciphertext', ctr.encrypt(message))
print_value('aes_gcm_assoc', assoc)
gcm = Cryptodome.Cipher.AES.new(aes_key, Cryptodome.Cipher.AES.MODE_GCM,
nonce=aes_iv[:12], mac_len=16)
gcm.update(assoc)
raw_ciphertext, tag = gcm.encrypt_and_digest(message)
print_value('aes_gcm_ciphertext', raw_ciphertext + tag)
# Unfortunately, pycryptodome doesn't support XTS, so for it we need to use
# a different Python package (the "cryptography" package).
print_value('aes_xts_key', aes_xts_key)
xts = cryptography.hazmat.primitives.ciphers.Cipher(
cryptography.hazmat.primitives.ciphers.algorithms.AES(aes_xts_key),
cryptography.hazmat.primitives.ciphers.modes.XTS(aes_iv)).encryptor()
ciphertext = xts.update(message) + xts.finalize()
print_value('aes_xts_ciphertext', ciphertext)
cmac = Cryptodome.Hash.CMAC.new(aes_key, ciphermod=Cryptodome.Cipher.AES)
cmac.update(message)
print_value('aes_cmac_digest', cmac.digest())
def generate_sha_testvecs():
print_value('hmac_key', hmac_key)
for alg in ['sha1', 'sha256', 'hmac_sha256', 'sha512']:
if alg.startswith('hmac_'):
h = hmac.new(hmac_key, message, alg.removeprefix('hmac_'))
else:
h = hashlib.new(alg, message)
print_value(f'{alg}_digest', h.digest())
print('/* SPDX-License-Identifier: GPL-2.0-only */')
print('/* Copyright 2021 Google LLC */')
print('')
warn_generated()
print('')
print_value('message', message)
generate_aes_testvecs()
generate_sha_testvecs()
warn_generated()