Crypto keys and module signing
Subsystems (6)
David Howells
maintainercover Crypto keys and module signing
Okay Rusty,
Here's a set of patches that does module signing attaching the signature in the way you wanted. I do not agree with doing it this way. However, as you insisted rather forcefully...
===============
<<< WARNING >>>
===============
Anyone wanting to use the module signing facility contained in these patches MUST FIRST make sure that modules are not stripped after being signed. This includes by packaging systems (such as rpmbuild) extracting debug information and due to size reduction for initramfs composition.
This is likely to require alterations to userspace packages, both on the build machine and the installed machine.
If the module is passed through strip, but the signature is _not_ discarded, then the module load will be rejected, potentially resulting in an unbootable machine. If you are in FIPS mode the kernel will panic.
To make the modules more usable from an initramfs (which may have limited capacity), the module files are maximally stripped (by both strip -x -g and eu-strip) before being signed. This appears to result in the smallest, still-viable module possible.
However, all debug information is discarded, along with chunks of the symbol and string tables that might otherwise be useful. An unstripped, unsigned copy of the module is left in the build tree (called foo.ko.unsigned) that should be usable for debugging purposes.
The extended module file format is as follows:
The module signature is appended to the end of the module file, followed by "@mod_size@\n@sig_size@\nThis Is A Crypto Signed Module".
The EOF must follow the magic string directly, so nothing further must be appended to the file.
mod_size and sig_size are left-aligned decimal numbers, space-padded to 8 characters. mod_size is the size of the module payload part of the file and sig_size is the size of the signature blob.
Note the first patch is a bugfix to kernel/module.c (look for "Guard check in module loader against integer overflow").
The patches can also be found here:
David
---
Changes made 22/05/2012:
(*) Fixes for the PGP/keys handling parts:
- Fix some checkpatch noise [Thanks to Tetsuo Handa].
- Preclear array on stack [Thanks to Tetsuo Handa].
- Check (sub)packet length [Thanks to Stephan Mueller].
- Decrease (not increase) remnant length in signature parsing.
- Handle new-format 5-octet length encoding.
- Better report encounter of Partial Body Length spec.
- Adjust the error handling.
(*) Completely redo how signature is attached to the module file to comply
with Rusty's specified method. Also pre-strip modules.
(*) Drop the MPILIB extra-exports patch as it's only required for the DSA
algorithm.
Changes made 10/05/2012:
(*) Overhauled the ELF checking code and module signing code.
- Moved into one file.
- Removed a lot of redundant ELF checks, relying a lot on the signature to catch stuff.
- Rearranged the ELF checker function.
- Commented thoroughly and documented things better in the commit messages.
- Made it possible to exclude REL or RELA relocation handling.
- Rearranged the modsign patch subset to be more logical.
- Massively reduced the code size.
(*) Applied a patch to handle short signatures.
(*) Fixed a potential overflow in a check in the core module code.
Changes made 07/12/2011:
(*) Dropped the DSA algorithm.
Changes made 02/12/2011:
(*) Completely overhauled the architecture.
- Introduced data parsers.
- Reduced subtype to cryptographic data carrier.
- Extracted out the common PGP bits of DSA and RSA algorithms.
- Defined an asymmetric public-key subtype.
- Reduced DSA and RSA algorithms to minimum.
- Rolled verification initiation and key selection together into one.
- Moved verification add_data/finish/cancel op pointers into verification context.
Changes made 29/11/2011:
(*) Added RSA signature verification.
(*) Stopped signature verification crashing on unsupported hash algorithm.
(*) Fixed ENOMEM handling bug in MPI.
(*) Worked around ccache problems with compilation of PGP public keyring into
kernel (ccache hashes the preprocessor output, but the assembler includes the binary data, so ccache doesn't see that it changed).
(*) Added a choice in kernel config for hash algorithm to use; forced the
appropriate crypto module to be built directly into the kernel.
(*) Cleaned out some debugging code.
(*) Updated documentation.
---
David Howells (23):
MODSIGN: Panic the kernel if FIPS is enabled upon module signing failure
MODSIGN: Automatically generate module signing keys if missing
MODSIGN: Module signature verification
MODSIGN: Provide module signing public keys to the kernel
MODSIGN: Sign modules during the build process
MODSIGN: Provide Documentation and Kconfig options
MODSIGN: Provide gitignore and make clean rules for extra files
KEYS: Provide a function to load keys from a PGP keyring blob
KEYS: PGP format signature parser
KEYS: PGP-based public key signature verification
KEYS: PGP data parser
PGPLIB: Signature parser
PGPLIB: Basic packet parser
PGPLIB: PGP definitions (RFC 4880)
Fix signature verification for shorter signatures
KEYS: RSA signature verification algorithm
KEYS: Asymmetric public-key algorithm crypto key subtype
KEYS: Add signature verification facility
KEYS: Create a key type that can be used for general cryptographic operations
KEYS: Reorganise keys Makefile
KEYS: Announce key type (un)registration
KEYS: Move the key config into security/keys/Kconfig
Guard check in module loader against integer overflow
.gitignore | 13 + Documentation/module-signing.txt | 183 +++++++++++ Documentation/security/keys-crypto.txt | 302 ++++++++++++++++++ Makefile | 1 include/keys/crypto-subtype.h | 77 ++++ include/keys/crypto-type.h | 37 ++ include/linux/modsign.h | 27 ++ include/linux/module.h | 3 include/linux/pgp.h | 255 +++++++++++++++ init/Kconfig | 62 ++++ kernel/Makefile | 42 ++ kernel/modsign-pubkey.c | 74 ++++ kernel/module-verify.c | 153 +++++++++ kernel/module-verify.h | 20 + kernel/module.c | 29 +- net/dns_resolver/dns_key.c | 5 scripts/Makefile.modpost | 98 ++++++ security/Kconfig | 68 ---- security/keys/Kconfig | 73 ++++ security/keys/Makefile | 13 + security/keys/crypto/Kconfig | 51 +++ security/keys/crypto/Makefile | 17 + security/keys/crypto/crypto_keys.h | 28 ++ security/keys/crypto/crypto_rsa.c | 290 +++++++++++++++++ security/keys/crypto/crypto_type.c | 228 +++++++++++++ security/keys/crypto/crypto_verify.c | 111 ++++++ security/keys/crypto/pgp_key_parser.c | 347 ++++++++++++++++++++ security/keys/crypto/pgp_library.c | 550 ++++++++++++++++++++++++++++++++ security/keys/crypto/pgp_parser.h | 35 ++ security/keys/crypto/pgp_preload.c | 90 +++++ security/keys/crypto/pgp_pubkey_sig.c | 324 +++++++++++++++++++ security/keys/crypto/pgp_sig_parser.c | 113 +++++++ security/keys/crypto/public_key.c | 55 +++ security/keys/crypto/public_key.h | 108 ++++++ security/keys/key.c | 3 35 files changed, 3803 insertions(+), 82 deletions(-) create mode 100644 Documentation/module-signing.txt create mode 100644 Documentation/security/keys-crypto.txt create mode 100644 include/keys/crypto-subtype.h create mode 100644 include/keys/crypto-type.h create mode 100644 include/linux/modsign.h create mode 100644 include/linux/pgp.h create mode 100644 kernel/modsign-pubkey.c create mode 100644 kernel/module-verify.c create mode 100644 kernel/module-verify.h create mode 100644 security/keys/Kconfig create mode 100644 security/keys/crypto/Kconfig create mode 100644 security/keys/crypto/Makefile create mode 100644 security/keys/crypto/crypto_keys.h create mode 100644 security/keys/crypto/crypto_rsa.c create mode 100644 security/keys/crypto/crypto_type.c create mode 100644 security/keys/crypto/crypto_verify.c create mode 100644 security/keys/crypto/pgp_key_parser.c create mode 100644 security/keys/crypto/pgp_library.c create mode 100644 security/keys/crypto/pgp_parser.h create mode 100644 security/keys/crypto/pgp_preload.c create mode 100644 security/keys/crypto/pgp_pubkey_sig.c create mode 100644 security/keys/crypto/pgp_sig_parser.c create mode 100644 security/keys/crypto/public_key.c create mode 100644 security/keys/crypto/public_key.h
David Howells
maintainerPATCH 1/23 Guard check in module loader against integer overflow
The check:
if (len < hdr->e_shoff + hdr->e_shnum * sizeof(Elf_Shdr))
may not work if there's an overflow in the right-hand side of the condition.
---
kernel/module.c | 3 ++- 1 files changed, 2 insertions(+), 1 deletions(-)
kernel/module.c +2 -1
@@ -2429,7 +2429,8 @@ static int copy_and_check(struct load_info *info, goto free_hdr; } -if (len < hdr->e_shoff + hdr->e_shnum *sizeof (Elf_Shdr)) { +if (hdr->e_shoff >= len || + hdr->e_shnum *sizeof (Elf_Shdr) > len - hdr->e_shoff) { err = -ENOEXEC ; goto free_hdr; }
David Howells
maintainerPATCH 2/23 KEYS: Move the key config into security/keys/Kconfig
In reply to David HowellsMove the key config into security/keys/Kconfig as there are going to be a lot of key-related options.
---
security/Kconfig | 68 +---------------------------------------------- security/keys/Kconfig | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 67 deletions(-) create mode 100644 security/keys/Kconfig
security/Kconfig +1 -67
@@ -4,73 +4,7 @@ menu "Security options" -config KEYS - bool "Enable access key retention support" - help - This option provides support for retaining authentication tokens and - access keys in the kernel. - - It also includes provision of methods by which such keys might be - associated with a process so that network filesystems, encryption - support and the like can find them. - - Furthermore, a special type of key is available that acts as keyring: - a searchable sequence of keys. Each process is equipped with access - to five standard keyrings: UID-specific, GID-specific, session, - process and thread. - - If you are unsure as to whether this is required, answer N. - -config TRUSTED_KEYS - tristate "TRUSTED KEYS" - depends on KEYS && TCG_TPM - select CRYPTO - select CRYPTO_HMAC - select CRYPTO_SHA1 - help - This option provides support for creating, sealing, and unsealing - keys in the kernel. Trusted keys are random number symmetric keys, - generated and RSA-sealed by the TPM. The TPM only unseals the keys, - if the boot PCRs and other criteria match. Userspace will only ever - see encrypted blobs. - - If you are unsure as to whether this is required, answer N. - -config ENCRYPTED_KEYS - tristate "ENCRYPTED KEYS" - depends on KEYS - select CRYPTO - select CRYPTO_HMAC - select CRYPTO_AES - select CRYPTO_CBC - select CRYPTO_SHA256 - select CRYPTO_RNG - help - This option provides support for create/encrypting/decrypting keys - in the kernel. Encrypted keys are kernel generated random numbers, - which are encrypted/decrypted with a 'master' symmetric key. The - 'master' key can be either a trusted-key or user-key type. - Userspace only ever sees/stores encrypted blobs. - - If you are unsure as to whether this is required, answer N. - -config KEYS_DEBUG_PROC_KEYS - bool "Enable the /proc/keys file by which keys may be viewed" - depends on KEYS - help - This option turns on support for the /proc/keys file - through which - can be listed all the keys on the system that are viewable by the - reading process. - - The only keys included in the list are those that grant View - permission to the reading process whether or not it possesses them. - Note that LSM security checks are still performed, and may further - filter out keys that the current process is not authorised to view. - - Only key attributes are listed here; key payloads are not included in - the resulting table. - - If you are unsure as to whether this is required, answer N. +source security/keys/Kconfig config SECURITY_DMESG_RESTRICT bool "Restrict unprivileged access to the kernel syslog"
security/keys/Kconfig new file +71 -0
71 lines not on this page · raw message
David Howells
maintainerPATCH 3/23 KEYS: Announce key type (un)registration
In reply to David HowellsAnnounce the (un)registration of a key type in the core key code rather than in the callers.
---
net/dns_resolver/dns_key.c | 5 ----- security/keys/key.c | 3 +++ 2 files changed, 3 insertions(+), 5 deletions(-)
net/dns_resolver/dns_key.c +0 -5
@@ -249,9 +249,6 @@ static int __init init_dns_resolver(void)struct key *keyring;int ret; -printk (KERN_NOTICE "Registering the %s key type\n" , - key_type_dns_resolver.name); -/* create an override credential set with a special thread keyring in * which DNS requests are cached *
@@ -301,8 +298,6 @@ static void __exit exit_dns_resolver(void)key_revoke (dns_resolver_cache->thread_keyring);unregister_key_type (&key_type_dns_resolver);put_cred (dns_resolver_cache); -printk (KERN_NOTICE "Unregistered %s key type\n" , - key_type_dns_resolver.name); }module_init (init_dns_resolver)
security/keys/key.c +3 -0
@@ -980,6 +980,8 @@ int register_key_type(struct key_type *ktype)/* store the type */ list_add (&ktype->link, &key_types_list); + +pr_notice ("Key type %s registered\n" , ktype->name); ret =0 ; out:
@@ -1002,6 +1004,7 @@ void unregister_key_type(struct key_type *ktype)list_del_init (&ktype->link);downgrade_write (&key_types_sem);key_gc_keytype (ktype); +pr_notice ("Key type %s unregistered\n" , ktype->name);up_read (&key_types_sem); }EXPORT_SYMBOL (unregister_key_type);
David Howells
maintainerPATCH 4/23 KEYS: Reorganise keys Makefile
In reply to David HowellsReorganise the keys directory Makefile to put all the core bits together and the type-specific bits after.
---
security/keys/Makefile | 12 +++++++++--- 1 files changed, 9 insertions(+), 3 deletions(-)
security/keys/Makefile +9 -3
@@ -2,6 +2,9 @@ # Makefile for key management # +# +# Core +# obj-y := \ gc.o \ key.o \
@@ -12,9 +15,12 @@ obj-y := \ request_key.o \ request_key_auth.o \ user_defined.o - -obj-$(CONFIG_TRUSTED_KEYS) += trusted.o -obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/ obj-$(CONFIG_KEYS_COMPAT) += compat.o obj-$(CONFIG_PROC_FS) += proc.o obj-$(CONFIG_SYSCTL) += sysctl.o + +# +# Key types +# +obj-$(CONFIG_TRUSTED_KEYS) += trusted.o +obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/
David Howells
maintainerPATCH 5/23 KEYS: Create a key type that can be used for general cryptographic operations
In reply to David HowellsCreate a key type that can be used for general cryptographic operations, such as encryption, decryption, signature generation and signature verification.
The key type is "crypto" and can provide access to a variety of cryptographic algorithms.
---
Documentation/security/keys-crypto.txt | 181 +++++++++++++++++++++++++ include/keys/crypto-subtype.h | 56 ++++++++ include/keys/crypto-type.h | 25 ++++ security/keys/Kconfig | 2 security/keys/Makefile | 1 security/keys/crypto/Kconfig | 7 + security/keys/crypto/Makefile | 7 + security/keys/crypto/crypto_keys.h | 28 ++++ security/keys/crypto/crypto_type.c | 228 ++++++++++++++++++++++++++++++++ 9 files changed, 535 insertions(+), 0 deletions(-) create mode 100644 Documentation/security/keys-crypto.txt create mode 100644 include/keys/crypto-subtype.h create mode 100644 include/keys/crypto-type.h create mode 100644 security/keys/crypto/Kconfig create mode 100644 security/keys/crypto/Makefile create mode 100644 security/keys/crypto/crypto_keys.h create mode 100644 security/keys/crypto/crypto_type.c
Documentation/security/keys-crypto.txt new file +181 -0
@@ -0,0 +1,181 @@ + ====================== + CRYPTOGRAPHIC KEY TYPE + ====================== + +Contents: + + - Overview. + - Key identification. + - Accessing crypto keys. + - Implementing crypto parsers. + - Implementing crypto subtypes. + + +======== +OVERVIEW +======== + +The "crypto" key type is designed to be a container for cryptographic keys, +without imposing any particular restrictions on the form of the cryptography or +the key. + +The crypto key is given a subtype that defines what sort of data is associated +with the key and provides operations to describe and destroy it. However, no +requirement is made that the key data actually be loaded into the key. + +The crypto key also has a number of data parsers registered with it. The data +parsers are responsible for extracing information the blobs of data passed to +the instantiator function. The first data parser that recognises the blob gets +to set the subtype of the key and define the operations that can be done on +that key. + +Completely in-kernel key retention and operation subtypes and parsers can be +defined, but it would also be possible to provide access to cryptographic +hardware (such as a TPM) that might be used to both retain the relevant key and +perform operations using that key. In such a case, the crypto key would then +merely be an interface to the TPM driver. + + +================== +KEY IDENTIFICATION +================== + +Because the identity of a key is not necessarily known and may not be easily +calculated when a crypto key is allocated, it may not be a simple matter to set +a key description to something that's useful for determining whether this is +the key you're looking for. Furthermore, it may be necessary to perform a +partial match upon the key identity. + +To help with this, when a key is loaded, the parser calculates the key +fingerprint and stores a copy in the key structure. + +The crypto key type's key matching function then performs more checks than just +the straightforward comparison of the description with the criterion string: + + (1) If the criterion string is of the form "id:<hexdigits>" then the match + function will examine a key's fingerprint to see if the hex digits given + after the "id:" match the tail. For instance: + + keyctl search @s crypto id:5acc2142 + + will match a key with fingerprint: + + 1A00 2040 7601 7889 DE11 882C 3823 04AD 5ACC 2142 + + (2) If the criterion string is of the form "<subtype>:<hexdigits>" then the + match will match the ID as in (1), but with the added restriction that + only keys of the specified subtype (e.g. dsa or rsa) will be matched. For + instance: + + keyctl search @s crypto dsa:5acc2142 + +Looking in /proc/keys, the last 8 hex digits of the key fingerprint are +displayed, along with the subtype: + + 1a39e171 I----- 1 perm 3f010000 0 0 crypto modsign.0: DSA 5acc2142 [] + + +===================== +ACCESSING CRYPTO KEYS +===================== + +To access crypto keys from within the kernel, the following inclusion is +required: + + #include <keys/crypto-type.h> + +This gives access to the key type: + + struct key_type key_type_crypto; + + +=========================== +IMPLEMENTING CRYPTO PARSERS +=========================== + +The crypto key type keeps a list of registered data parsers. An example of +such a parser is one that parses OpenPGP packet formatted data [RFC 4880]. + +During key instantiation each parser in the list is tried until one doesn't +return -EBADMSG. + +The parser definition structure looks like the following: + + struct crypto_key_parser { + struct module *owner; + const char *name; + + int (*instantiate)(struct key *key, + const void *data, size_t datalen); + }; + +The owner and name fields should be set to the owning module and the name of +the parser. + +There are a number of operations defined by the parser. They are all optional, +but it is expected that at least one will be defined. + + (1) instantiate(). + + The arguments are the same as for the instantiate function in the key + type. 'key' is the crypto key being instantiated; data and datalen are + the instantiation data, presumably containing cryptographic key data, and + the length of that data. + + If the data format is not recognised, -EBADMSG should be returned. If it + is recognised, but the key cannot for some reason be set up, some other + negative error code should be returned. + + If the key can be successfully set up, then key->payload should be set to + point to the retained data, key->type_data.p[0] should be set to point to + the subtype chosen and key->type_data.p[1] should be set to point to a + copy of the key's identity string and 0 should be returned. + + The key's identity string may be partially matched upon. For a public-key + algorithm such as RSA and DSA this will likely be a printable hex version + of the key's fingerprint. + +Functions are provided to register and unregister parsers: + + int register_crypto_key_parser(struct crypto_key_parser *parser); + void unregister_crypto_key_parser(struct crypto_key_parser *subtype); + +Parsers may not have the same name. The names are only used for displaying in +debugging messages. + + +============================ +IMPLEMENTING CRYPTO SUBTYPES +============================ + +The parser selects the appropriate subtype directly and sets it on the key; the +crypto key then retains a reference on the subtype module (which means the +parser can be removed thereafter). + +The subtype definition structure looks like the following: + + struct crypto_key_subtype { + struct module *owner; + const char *name; + + void (*describe)(const struct key *key, struct seq_file *m); + void (*destroy)(void *payload); + }; + +The owner and name fields should be set to the owning module and the name of +the subtype. + +There are a number of operations defined by the subtype: + + (1) describe(). + + Mandatory. This allows the subtype to display something in /proc/keys + against the key. For instance the name of the public key algorithm type + could be displayed. The key type will display the tail of the key + identity string after this. + + (2) destroy(). + + Mandatory. This should free the memory associated with the key. The + crypto key will look after freeing the fingerprint and releasing the + reference on the subtype module.
include/keys/crypto-subtype.h new file +56 -0
56 lines not on this page · raw message
include/keys/crypto-type.h new file +25 -0
@@ -0,0 +1,25 @@ +/* Cryptographic key type interface +* +* Copyright (C) 2011 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +* +* See Documentation/security/keys-crypto.txt +*/ + +#ifndef _KEYS_CRYPTO_TYPE_H +#define _KEYS_CRYPTO_TYPE_H + +#include <linux/key-type.h> + +extern struct key_type key_type_crypto; + +/* +* The payload is at the discretion of the subtype. +*/ + +#endif /* _KEYS_CRYPTO_TYPE_H */
security/keys/Kconfig +2 -0
@@ -69,3 +69,5 @@ config KEYS_DEBUG_PROC_KEYS the resulting table. If you are unsure as to whether this is required, answer N. + +source security/keys/crypto/Kconfig
security/keys/Makefile +1 -0
@@ -24,3 +24,4 @@ obj-$(CONFIG_SYSCTL) += sysctl.o # obj-$(CONFIG_TRUSTED_KEYS) += trusted.o obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/ +obj-$(CONFIG_CRYPTO_KEY_TYPE) += crypto/
security/keys/crypto/Kconfig new file +7 -0
@@ -0,0 +1,7 @@ +config CRYPTO_KEY_TYPE + tristate "Cryptographic key type" + depends on KEYS + help + This option provides support for a type of key that holds the keys + required for cryptographic operations such as encryption, decryption, + signature generation and signature verification.
security/keys/crypto/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# +# Makefile for cryptographic keys +# + +obj-$(CONFIG_CRYPTO_KEY_TYPE) += crypto_keys.o + +crypto_keys-y := crypto_type.o
security/keys/crypto/crypto_keys.h new file +28 -0
@@ -0,0 +1,28 @@ +/* Internal crypto type stuff +* +* Copyright (C) 2011 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +*/ + +static inline +struct crypto_key_subtype *crypto_key_subtype (const struct key *key) +{ +return key->type_data.p[0 ]; +} + +static inline char *crypto_key_id (const struct key *key) +{ +return key->type_data.p[1 ]; +} + + +/* +* crypto_type.c +*/ +extern struct list_head crypto_key_parsers; +extern struct rw_semaphore crypto_key_parsers_sem;
security/keys/crypto/crypto_type.c new file +228 -0
228 lines not on this page · raw message
David Howells
maintainerPATCH 6/23 KEYS: Add signature verification facility
In reply to David HowellsAdd a facility whereby a key subtype may be asked to verify a signature against the data it is purported to have signed.
This adds four routines:
(1) struct crypto_key_verify_context *
verify_sig_begin(struct key *keyring, const void *sig, size_t siglen);
This sets up a verification context for the given signature using information in that signature to select a key from the specified keyring and to request a hash algorithm from the crypto layer.
(2) int verify_sig_add_data(struct crypto_key_verify_context *ctx,
const void *data, size_t datalen);
Incrementally supply data to be signed. May be called multiple times. (3) int verify_sig_end(struct crypto_key_verify_context *ctx, const void *sig, size_t siglen);
Complete the verification process and return the result. -EKEYREJECTED will indicate that the verification failed and 0 will indicate success. Other errors are also possible.
(4) void verify_sig_cancel(struct crypto_key_verify_context *ctx);
Cancel the verification process.
---
Documentation/security/keys-crypto.txt | 101 +++++++++++++++++++++++++++++ include/keys/crypto-subtype.h | 21 ++++++ include/keys/crypto-type.h | 9 +++ security/keys/crypto/Makefile | 2 - security/keys/crypto/crypto_verify.c | 111 ++++++++++++++++++++++++++++++++ 5 files changed, 243 insertions(+), 1 deletions(-) create mode 100644 security/keys/crypto/crypto_verify.c
Documentation/security/keys-crypto.txt +101 -0
@@ -7,6 +7,7 @@ Contents: - Overview. - Key identification. - Accessing crypto keys. + - Signature verification. - Implementing crypto parsers. - Implementing crypto subtypes.
@@ -89,6 +90,65 @@ This gives access to the key type: struct key_type key_type_crypto; +SIGNATURE VERIFICATION +---------------------- + +The four operations that can perform cryptographic signature verification, +using one of a set of keys to provide the public key: + + (1) Begin verification procedure. + + struct crypto_key_verify_context * + verify_sig_begin(struct key *keyring, const void *sig, size_t siglen); + + This function sets up a verification context from the information in the + signature and looks for a suitable key in the keyring. The signature blob + must be presented again at the end of the procedure. The keys will be + checked against parameters in the signature, and if the matching one is + not found then -ENOKEY will be returned. + + The hashing algorithm, if such a thing applies, will be determined from + information in the signature and the appropriate crypto module will be + used. -ENOPKG will be returned if the hash algorithm is unavailable. + + The return value is an opaque pointer to be passed to the other functions, + or a negative error code. + + (2) Indicate data to be verified. + + int verify_sig_add_data(struct crypto_key_verify_context *ctx, + const void *data, size_t datalen); + + This function is used to shovel data to the verification procedure so that + it can load it into the hash, pass it to hardware or whatever is + appropriate for the algorithm being employed. + + The data is not canonicalised for the document type specified in the + signature. The caller must do that. + + It will return 0 if successful and a negative error code if not. + + (3) Complete the verification process. + + int verify_sig_end(struct crypto_key_verify_context *ctx, + const void *sig, size_t siglen); + + This function performs the actual signature verification step and cleans + up the resources allocated at the beginning. The signature must be + presented again as some of the data therein may need to be added to the + internal hash. + + It will return -EKEYREJECTED if the signature didn't match, 0 if + successful and may return other errors as appropriate. + + (4) Cancel the verification process. + + void verify_sig_cancel(struct crypto_key_verify_context *ctx); + + This function cleans up the resources allocated at the beginning. This is + not necessary if verify_sig_end() was called. + + =========================== IMPLEMENTING CRYPTO PARSERS ===========================
@@ -96,6 +156,7 @@ IMPLEMENTING CRYPTO PARSERS The crypto key type keeps a list of registered data parsers. An example of such a parser is one that parses OpenPGP packet formatted data [RFC 4880]. + During key instantiation each parser in the list is tried until one doesn't return -EBADMSG.
@@ -107,6 +168,8 @@ The parser definition structure looks like the following: int (*instantiate)(struct key *key, const void *data, size_t datalen); + struct crypto_key_verify_context *(*verify_sig_begin)( + struct key *keyring, const u8 *sig, size_t siglen); }; The owner and name fields should be set to the owning module and the name of
@@ -135,6 +198,44 @@ but it is expected that at least one will be defined. algorithm such as RSA and DSA this will likely be a printable hex version of the key's fingerprint. + (2) verify_sig_begin(). + + This is similar in concept to the instantiate() function, except that it + is given a signature blob to parse rather than a key data blob. + + If the data format is not recognised, -EBADMSG should be returned. If it + is recognised, but the signature verification process cannot for some + reason be set up, some other negative error code should be returned. + -ENOKEY should be used to indicate that no matching key is available and + -ENOPKG should be returned if the hash algorithm or the verification + algorithm are unavailable. + + If successful, the parser should allocate a verification context and embed + the following struct in it: + + struct crypto_key_verify_context { + struct key *key; + int (*add_data)(struct crypto_key_verify_context *ctx, + const void *data, size_t datalen); + int (*end)(struct crypto_key_verify_context *ctx, + const u8 *sig, size_t siglen); + void (*cancel)(struct crypto_key_verify_context *ctx); + }; + + and return a pointer to this to the caller, who will then pass it to the + verification operation wrappers described in the "Signature Verification" + section. The three operation pointers here correspond exactly to those + wrappers and are all mandatory. container_of() should be used to retrieve + the actual context. + + Note that the crypto key type retains a reference on the parser module for + the lifetime of this context, though the operation pointers need not point + into this module. + + The parser should also record a pointer to the key selected and take a + reference on that key with key_get(). + + Functions are provided to register and unregister parsers: int register_crypto_key_parser(struct crypto_key_parser *parser);
include/keys/crypto-subtype.h +21 -0
@@ -20,6 +20,20 @@extern struct key_type key_type_crypto;/* +* Context base for signature verification methods. Allocated by the subtype +* and presumably embedded in something appropriate. +*/ +struct crypto_key_verify_context { +struct key *key; +struct crypto_key_parser *parser; +int (*add_data)(struct crypto_key_verify_context *ctx, +const void *data,size_t datalen); +int (*end)(struct crypto_key_verify_context *ctx, +const u8 *sig,size_t siglen); +void (*cancel)(struct crypto_key_verify_context *ctx); +}; + +/* * Keys of this type declare a subtype that indicates the handlers and * capabilities. */
@@ -48,6 +62,13 @@ struct crypto_key_parser {* Return EBADMSG if not recognised. */ int (*instantiate)(struct key *key,const void *data,size_t datalen); + +/* Attempt to recognise a signature blob and find a matching key. +* +* Return EBADMSG if not recognised. +*/ +struct crypto_key_verify_context *(*verify_sig_begin)( +struct key *keyring,const u8 *sig,size_t siglen); };extern int register_crypto_key_parser (struct crypto_key_parser *);
include/keys/crypto-type.h +9 -0
@@ -18,6 +18,15 @@extern struct key_type key_type_crypto; +struct crypto_key_verify_context ; +extern struct crypto_key_verify_context *verify_sig_begin ( +struct key *key,const void *sig,size_t siglen); +extern int verify_sig_add_data (struct crypto_key_verify_context *ctx, +const void *data,size_t datalen); +extern int verify_sig_end (struct crypto_key_verify_context *ctx, +const void *sig,size_t siglen); +extern void verify_sig_cancel (struct crypto_key_verify_context *ctx); +/* * The payload is at the discretion of the subtype. */
security/keys/crypto/Makefile +1 -1
@@ -4,4 +4,4 @@ obj-$(CONFIG_CRYPTO_KEY_TYPE) += crypto_keys.o -crypto_keys-y := crypto_type.o +crypto_keys-y := crypto_type.o crypto_verify.o
security/keys/crypto/crypto_verify.c new file +111 -0
111 lines not on this page · raw message
David Howells
maintainerPATCH 7/23 KEYS: Asymmetric public-key algorithm crypto key subtype
In reply to David HowellsAdd a subtype for supporting asymmetric public-key encryption algorithms such as DSA (FIPS-186) and RSA (PKCS#1 / RFC1337).
---
security/keys/crypto/Kconfig | 10 +++ security/keys/crypto/Makefile | 3 + security/keys/crypto/public_key.c | 55 +++++++++++++++++++ security/keys/crypto/public_key.h | 106 +++++++++++++++++++++++++++++++++++++ 4 files changed, 173 insertions(+), 1 deletions(-) create mode 100644 security/keys/crypto/public_key.c create mode 100644 security/keys/crypto/public_key.h
security/keys/crypto/Kconfig +10 -0
@@ -5,3 +5,13 @@ config CRYPTO_KEY_TYPE This option provides support for a type of key that holds the keys required for cryptographic operations such as encryption, decryption, signature generation and signature verification. + +config CRYPTO_KEY_PUBLIC_KEY_SUBTYPE + tristate "Asymmetric public-key crypto algorithm subtype" + depends on CRYPTO_KEY_TYPE + select MPILIB + help + This option provides support for asymmetric public key type handling. + If signature generation and/or verification are to be used, + appropriate hash algorithms (such as SHA-1) must be available. + ENOPKG will be reported if the requisite algorithm is unavailable.
security/keys/crypto/Makefile +2 -1
@@ -3,5 +3,6 @@ # obj-$(CONFIG_CRYPTO_KEY_TYPE) += crypto_keys.o - crypto_keys-y := crypto_type.o crypto_verify.o + +obj-$(CONFIG_CRYPTO_KEY_PUBLIC_KEY_SUBTYPE) += public_key.o
security/keys/crypto/public_key.c new file +55 -0
55 lines not on this page · raw message
security/keys/crypto/public_key.h new file +106 -0
106 lines not on this page · raw message
David Howells
maintainerPATCH 8/23 KEYS: RSA signature verification algorithm
In reply to David HowellsImplement the RSA algorithm (PKCS#1 / RFC3447). At this time, only signature verification is supported. This uses the asymmetric public key subtype to hold its key data.
---
security/keys/crypto/Kconfig | 7 + security/keys/crypto/Makefile | 1 security/keys/crypto/crypto_rsa.c | 282 +++++++++++++++++++++++++++++++++++++ security/keys/crypto/public_key.h | 2 4 files changed, 292 insertions(+), 0 deletions(-) create mode 100644 security/keys/crypto/crypto_rsa.c
security/keys/crypto/Kconfig +7 -0
@@ -15,3 +15,10 @@ config CRYPTO_KEY_PUBLIC_KEY_SUBTYPE If signature generation and/or verification are to be used, appropriate hash algorithms (such as SHA-1) must be available. ENOPKG will be reported if the requisite algorithm is unavailable. + +config CRYPTO_KEY_PKEY_ALGO_RSA + tristate "RSA public-key algorithm" + depends on CRYPTO_KEY_PUBLIC_KEY_SUBTYPE + select MPILIB_EXTRA + help + This option enables support for the RSA algorithm (PKCS#1, RFC3447).
security/keys/crypto/Makefile +1 -0
@@ -6,3 +6,4 @@ obj-$(CONFIG_CRYPTO_KEY_TYPE) += crypto_keys.o crypto_keys-y := crypto_type.o crypto_verify.o obj-$(CONFIG_CRYPTO_KEY_PUBLIC_KEY_SUBTYPE) += public_key.o +obj-$(CONFIG_CRYPTO_KEY_PKEY_ALGO_RSA) += crypto_rsa.o
security/keys/crypto/crypto_rsa.c new file +282 -0
282 lines not on this page · raw message
security/keys/crypto/public_key.h +2 -0
@@ -42,6 +42,8 @@ struct public_key_algorithm { const struct public_key_signature *sig); }; +extern const struct public_key_algorithm RSA_public_key_algorithm; +/* * Asymmetric public key data */
David Howells
maintainerPATCH 9/23 Fix signature verification for shorter signatures
In reply to David Howellsgpg can produce a signature file where length of signature is less than the modulus size because the amount of space an MPI takes up is kept as low as possible by discarding leading zeros. This regularly happens for several modules during the build.
Fix it by relaxing check in RSA verification code.
Thanks to Tomas Mraz and Miloslav Trmac for help.
---
security/keys/crypto/crypto_rsa.c | 14 +++++++++++--- 1 files changed, 11 insertions(+), 3 deletions(-)
security/keys/crypto/crypto_rsa.c +11 -3
@@ -219,15 +219,23 @@ static int RSA_verify_signature(const struct public_key *key,kenter ("" );/* (1) Check the signature size against the public key modulus size */ - k = (mpi_get_nbits (key->rsa.n) +7 ) /8 ; + k =mpi_get_nbits (key->rsa.n); + tsize =mpi_get_nbits (sig->rsa.s); - tsize = (mpi_get_nbits (sig->rsa.s) +7 ) /8 ; +/* According to RFC 4880 sec 3.2, length of MPI is computed starting +* from most significant bit. So the RFC 3447 sec 8.2.2 size check +* must be relaxed to conform with shorter signatures - so we fail here +* only if signature length is longer than modulus size. +*/ pr_devel ("step 1: k=%zu size(S)=%zu\n" , k, tsize); -if (tsize != k) { +if (k < tsize) { ret = -EBADMSG ; goto error; } +/* Round up and convert to octets */ + k = (k +7 ) /8 ; +/* (2b) Apply the RSAVP1 verification primitive to the public key */ ret =RSAVP1 (key, sig->rsa.s, &m);if (ret <0 )
David Howells
maintainerPATCH 10/23 PGPLIB: PGP definitions (RFC 4880)
In reply to David HowellsProvide some useful PGP definitions from RFC 4880. These describe details of public key crypto as used by crypto keys for things like signature verification.
---
include/linux/pgp.h | 206 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 206 insertions(+), 0 deletions(-) create mode 100644 include/linux/pgp.h
include/linux/pgp.h new file +206 -0
@@ -0,0 +1,206 @@ +/* PGP definitions (RFC 4880) +* +* Copyright (C) 2011 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +*/ + +#ifndef _LINUX_PGP_H +#define _LINUX_PGP_H + +#include <linux/types.h> + +struct pgp_key_ID { +u8 id[8 ]; +}; + +struct pgp_time { +u8 time[4 ]; +}; + +/* +* PGP public-key algorithm identifiers [RFC4880: 9.1] +*/ +enum pgp_pubkey_algo { +PGP_PUBKEY_RSA_ENC_OR_SIG =1 , +PGP_PUBKEY_RSA_ENC_ONLY =2 , +PGP_PUBKEY_RSA_SIG_ONLY =3 , +PGP_PUBKEY_ELGAMAL =16 , +PGP_PUBKEY_DSA =17 , +PGP_PUBKEY__LAST +}; + +/* +* PGP symmetric-key algorithm identifiers [RFC4880: 9.2] +*/ +enum pgp_symkey_algo { +PGP_SYMKEY_PLAINTEXT =0 , +PGP_SYMKEY_IDEA =1 , +PGP_SYMKEY_3DES =2 , +PGP_SYMKEY_CAST5 =3 , +PGP_SYMKEY_BLOWFISH =4 , +PGP_SYMKEY_AES_128KEY =7 , +PGP_SYMKEY_AES_192KEY =8 , +PGP_SYMKEY_AES_256KEY =9 , +PGP_SYMKEY_TWOFISH_256KEY =10 , +}; + +/* +* PGP compression algorithm identifiers [RFC4880: 9.3] +*/ +enum pgp_compr_algo { +PGP_COMPR_UNCOMPRESSED =0 , +PGP_COMPR_ZIP =1 , +PGP_COMPR_ZLIB =2 , +PGP_COMPR_BZIP2 =3 , +}; + +/* +* PGP hash algorithm identifiers [RFC4880: 9.4] +*/ +enum pgp_hash_algo { +PGP_HASH_MD5 =1 , +PGP_HASH_SHA1 =2 , +PGP_HASH_RIPE_MD_160 =3 , +PGP_HASH_SHA256 =8 , +PGP_HASH_SHA384 =9 , +PGP_HASH_SHA512 =10 , +PGP_HASH_SHA224 =11 , +PGP_HASH__LAST +}; + +extern const char *const pgp_hash_algorithms[PGP_HASH__LAST ]; + +/* +* PGP packet type tags [RFC4880: 4.3]. +*/ +enum pgp_packet_tag { +PGP_PKT_RESERVED =0 , +PGP_PKT_PUBKEY_ENC_SESSION_KEY =1 , +PGP_PKT_SIGNATURE =2 , +PGP_PKT_SYMKEY_ENC_SESSION_KEY =3 , +PGP_PKT_ONEPASS_SIGNATURE =4 , +PGP_PKT_SECRET_KEY =5 , +PGP_PKT_PUBLIC_KEY =6 , +PGP_PKT_SECRET_SUBKEY =7 , +PGP_PKT_COMPRESSED_DATA =8 , +PGP_PKT_SYM_ENC_DATA =9 , +PGP_PKT_MARKER =10 , +PGP_PKT_LITERAL_DATA =11 , +PGP_PKT_TRUST =12 , +PGP_PKT_USER_ID =13 , +PGP_PKT_PUBLIC_SUBKEY =14 , +PGP_PKT_USER_ATTRIBUTE =17 , +PGP_PKT_SYM_ENC_AND_INTEG_DATA =18 , +PGP_PKT_MODIFY_DETECT_CODE =19 , +PGP_PKT_PRIVATE_0 =60 , +PGP_PKT_PRIVATE_3 =63 , +PGP_PKT__HIGHEST =63 +}; + +/* +* Signature (tag 2) packet [RFC4880: 5.2]. +*/ +enum pgp_signature_version { +PGP_SIG_VERSION_3 =3 , +PGP_SIG_VERSION_4 =4 , +}; + +enum pgp_signature_type { +PGP_SIG_BINARY_DOCUMENT_SIG =0x00 , +PGP_SIG_CANONICAL_TEXT_DOCUMENT_SIG =0x01 , +PGP_SIG_STANDALONE_SIG =0x02 , +PGP_SIG_GENERAL_CERT_OF_UID_PUBKEY =0x10 , +PGP_SIG_PERSONAL_CERT_OF_UID_PUBKEY =0x11 , +PGP_SIG_CASUAL_CERT_OF_UID_PUBKEY =0x12 , +PGP_SIG_POSTITIVE_CERT_OF_UID_PUBKEY =0x13 , +PGP_SIG_SUBKEY_BINDING_SIG =0x18 , +PGP_SIG_PRIMARY_KEY_BINDING_SIG =0x19 , +PGP_SIG_DIRECTLY_ON_KEY =0x1F , +PGP_SIG_KEY_REVOCATION_SIG =0x20 , +PGP_SIG_SUBKEY_REVOCATION_SIG =0x28 , +PGP_SIG_CERT_REVOCATION_SIG =0x30 , +PGP_SIG_TIMESTAMP_SIG =0x40 , +PGP_SIG_THIRD_PARTY_CONFIRM_SIG =0x50 , +}; + +struct pgp_signature_v3_packet { +enum pgp_signature_version version :8 ;/* == PGP_SIG_VERSION_3 */ +u8 length_of_hashed;/* == 5 */ +struct { +enum pgp_signature_type signature_type :8 ; +struct pgp_time creation_time; + } hashed; +struct pgp_key_ID issuer; +enum pgp_pubkey_algo pubkey_algo :8 ; +enum pgp_hash_algo hash_algo :8 ; +} __packed; + +struct pgp_signature_v4_packet { +enum pgp_signature_version version :8 ;/* == PGP_SIG_VERSION_4 */ +enum pgp_signature_type signature_type :8 ; +enum pgp_pubkey_algo pubkey_algo :8 ; +enum pgp_hash_algo hash_algo :8 ; +} __packed; + +/* +* V4 signature subpacket types [RFC4880: 5.2.3.1]. +*/ +enum pgp_sig_subpkt_type { +PGP_SIG_CREATION_TIME =2 , +PGP_SIG_EXPIRATION_TIME =3 , +PGP_SIG_EXPORTABLE_CERT =4 , +PGP_SIG_TRUST_SIG =5 , +PGP_SIG_REGEXP =6 , +PGP_SIG_REVOCABLE =7 , +PGP_SIG_KEY_EXPIRATION_TIME =9 , +PGP_SIG_PREF_SYM_ALGO =11 , +PGP_SIG_REVOCATION_KEY =12 , +PGP_SIG_ISSUER =16 , +PGP_SIG_NOTATION_DATA =20 , +PGP_SIG_PREF_HASH_ALGO =21 , +PGP_SIG_PREF_COMPR_ALGO =22 , +PGP_SIG_KEY_SERVER_PREFS =23 , +PGP_SIG_PREF_KEY_SERVER =24 , +PGP_SIG_PRIMARY_USER_ID =25 , +PGP_SIG_POLICY_URI =26 , +PGP_SIG_KEY_FLAGS =27 , +PGP_SIG_SIGNERS_USER_ID =28 , +PGP_SIG_REASON_FOR_REVOCATION =29 , +PGP_SIG_FEATURES =30 , +PGP_SIG_TARGET =31 , +PGP_SIG_EMBEDDED_SIG =32 , +PGP_SIG__LAST +}; + +#define PGP_SIG_SUBPKT_TYPE_CRITICAL_MASK 0x80 + +/* +* Key (tag 5, 6, 7 and 14) packet +*/ +enum pgp_key_version { +PGP_KEY_VERSION_2 =2 , +PGP_KEY_VERSION_3 =3 , +PGP_KEY_VERSION_4 =4 , +}; + +struct pgp_key_v3_packet { +enum pgp_key_version version :8 ; +struct pgp_time creation_time; +u8 expiry[2 ];/* 0 or time in days till expiry */ +enum pgp_pubkey_algo pubkey_algo :8 ; +u8 key_material[0 ]; +} __packed; + +struct pgp_key_v4_packet { +enum pgp_key_version version :8 ; +struct pgp_time creation_time; +enum pgp_pubkey_algo pubkey_algo :8 ; +u8 key_material[0 ]; +} __packed; + +#endif /* _LINUX_PGP_H */
David Howells
maintainerPATCH 11/23 PGPLIB: Basic packet parser
In reply to David HowellsProvide a simple parser that extracts the packets from a PGP packet blob and passes the desirous ones to the given processor function:
struct pgp_parse_context {
u64 types_of_interest;
int (*process_packet)(struct pgp_parse_context *context,
enum pgp_packet_tag type,
u8 headerlen,
const u8 *data,
size_t datalen);
};
int pgp_parse_packets(const u8 *data, size_t datalen,
struct pgp_parse_context *ctx);This is configured on with CONFIG_PGP_LIBRARY.
---
include/linux/pgp.h | 25 +++ security/keys/crypto/Kconfig | 6 + security/keys/crypto/Makefile | 1 security/keys/crypto/pgp_library.c | 268 ++++++++++++++++++++++++++++++++++++ 4 files changed, 300 insertions(+), 0 deletions(-) create mode 100644 security/keys/crypto/pgp_library.c
include/linux/pgp.h +25 -0
@@ -203,4 +203,29 @@ struct pgp_key_v4_packet { u8 key_material[0]; } __packed; +/* +* PGP library packet parser +*/ +struct pgp_parse_context { +u64 types_of_interest; +int (*process_packet)(struct pgp_parse_context *context, +enum pgp_packet_tag type, +u8 headerlen, +const u8 *data, +size_t datalen); +}; + +extern int pgp_parse_packets (const u8 *data,size_t datalen, +struct pgp_parse_context *ctx); + +struct pgp_parse_pubkey { +enum pgp_key_version version :8 ; +enum pgp_pubkey_algo pubkey_algo :8 ; +time_t creation_time; +time_t expires_at; +}; + +extern int pgp_parse_public_key (const u8 **_data,size_t *_datalen, +struct pgp_parse_pubkey *pk); +#endif /* _LINUX_PGP_H */
security/keys/crypto/Kconfig +6 -0
@@ -22,3 +22,9 @@ config CRYPTO_KEY_PKEY_ALGO_RSA select MPILIB_EXTRA help This option enables support for the RSA algorithm (PKCS#1, RFC3447). + +config PGP_LIBRARY + tristate "PGP parsing library" + help + This option enables a library that provides a number of simple + utility functions for parsing PGP (RFC 4880) packet-based messages.
security/keys/crypto/Makefile +1 -0
@@ -7,3 +7,4 @@ crypto_keys-y := crypto_type.o crypto_verify.o obj-$(CONFIG_CRYPTO_KEY_PUBLIC_KEY_SUBTYPE) += public_key.o obj-$(CONFIG_CRYPTO_KEY_PKEY_ALGO_RSA) += crypto_rsa.o +obj-$(CONFIG_PGP_LIBRARY) += pgp_library.o
security/keys/crypto/pgp_library.c new file +268 -0
268 lines not on this page · raw message
David Howells
maintainerPATCH 12/23 PGPLIB: Signature parser
In reply to David HowellsProvide some PGP signature parsing helpers:
(1) A function to parse V4 signature subpackets and pass the desired ones to a processor function:
int pgp_parse_sig_subpkts(const u8 *data, size_t datalen,
struct pgp_parse_sig_context *ctx);
(2) A function to parse out basic signature parameters from any PGP signature such that the algorithms and public key can be selected:
int pgp_parse_sig_params(const u8 **_data, size_t *_datalen,
struct pgp_sig_parameters *p);
---
include/linux/pgp.h | 24 +++ security/keys/crypto/pgp_library.c | 282 ++++++++++++++++++++++++++++++++++++ 2 files changed, 306 insertions(+), 0 deletions(-)
include/linux/pgp.h +24 -0
@@ -228,4 +228,28 @@ struct pgp_parse_pubkey {extern int pgp_parse_public_key (const u8 **_data,size_t *_datalen,struct pgp_parse_pubkey *pk); +struct pgp_parse_sig_context { +unsigned long types_of_interest[128 /BITS_PER_LONG ]; +int (*process_packet)(struct pgp_parse_sig_context *context, +enum pgp_sig_subpkt_type type, +const u8 *data, +size_t datalen); +}; + +extern int pgp_parse_sig_packets (const u8 *data,size_t datalen, +struct pgp_parse_sig_context *ctx); + +struct pgp_sig_parameters { +enum pgp_signature_type signature_type :8 ; +union { +struct pgp_key_ID issuer; +__be32 issuer32[2 ]; + }; +enum pgp_pubkey_algo pubkey_algo :8 ; +enum pgp_hash_algo hash_algo :8 ; +}; + +extern int pgp_parse_sig_params (const u8 **_data,size_t *_datalen, +struct pgp_sig_parameters *p); +#endif /* _LINUX_PGP_H */
security/keys/crypto/pgp_library.c +282 -0
285 lines not on this page · raw message
David Howells
maintainerPATCH 13/23 KEYS: PGP data parser
In reply to David HowellsImplement a PGP data parser for the crypto key type to use when instantiating a key.
This parser attempts to parse the instantiation data as a PGP packet sequence (RFC 4880) and if it parses okay, attempts to extract a public-key algorithm key or subkey from it.
If it finds such a key, it will set up a public_key subtype payload with appropriate handler routines (DSA or RSA) and attach it to the key.
---
security/keys/crypto/Kconfig | 12 + security/keys/crypto/Makefile | 4 security/keys/crypto/pgp_key_parser.c | 346 +++++++++++++++++++++++++++++++++ security/keys/crypto/pgp_parser.h | 23 ++ 4 files changed, 385 insertions(+), 0 deletions(-) create mode 100644 security/keys/crypto/pgp_key_parser.c create mode 100644 security/keys/crypto/pgp_parser.h
security/keys/crypto/Kconfig +12 -0
@@ -28,3 +28,15 @@ config PGP_LIBRARY help This option enables a library that provides a number of simple utility functions for parsing PGP (RFC 4880) packet-based messages. + +config CRYPTO_KEY_PGP_PARSER + tristate "PGP key blob parser" + depends on CRYPTO_KEY_TYPE + select CRYPTO_KEY_PUBLIC_KEY_SUBTYPE + select PGP_LIBRARY + select MD5 # V3 fingerprint generation + select SHA1 # V4 fingerprint generation + help + This option provides support for parsing PGP (RFC 4880) format blobs + for key data and provides the ability to instantiate a crypto key + from a public key packet found inside the blob.
security/keys/crypto/Makefile +4 -0
@@ -8,3 +8,7 @@ crypto_keys-y := crypto_type.o crypto_verify.o obj-$(CONFIG_CRYPTO_KEY_PUBLIC_KEY_SUBTYPE) += public_key.o obj-$(CONFIG_CRYPTO_KEY_PKEY_ALGO_RSA) += crypto_rsa.o obj-$(CONFIG_PGP_LIBRARY) += pgp_library.o + +obj-$(CONFIG_CRYPTO_KEY_PGP_PARSER) += pgp_parser.o +pgp_parser-y := \ + pgp_key_parser.o
security/keys/crypto/pgp_key_parser.c new file +346 -0
346 lines not on this page · raw message
security/keys/crypto/pgp_parser.h new file +23 -0
@@ -0,0 +1,23 @@ +/* PGP crypto data parser internal definitions +* +* Copyright (C) 2011 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +*/ + +#include <linux/pgp.h> + +#define kenter (FMT , ...) \ + pr_devel("==> %s("FMT")\n", __func__, ##__VA_ARGS__) +#define kleave (FMT , ...) \ + pr_devel("<== %s()"FMT"\n", __func__, ##__VA_ARGS__) + +/* +* pgp_key_parser.c +*/ +extern const +struct public_key_algorithm *pgp_public_key_algorithms[PGP_PUBKEY__LAST ];
David Howells
maintainerPATCH 14/23 KEYS: PGP-based public key signature verification
In reply to David HowellsProvide handlers for PGP-based public-key algorithm signature verification. This does most of the work involved in signature verification as most of it is public-key algorithm agnostic. The public-key verification algorithm itself is just the last little bit and is supplied the complete hash data to process.
This requires glue logic putting on top to make use of it - something the next patch provides.
---
security/keys/crypto/Makefile | 3 security/keys/crypto/pgp_parser.h | 6 + security/keys/crypto/pgp_pubkey_sig.c | 324 +++++++++++++++++++++++++++++++++ 3 files changed, 332 insertions(+), 1 deletions(-) create mode 100644 security/keys/crypto/pgp_pubkey_sig.c
security/keys/crypto/Makefile +2 -1
@@ -11,4 +11,5 @@ obj-$(CONFIG_PGP_LIBRARY) += pgp_library.o obj-$(CONFIG_CRYPTO_KEY_PGP_PARSER) += pgp_parser.o pgp_parser-y := \ - pgp_key_parser.o + pgp_key_parser.o \ + pgp_pubkey_sig.o
security/keys/crypto/pgp_parser.h +6 -0
@@ -21,3 +21,9 @@*/ extern const struct public_key_algorithm *pgp_public_key_algorithms[PGP_PUBKEY__LAST ]; + +/* +* pgp_pubkey_sig.c +*/ +extern struct crypto_key_verify_context *pgp_pkey_verify_sig_begin ( +struct key *crypto_key,const u8 *sigdata,size_t siglen);
security/keys/crypto/pgp_pubkey_sig.c new file +324 -0
324 lines not on this page · raw message
David Howells
maintainerPATCH 15/23 KEYS: PGP format signature parser
In reply to David HowellsImplement a signature parser that will attempt to parse a signature blob as a PGP packet format message. If it can, it will find an appropriate crypto key and set the public-key algorithm according to the data in the signature.
---
security/keys/crypto/Makefile | 1 security/keys/crypto/pgp_key_parser.c | 1 security/keys/crypto/pgp_parser.h | 6 ++ security/keys/crypto/pgp_sig_parser.c | 113 +++++++++++++++++++++++++++++++++ 4 files changed, 121 insertions(+), 0 deletions(-) create mode 100644 security/keys/crypto/pgp_sig_parser.c
security/keys/crypto/Makefile +1 -0
@@ -12,4 +12,5 @@ obj-$(CONFIG_PGP_LIBRARY) += pgp_library.o obj-$(CONFIG_CRYPTO_KEY_PGP_PARSER) += pgp_parser.o pgp_parser-y := \ pgp_key_parser.o \ + pgp_sig_parser.o \ pgp_pubkey_sig.o
security/keys/crypto/pgp_key_parser.c +1 -0
@@ -327,6 +327,7 @@ static struct crypto_key_parser pgp_key_parser = { .owner = THIS_MODULE, .name = "pgp", .instantiate = pgp_key_instantiate, + .verify_sig_begin = pgp_verify_sig_begin, };/*
security/keys/crypto/pgp_parser.h +6 -0
@@ -23,6 +23,12 @@ extern conststruct public_key_algorithm *pgp_public_key_algorithms[PGP_PUBKEY__LAST ];/* +* pgp_sig_parser.c +*/ +extern struct crypto_key_verify_context *pgp_verify_sig_begin ( +struct key *keyring,const u8 *sig,size_t siglen); + +/* * pgp_pubkey_sig.c */ extern struct crypto_key_verify_context *pgp_pkey_verify_sig_begin(
security/keys/crypto/pgp_sig_parser.c new file +113 -0
113 lines not on this page · raw message
David Howells
maintainerPATCH 16/23 KEYS: Provide a function to load keys from a PGP keyring blob
In reply to David HowellsProvide a function to load keys from a PGP keyring blob for use in initialising the module signing key keyring:
int load_PGP_keys(const u8 *pgpdata, size_t pgpdatalen, struct key *keyring, const char *descprefix);
The keys are labelled with descprefix plus a number to uniquify them. The keys will actually be identified by the ID calculated from the PGP data rather than by the description, so this shouldn't be a problem.
The keys are attached to the keyring supplied.
Looking as root in /proc/keys after the module signing keyring has been loaded:
24460d1c I----- 1 perm 3f010000 0 0 crypto modsign.0: dsa 5acc2142 [] 3ca85723 I----- 1 perm 1f010000 0 0 keyring .module_sign: 1/4
---
Documentation/security/keys-crypto.txt | 20 +++++++ include/keys/crypto-type.h | 3 + security/keys/crypto/Kconfig | 9 +++ security/keys/crypto/Makefile | 1 security/keys/crypto/pgp_preload.c | 90 ++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 0 deletions(-) create mode 100644 security/keys/crypto/pgp_preload.c
Documentation/security/keys-crypto.txt +20 -0
@@ -10,6 +10,7 @@ Contents: - Signature verification. - Implementing crypto parsers. - Implementing crypto subtypes. + - Initial PGP key preloading. ========
@@ -280,3 +281,22 @@ There are a number of operations defined by the subtype: Mandatory. This should free the memory associated with the key. The crypto key will look after freeing the fingerprint and releasing the reference on the subtype module. + + +======================= +INITIAL PGP KEY LOADING +======================= + +A function is provided to perform an initial load of a set of public keys bound +into a PGP packet format blob: + + int preload_pgp_keys(const u8 *pgpdata, size_t pgpdatalen, + struct key *keyring, const char *descprefix); + +This takes the blob of data defined by pgpdata and pgpdatalen, extracts keys +from them and adds them to the specified keyring. The keys are labelled with +descprefix plus a simple uniquifier - it is not expected that the description +will be used to identify the key. The description is required to prevent all +but the last key being discarded when the keys are linked into the keyring. + +This function is only available during initial kernel set up.
include/keys/crypto-type.h +3 -0
@@ -31,4 +31,7 @@ extern void verify_sig_cancel(struct crypto_key_verify_context *ctx);* The payload is at the discretion of the subtype. */ +extern __init int preload_pgp_keys (const u8 *pgpdata,size_t pgpdatalen, +struct key *keyring,const char *descprefix); +#endif /* _KEYS_CRYPTO_TYPE_H */
security/keys/crypto/Kconfig +9 -0
@@ -40,3 +40,12 @@ config CRYPTO_KEY_PGP_PARSER This option provides support for parsing PGP (RFC 4880) format blobs for key data and provides the ability to instantiate a crypto key from a public key packet found inside the blob. + +config PGP_PRELOAD + bool "PGP public key preloading facility" + select PGP_LIBRARY + select CRYPTO_KEY_PGP_PARSER + help + This option provides a facility for the kernel to preload PGP-wrapped + bundles of keys during boot. It is used by module signing to load + the module signing keys for example.
security/keys/crypto/Makefile +1 -0
@@ -8,6 +8,7 @@ crypto_keys-y := crypto_type.o crypto_verify.o obj-$(CONFIG_CRYPTO_KEY_PUBLIC_KEY_SUBTYPE) += public_key.o obj-$(CONFIG_CRYPTO_KEY_PKEY_ALGO_RSA) += crypto_rsa.o obj-$(CONFIG_PGP_LIBRARY) += pgp_library.o +obj-$(CONFIG_PGP_PRELOAD) += pgp_preload.o obj-$(CONFIG_CRYPTO_KEY_PGP_PARSER) += pgp_parser.o pgp_parser-y := \
security/keys/crypto/pgp_preload.c new file +90 -0
90 lines not on this page · raw message
David Howells
maintainerPATCH 17/23 MODSIGN: Provide gitignore and make clean rules for extra files
In reply to David HowellsProvide gitignore and make clean rules for extra files to hide and clean up the extra files produced by module signing stuff once it is added. Also add a clean up rule for the module content extractor program used to extract the data to be signed.
---
.gitignore | 13 +++++++++++++ Makefile | 1 + 2 files changed, 14 insertions(+), 0 deletions(-)
.gitignore +13 -0
@@ -14,6 +14,10 @@ *.o.* *.a *.s +*.ko.unsigned +*.ko.stripped +*.ko.stripped.sig +*.ko.trailer *.ko *.so *.so.dbg
@@ -84,3 +88,12 @@ GTAGS *.orig *~ \#*# + +# +# GPG leavings from module signing +# +genkey +modsign.pub +modsign.sec +random_seed +trustdb.gpg
Makefile +1 -0
@@ -1407,6 +1407,7 @@ clean: $(clean-dirs) $(call cmd,rmfiles) @find $(if $(KBUILD_EXTMOD), $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \ \( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \ + -o -name '*.ko.*' \ -o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \ -o -name '*.symtypes' -o -name 'modules.order' \ -o -name modules.builtin -o -name '.tmp_*.o.*' \
David Howells
maintainerPATCH 18/23 MODSIGN: Provide Documentation and Kconfig options
In reply to David HowellsProvide documentation and kernel configuration options for module signing.
The documentation can be found in:
Documentation/module-signing.txt
The following configuration options are added:
(1) CONFIG_MODULE_SIG
Enable module signing. This will both cause the build process to sign modules and the kernel to check modules when they're loaded.
(2) CONFIG_MODULE_SIG_SHA1
CONFIG_MODULE_SIG_SHA224
CONFIG_MODULE_SIG_SHA256
CONFIG_MODULE_SIG_SHA384
CONFIG_MODULE_SIG_SHA512
Select the cryptographic hash used to digest the data prior to signing. Additionally, the crypto module selected will be built into the kernel as it won't be possible to load it as a module without incurring a circular dependency when the kernel tries to check its signature.
(3) CONFIG_MODULE_SIG_FORCE
Require that any module loaded must be signed with a key compiled into the kernel. All other modules are rejected with EKEYREJECTED.
---
Documentation/module-signing.txt | 183 ++++++++++++++++++++++++++++++++++++++ include/linux/modsign.h | 27 ++++++ init/Kconfig | 62 +++++++++++++ 3 files changed, 272 insertions(+), 0 deletions(-) create mode 100644 Documentation/module-signing.txt create mode 100644 include/linux/modsign.h
Documentation/module-signing.txt new file +183 -0
@@ -0,0 +1,183 @@ + ============================== + KERNEL MODULE SIGNING FACILITY + ============================== + +The module signing facility applies cryptographic signature checking to modules +on module load, checking the signature against a ring of public keys compiled +into the kernel. GPG is used to do the cryptographic work and determines the +format of the signature and key data. The facility uses GPG's MPI library to +handle the huge numbers involved. + +The signature checker in the kernel is capable of handling multiple keys of +either DSA or RSA type, and can support any of MD5, RIPE-MD-160, SHA-1, +SHA-224, SHA-256, SHA-384 and SHA-512 hashes - PROVIDED(!) the requisite +algorithms are compiled into the kernel. + +(!) NOTE: Modules may only be verified initially with algorithms compiled into +the kernel. Further algorithm modules may be loaded and used - but these must +first pass a verification step using already loaded/compiled-in algorithms. + + +===================== +SUPPLYING PUBLIC KEYS +===================== + +A set of public keys must be supplied at kernel image build time. This is done +by taking a GPG public key file and placing it in the base of the kernel +directory in a file called modsign.pub. + +For example, a throwaway key could be generated automatically by something like +the following: + + cat >genkey <<EOF + %pubring modsign.pub + %secring modsign.sec + Key-Type: RSA + Key-Length: 4096 + Name-Real: A. N. Other + Name-Comment: Kernel Module GPG key + %commit + EOF + gpg --homedir . --batch --gen-key genkey + +The above generates fresh keys using /dev/random. If there's insufficient data +in /dev/random, more can be provided using the rngd program if there's a +hardware random number generator available. + +Note that no GPG password is used in the above scriptlet. + +The modsign.pub file is compiled into the kernel directly by the assembler by +means of an ".incbin" directive in kernel/modsign-pubkey.c. + +Once the kernel is running, the keys are visible to root as kernel crypto keys +in /proc/keys in a keyring called .module_sign: + +335ab517 I----- 1 perm 1f030000 0 0 keyring .module_sign: 2/4 +38d7d169 I----- 1 perm 3f010000 0 0 crypto modsign.0: rsa 57532ca5 [] +195fa736 I----- 1 perm 3f010000 0 0 crypto modsign.1: dsa 5acc2142 [] + +This keyring can be listed with the keyctl program. See: + + Documentation/security/keys-crypto.txt + +for more information of crypto keys. + + +============================ +SELECTING THE HASH ALGORITHM +============================ + +The hash algorithm to be used is selected by a multiple choice configuration +item that enables one of the following variables: + + CONFIG_SIG_SHA1 + CONFIG_SIG_SHA224 + CONFIG_SIG_SHA256 + CONFIG_SIG_SHA384 + CONFIG_SIG_SHA512 + +These cause an appropriate "--digest-algo=" parameter to be passed to gpg when +signing a module and force the appropriate hash algorithm to be compiled +directly into the kernel rather than being built as a module. + + +============== +MODULE SIGNING +============== + +Modules will then be signed automatically. The kernel make command line can +include the following options: + + (*) MODSECKEY=<secret-key-ring-path> + + This indicates the whereabouts of the GPG keyring that is the source of + the secret key to be used. The default is "./modsign.sec". + + (*) MODPUBKEY=<public-key-ring-path> + + This indicates the whereabouts of the GPG keyring that is the source of + the public key to be used. The default is "./modsign.pub". + + (*) MODKEYNAME=<key-name> + + The name of the key pair to be used from the aforementioned keyrings. + This defaults to being unset, thus leaving the choice of default key to + gpg. + + (*) KEYFLAGS="gpg-options" + + Override the complete gpg command line, including the preceding three + options. The default options supplied to gpg are: + + --no-default-keyring + --secret-keyring $(MODSECKEY) + --keyring $(MODPUBKEY) + --no-default-keyring + --homedir . + --no-options + --no-auto-check-trustdb + --no-permission-warning + --digest-algo=<hash-algorithm> + + with: + + --default-key $(MODKEYNAME) + + being added if requested. + +The resulting module.ko file will be the signed module. + + +============================ +SIGNED MODULES AND STRIPPING +============================ + +The module signature is just appended to the module binary with a magic number +at the end of file, a couple of fixed-size lengths prior to that and the +signature prior to that. + +WARNING! Signed modules are BRITTLE as the signature is outside of the defined +ELF container. Thus they MAY NOT be stripped once the signature is computed +and attached, lest the signature be discarded or the payload be modified. Note +that the entire module is the signed payload, including all the debug +information present at the time of signing so it must still be present when the +signature is checked. + +As the module may need to be included in a ramdisk image of limited capacity, +modules are maximally stripped prior to signing by the build process. + +Note that if FIPS mode is engaged, a module for which the signature does not +match the payload will panic the box. + + +====================== +LOADING SIGNED MODULES +====================== + +Modules are loaded with insmod, exactly as for unsigned modules. The signature +checker will check at the end of the file for the signature marker and apply +signature checking if found. + + +========================================= +NON-VALID SIGNATURES AND UNSIGNED MODULES +========================================= + +If CONFIG_MODULE_SIG_FORCE is enabled or "enforcemodulesig=1" is supplied on +the kernel command line, the kernel will _only_ load validly signed modules +for which it has a public key. Otherwise, it will also load modules that are +unsigned. Any module for which the kernel has a key, but which proves to have +a signature mismatch will not be permitted to load (returning EKEYREJECTED). + +This table indicates the behaviours of the various situations: + + MODULE STATE PERMISSIVE MODE ENFORCING MODE + ======================================= =============== =============== + Unsigned Ok EKEYREJECTED + Signed, no public key ENOKEY ENOKEY + Validly signed, public key Ok Ok + Invalidly signed, public key EKEYREJECTED EKEYREJECTED + Validly signed, expired key EKEYEXPIRED EKEYEXPIRED + Signed, hash algorithm unavailable ENOPKG ENOPKG + Corrupt signature EBADMSG EBADMSG +
include/linux/modsign.h new file +27 -0
@@ -0,0 +1,27 @@ +/* Module signing definitions +* +* Copyright (C) 2009 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +*/ + +#ifndef _LINUX_MODSIGN_H +#define _LINUX_MODSIGN_H + +#ifdef CONFIG_MODULE_SIG + +#include <linux/elfnote.h> + +/* +* The parameters of the ELF note used to carry the signature +*/ +#define MODSIGN_NOTE_NAME module.sig +#define MODSIGN_NOTE_TYPE 100 + +#endif + +#endif /* _LINUX_MODSIGN_H */
init/Kconfig +62 -0
68 lines not on this page · raw message
David Howells
maintainerPATCH 19/23 MODSIGN: Sign modules during the build process
In reply to David HowellsIf CONFIG_MODULE_SIG is set, then this patch will cause the module to get a signature installed. The following steps will occur:
(1) The module will be linked to foo.ko.unsigned instead of foo.ko
(2) The module will be stripped using both "strip -x -g" and "eu-strip" to ensure minimal size for inclusion in an initramfs.
(3) The signature will be generated on the stripped module.
(4) The signature will be appended to the module, along with the payload size, the signature size and a magic string.
Step (3) requires private and public keys to be available. By default these are expected to be found in PGP keyring files called modsign.sec (the secret key) and modsign.pub (the public key) in the build root.
If the secret key is not found then signing will be skipped and the unsigned module from (1) will just be copied to foo.ko.
If signing occurs, lines like the following will be seen:
LD [M] fs/foo/foo.ko.unsigned
STRIP [M] fs/foo/foo.ko.stripped
SIGN [M] fs/foo/foo.ko
will appear in the build log. If the signature step will be skipped and the following will be seen:
LD [M] fs/foo/foo.ko.unsigned
STRIP [M] fs/foo/foo.ko.stripped
NO SIGN [M] fs/foo/foo.ko
NOTE! After the signature step, the signed module must not be passed through strip. The unstripped, unsigned module is still available at the name on the LD [M] line. This restriction may affect packaging tools (such as rpmbuild) and initramfs composition tools.
Note that I do not agree with this method of attaching signatures to modules.
---
scripts/Makefile.modpost | 98 ++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 97 insertions(+), 1 deletions(-)
scripts/Makefile.modpost +97 -1
@@ -14,7 +14,8 @@ # 3) create one <module>.mod.c file pr. module # 4) create one Module.symvers file with CRC for all exported symbols # 5) compile all <module>.mod.c files -# 6) final link of the module to a <module.ko> file +# 6) final link of the module to a <module.ko> (or <module.unsigned>) file +# 7) signs the modules to a <module.ko> file # Step 3 is used to place certain information in the module's ELF # section, including information such as:
@@ -32,6 +33,8 @@ # Step 4 is solely used to allow module versioning in external modules, # where the CRC of each module is retrieved from the Module.symvers file. +# Step 7 is dependent on CONFIG_MODULE_SIG being enabled. + # KBUILD_MODPOST_WARN can be set to avoid error out in case of undefined # symbols in the final module linking stage # KBUILD_MODPOST_NOFINAL can be set to skip the final link of modules.
@@ -116,6 +119,7 @@ $(modules:.ko=.mod.o): %.mod.o: %.mod.c FORCE targets += $(modules:.ko=.mod.o) # Step 6), final link of the modules +ifneq ($(CONFIG_MODULE_SIG),y) quiet_cmd_ld_ko_o = LD [M] $@ cmd_ld_ko_o = $(LD) -r $(LDFLAGS) \ $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \
@@ -125,7 +129,99 @@ $(modules): %.ko :%.o %.mod.o FORCE $(call if_changed,ld_ko_o) targets += $(modules) +else +quiet_cmd_ld_ko_unsigned_o = LD [M] $@ + cmd_ld_ko_unsigned_o = \ + $(LD) -r $(LDFLAGS) \ + $(KBUILD_LDFLAGS_MODULE) $(LDFLAGS_MODULE) \ + -o $@ $(filter-out FORCE,$^) \ + $(if $(AFTER_LINK),; $(AFTER_LINK)) + +$(modules:.ko=.ko.unsigned): %.ko.unsigned :%.o %.mod.o FORCE + $(call if_changed,ld_ko_unsigned_o) + +targets += $(modules:.ko=.ko.unsigned) + +# Step 7), sign the modules +MODSECKEY = ./modsign.sec +MODPUBKEY = ./modsign.pub +KEYFLAGS = --no-default-keyring --secret-keyring $(MODSECKEY) --keyring $(MODPUBKEY) --no-default-keyring --homedir . --no-options --no-auto-check-trustdb --no-permission-warning + +ifdef CONFIG_MODULE_SIG_SHA1 +KEYFLAGS += --digest-algo=SHA1 +else +ifdef CONFIG_MODULE_SIG_SHA224 +KEYFLAGS += --digest-algo=SHA224 +else +ifdef CONFIG_MODULE_SIG_SHA256 +KEYFLAGS += --digest-algo=SHA256 +else +ifdef CONFIG_MODULE_SIG_SHA384 +KEYFLAGS += --digest-algo=SHA384 +else +ifdef CONFIG_MODULE_SIG_SHA512 +KEYFLAGS += --digest-algo=SHA512 +else +endif +endif +endif +endif +endif + +ifdef MODKEYNAME +KEYFLAGS += --default-key $(MODKEYNAME) +endif + +ifeq ($(wildcard $(MODSECKEY))+$(wildcard $(MODPUBKEY)),$(MODSECKEY)+$(MODPUBKEY)) +ifeq ($(KBUILD_SRC),) + # no O= is being used + SCRIPTS_DIR := scripts +else + SCRIPTS_DIR := $(KBUILD_SRC)/scripts +endif +SIGN_MODULES := 1 +else +SIGN_MODULES := 0 +endif + +# only sign if it's an in-tree module +ifneq ($(KBUILD_EXTMOD),) +SIGN_MODULES := 0 +endif + +# We strip the module as best we can - note that using both strip and eu-strip +# results in a smaller module than using either alone. +quiet_cmd_sign_ko_stripped_ko_unsigned = STRIP [M] $@ + cmd_sign_ko_stripped_ko_unsigned = \ + cp $< $@ && \ + strip -x -g $@ && \ + eu-strip $@ + +ifeq ($(SIGN_MODULES),1) +KEYRING_DEP := modsign.sec modsign.pub +quiet_cmd_sign_ko_ko_stripped = SIGN [M] $@ + cmd_sign_ko_ko_stripped = \ + rm -f $<.sig && \ + gpg --batch --no-greeting $(KEYFLAGS) -b $< && \ + stat -c @%-8s@ $< >[email protected] && \ + stat -c @%-8s@ $<.sig >>[email protected] && \ + echo -n "This Is A Crypto Signed Module" >>[email protected] && \ + cat $< $<.sig [email protected] >$@ +else +KEYRING_DEP := +quiet_cmd_sign_ko_ko_unsigned = NO SIGN [M] $@ + cmd_sign_ko_ko_unsigned = \ + cp $< $@ +endif + +$(modules): %.ko :%.ko.stripped $(KEYRING_DEP) FORCE + $(call if_changed,sign_ko_ko_stripped) + +$(patsubst %.ko,%.ko.stripped,$(modules)): %.ko.stripped :%.ko.unsigned FORCE + $(call if_changed,sign_ko_stripped_ko_unsigned) +targets += $(modules) +endif # Add FORCE to the prequisites of a target to force it to be always rebuilt. # ---------------------------------------------------------------------------
David Howells
maintainerPATCH 20/23 MODSIGN: Provide module signing public keys to the kernel
In reply to David HowellsInclude a PGP keyring containing the public keys required to perform module verification in the kernel image during build and create a special keyring during boot which is then populated with keys of crypto type holding the public keys found in the PGP keyring.
These can be seen by root:
[root@andromeda ~]# cat /proc/keys
07ad4ee0 I----- 1 perm 3f010000 0 0 crypto modsign.0: RSA 87b9b3bd [] 15c7f8c3 I----- 1 perm 1f030000 0 0 keyring .module_sign: 1/4
...
It is probably worth permitting root to invalidate these keys, resulting in their removal and preventing further modules from being loaded with that key.
---
kernel/Makefile | 3 ++ kernel/modsign-pubkey.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++ kernel/module-verify.h | 14 +++++++++ 3 files changed, 91 insertions(+), 0 deletions(-) create mode 100644 kernel/modsign-pubkey.c create mode 100644 kernel/module-verify.h
kernel/Makefile +3 -0
@@ -51,6 +51,7 @@ obj-$(CONFIG_DEBUG_SPINLOCK) += spinlock.o obj-$(CONFIG_PROVE_LOCKING) += spinlock.o obj-$(CONFIG_UID16) += uid16.o obj-$(CONFIG_MODULES) += module.o +obj-$(CONFIG_MODULE_SIG) += modsign-pubkey.o obj-$(CONFIG_KALLSYMS) += kallsyms.o obj-$(CONFIG_BSD_PROCESS_ACCT) += acct.o obj-$(CONFIG_KEXEC) += kexec.o
@@ -127,3 +128,5 @@ quiet_cmd_timeconst = TIMEC $@ targets += timeconst.h $(obj)/timeconst.h: $(src)/timeconst.pl FORCE $(call if_changed,timeconst) + +kernel/modsign-pubkey.o: modsign.pub
kernel/modsign-pubkey.c new file +74 -0
74 lines not on this page · raw message
kernel/module-verify.h new file +14 -0
@@ -0,0 +1,14 @@ +/* Module verification definitions +* +* Copyright (C) 2004, 2012 Red Hat, Inc. All Rights Reserved. +* Written by David Howells ([email protected]) +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public Licence +* as published by the Free Software Foundation; either version +* 2 of the Licence, or (at your option) any later version. +*/ + +#ifdef CONFIG_MODULE_SIG +extern struct key *modsign_keyring; +#endif
David Howells
maintainerPATCH 22/23 MODSIGN: Automatically generate module signing keys if missing
In reply to David HowellsAutomatically generate keys for module signing if they're absent so that allyesconfig doesn't break. The builder should consider generating their own keyrings, however, so that the keys are appropriately named and any extra keys required get imported.
Also change the names of the keyring files to modsign.pub and modsign.sec so that they are then a more obvious what they're about and add a dependency for the signing rules on the keyring files so that the signatures get regenerated if the keyrings change.
---
kernel/Makefile | 39 +++++++++++++++++++++++++++++++++++++++ 1 files changed, 39 insertions(+), 0 deletions(-)
kernel/Makefile +39 -0
@@ -129,4 +129,43 @@ targets += timeconst.h $(obj)/timeconst.h: $(src)/timeconst.pl FORCE $(call if_changed,timeconst) +############################################################################### +# +# If module signing is requested, say by allyesconfig, but a key has not been +# supplied, then one will need to be generated to make sure the build does not +# fail and that the kernel may be used afterwards. +# +############################################################################### +ifeq ($(CONFIG_MODULE_SIG),y) kernel/modsign-pubkey.o: modsign.pub + +modsign.pub modsign.sec: genkey + @echo "###" + @echo "### Now generating a PGP key pair to be used for signing modules." + @echo "###" + @echo "### If this takes a long time, you might wish to run rngd in the" + @echo "### background to keep the supply of entropy topped up. It" + @echo "### needs to be run as root, and should use a hardware random" + @echo "### number generator if one is available, eg:" + @echo "###" + @echo "### rngd -r /dev/hwrandom" + @echo "###" + gpg --homedir . --batch --gen-key genkey + @echo "###" + @echo "### Key pair generated." + @echo "###" + rm -f pubring.gpg secring.gpg trustdb.gpg + +genkey: + echo "%pubring modsign.pub" >genkey + echo "%secring modsign.sec" >>genkey + echo "%no-protection: yes" >> genkey + echo "%transient-key: yes" >>genkey + echo "Key-Type: RSA" >>genkey + echo "Key-Length: 4096" >>genkey + echo "Name-Real: Sample kernel key" >>genkey + echo "Name-Comment: Sample kernel module signing key" >>genkey + echo "%commit" >>genkey + +endif +CLEAN_FILES += modsign.pub modsign.sec genkey random_seed
David Howells
maintainerPATCH 23/23 MODSIGN: Panic the kernel if FIPS is enabled upon module signing failure
In reply to David HowellsIf module signing fails when the kernel is running with FIPS enabled then the kernel should panic lest the crypto layer be compromised. Possibly a panic shouldn't happen on cases like ENOMEM.
---
kernel/module-verify.c | 5 +++++ 1 files changed, 5 insertions(+), 0 deletions(-)
kernel/module-verify.c +5 -0
@@ -19,6 +19,7 @@#include <linux/sched.h> #include <linux/modsign.h> #include <linux/moduleparam.h> +#include <linux/fips.h> #include <keys/crypto-type.h> #include "module-verify.h"
@@ -109,6 +110,10 @@ int module_verify(const void *data, size_t size, bool *_gpgsig_ok)pr_devel ("module_verify_signature() = %d\n" , ret); +if (ret <0 && fips_enabled) +panic ("Module verification failed with error %d in FIPS mode\n" , + ret); +switch (ret) {case 0 :/* Good signature */ *_gpgsig_ok = true;
David Howells
maintainerPATCH 21/23 MODSIGN: Module signature verification
In reply to David HowellsApply signature checking to modules on module load, checking the signature against the ring of public keys compiled into the kernel (if enabled by CONFIG_MODULE_SIG).
There are several reasons why these patches are useful, amongst which are:
(1) to prevent accidentally corrupted modules from causing damage;
(2) to prevent maliciously modified modules from causing damage;
(3) to allow a sysadmin (or more likely an IT department) to enforce a policy that only known and approved modules shall be loaded onto machines which they're expected to support;
(4) to allow other support providers to do likewise, or at least to _detect_
the fact that unsupported modules are loaded;
(5) to allow the detection of modules replaced by a second-order distro or a preloaded Linux purveyor.
These patches have two main appeals: (a) preventing malicious modules from being loaded, and (b) reducing support workload by pointing out modules on a crashing box that aren't what they're expected to be.
Note that this is not a complete solution by any means: the core kernel is not protected, and nor are /dev/mem or /dev/kmem, but it denies (or at least controls) one relatively simple attack vector. To protect the kernel image would be the responsibility of the boot loader or the system BIOS.
This facility is optional: the builder of a kernel is by no means under any requirement to actually enable it, let alone force the set of loadable modules to be restricted to just those that the builder provides (there are degrees of restriction available).
If CONFIG_MODULE_SIG_FORCE is enabled or "enforcemodulesig=1" is supplied on the kernel command line, the kernel will _only_ load validly signed modules for which it has a public key. Otherwise, it will also load modules that are unsigned. Any module for which the kernel has a key, but which proves to have a signature mismatch will not be permitted to load.
This table indicates the behaviours in the various situations:
MODULE STATE PERMISSIVE MODE ENFORCING MODE
======================================= =============== ===============
Unsigned Ok EKEYREJECTED
Signed, no public key ENOKEY ENOKEY
Validly signed, public key Ok Ok
Invalidly signed, public key EKEYREJECTED EKEYREJECTED
Validly signed, expired key EKEYEXPIRED EKEYEXPIRED
Signed, hash algorithm unavailable ENOPKG ENOPKG
Signed, pubkey algorithm unavailable ENOPKG ENOPKG
Signature without sig packet ENOMSG ENOMSG
Corrupt signature EBADMSG EBADMSG
Corrupt file ELIBBAD ELIBBAD
=======================
!!!IMPORTANT WARNING!!!
=======================
Signed modules generated by this kernel very likely CANNOT be used with existing packaging and installation infrastructure. For example, in Fedora's environment, the module is potentially stripped at least twice:
(1) by rpmbuild when the debuginfo is detached from the module, and
(2) by the initrd image composer to reduce the module size.
Both of these will potentially result in the module signature being discarded or rendered unverifiable, resulting in the module load just going ahead if the signature magic is not found and enforcemodulesig=1 not being supplied or -EKEYREJECTED being given or a panic being forced if FIPS mode is engaged.
To aid with (2), the module is completely stripped prior to signing as it cannot be stripped after signing. Both "strip -x -g" and "eu-strip" are applied as the use of both of these results in a smaller binary.
That, however, means there is no debug information directly available for the module.
The original unstripped binary for the foo.ko module can be found as foo.ko.unsigned in the build tree. It may be possible to use this as the debug info source.
---
include/linux/module.h | 3 + kernel/Makefile | 2 - kernel/module-verify.c | 148 ++++++++++++++++++++++++++++++++++++++++++++++++ kernel/module-verify.h | 6 ++ kernel/module.c | 26 +++++++- 5 files changed, 179 insertions(+), 6 deletions(-) create mode 100644 kernel/module-verify.c
include/linux/module.h +3 -0
@@ -227,6 +227,9 @@ struct module/* Unique handle for this module */ char name[MODULE_NAME_LEN ]; +/* Is this module GPG signed */ +bool gpgsig_ok; +/* Sysfs stuff. */ struct module_kobject mkobj;struct module_attribute *modinfo_attrs;
kernel/Makefile +1 -1
@@ -51,7 +51,7 @@ obj-$(CONFIG_DEBUG_SPINLOCK) += spinlock.o obj-$(CONFIG_PROVE_LOCKING) += spinlock.o obj-$(CONFIG_UID16) += uid16.o obj-$(CONFIG_MODULES) += module.o -obj-$(CONFIG_MODULE_SIG) += modsign-pubkey.o +obj-$(CONFIG_MODULE_SIG) += module-verify.o modsign-pubkey.o obj-$(CONFIG_KALLSYMS) += kallsyms.o obj-$(CONFIG_BSD_PROCESS_ACCT) += acct.o obj-$(CONFIG_KEXEC) += kexec.o
kernel/module-verify.c new file +148 -0
148 lines not on this page · raw message
kernel/module-verify.h +6 -0
@@ -11,4 +11,10 @@#ifdef CONFIG_MODULE_SIG extern struct key *modsign_keyring; +extern int module_verify (const void *data,size_t size,bool *_gpgsig_ok); +#else +static inline int module_verify (const void *data,size_t size,bool *_gpgsig_ok) +{ +return 0 ; +}#endif
kernel/module.c +21 -5
@@ -58,6 +58,7 @@#include <linux/jump_label.h> #include <linux/pfn.h> #include <linux/bsearch.h> +#include "module-verify.h" #define CREATE_TRACE_POINTS #include <trace/events/module.h>
@@ -2402,7 +2403,8 @@ static inline void kmemleak_load_module(const struct module *mod,/* Sets info->hdr and info->len. */ static int copy_and_check (struct load_info *info,const void __user *umod,unsigned long len, -const char __user *uargs) +const char __user *uargs, +bool *_gpgsig_ok) {int err;Elf_Ehdr *hdr;
@@ -2435,6 +2437,12 @@ static int copy_and_check(struct load_info *info, goto free_hdr; } +/* Verify the module's contents */ + *_gpgsig_ok = false; + err =module_verify (hdr, len, _gpgsig_ok); +if (err <0 ) + goto free_hdr; + info->hdr = hdr; info->len = len;return 0 ;
@@ -2777,7 +2785,8 @@ int __weak module_frob_arch_sections(Elf_Ehdr *hdr,return 0 ; } -static struct module *layout_and_allocate (struct load_info *info) +static struct module *layout_and_allocate (struct load_info *info, +bool gpgsig_ok) {/* Module within temporary copy. */ struct module *mod;
@@ -2787,6 +2796,7 @@ static struct module *layout_and_allocate(struct load_info *info) mod =setup_load_info (info);if (IS_ERR (mod))return mod; + mod->gpgsig_ok = gpgsig_ok; err =check_modinfo (mod, info);if (err)
@@ -2870,17 +2880,18 @@ static struct module *load_module(void __user *umod,struct load_info info = {NULL , };struct module *mod;long err; +bool gpgsig_ok;pr_debug ("load_module: umod=%p, len=%lu, uargs=%p\n" , umod, len, uargs);/* Copy in the blobs from userspace, check they are vaguely sane. */ - err =copy_and_check (&info, umod, len, uargs); + err =copy_and_check (&info, umod, len, uargs, &gpgsig_ok);if (err)return ERR_PTR (err);/* Figure out module layout, and allocate all the memory. */ - mod =layout_and_allocate (&info); + mod =layout_and_allocate (&info, gpgsig_ok);if (IS_ERR (mod)) { err =PTR_ERR (mod); goto free_copy;
@@ -3517,8 +3528,13 @@ void print_modules(void)printk (KERN_DEFAULT "Modules linked in:" );/* Most callers should already have preempt disabled, but make sure */ preempt_disable (); -list_for_each_entry_rcu (mod, &modules, list) +list_for_each_entry_rcu (mod, &modules, list) {printk (" %s%s" , mod->name,module_flags (mod, buf)); +#ifdef CONFIG_MODULE_SIG +if (!mod->gpgsig_ok) +printk ("(U)" ); +#endif + }preempt_enable ();if (last_unloaded_module[0 ])printk (" [last unloaded: %s]" , last_unloaded_module);
Quoted 11 lines · David Howells
The extended module file format is as follows:
The module signature is appended to the end of the module file, followed by "@mod_size@\n@sig_size@\nThis Is A Crypto Signed Module".
The EOF must follow the magic string directly, so nothing further must be appended to the file.
mod_sizeandsig_sizeare left-aligned decimal numbers, space-padded to 8 characters.mod_sizeis the size of the module payload part of the file andsig_sizeis the size of the signature blob.
Hi David,
That's pretty weird. Why not put the "@This Is A Crypto Signed
Module\n" before the signature? Then module-size is implied: everything before that signature. The signature size is implied: everything after that signature.
In fact, I'd modify this slightly, to allow multiple signatures.
This would work nicely with a deterministic strip. Find the signatures backward, and truncate as they fail.
If you want to be super-paranoid, scan for that signature before
signing the module.
Cheers,
Rusty.
David Howells
maintainerQuoted 4 lines · Rusty Russell
That's pretty weird. Why not put the "@This Is A Crypto Signed
Module\n" before the signature? Then module-size is implied: everything before that signature. The signature size is implied: everything after that signature.
This makes it simpler. No scanning required. The magic number can only be in one place and you can find it by dead reckoning.
Quoted 3 lines
In fact, I'd modify this slightly, to allow multiple signatures.
This would work nicely with a deterministic strip. Find the signatures backward, and truncate as they fail.
Why would you want multiple signatures? That just complicates things. If you're in FIPS mode, you probably have to panic if any of them fail.
I suppose I may as well punt the signature detection and removal to userspace and pass the signature as an argument to init_module() as Dmitry suggested. Then the signature need not be in the file at all (he wants to use an xattr or hardware, I think). mkinitrd and rpmbuild/kernel spec have to be changed to accommodate enablement of these patches, so why not module-init-tools, dracut and busybox whilst we're at it?
David
Quoted 9 lines · David Howells
Quoted 4 lines · Rusty Russell
That's pretty weird. Why not put the "@This Is A Crypto Signed
Module\n" before the signature? Then module-size is implied: everything before that signature. The signature size is implied: everything after that signature.This makes it simpler. No scanning required. The magic number can only be in one place and you can find it by dead reckoning.
Scanning isn't complicated. Slow, sure, but I doubt you can really measure it when you're doing crypto.
Compare:
(1) Your scheme signing looks something like this:
gpg --sign $m > $m.sig
MSIZE=`ls -l $m | awk '{ print $5 }'`
SSIZE=`ls -l $m.sig | awk '{ print $5 }'`
printf '@%-10i@%-10i@This Is A Crypto Signed Module' $MSIZE $SSIZE >> $m(2) Your verification scheme looks like this:
+ magic_size = sizeof(modsign_magic) - 1;
+ if (size <= 11 + 11 + magic_size)
+ return 1;
+
+ if (memcmp(data + size - magic_size, modsign_magic, magic_size) != 0)
+ return 1;
+ size -= 11 + 11 + magic_size;
+
+ cp = data + size;
+ if (cp[ 0] != '@' && cp[ 9] != '@' && cp[10] != '\n' &&
+ cp[11] != '@' && cp[20] != '@' && cp[21] != '\n')
+ return -ELIBBAD;
+ mod_size = simple_strtoul(cp + 1, &end, 10);
+ if (mod_size > size || (*end != ' ' && *end != '@'))
+ return -ELIBBAD;
+ sig_size = simple_strtoul(cp + 12, &end, 10);
+ if (sig_size > size || (*end != ' ' && *end != '@'))
+ return -ELIBBAD;
+
+ pr_devel("sig at %zu, size %zu (to %zu)\n", mod_size, sig_size,
size);
+ if (size - mod_size != sig_size)
+ return -ELIBBAD;
Now, the scheme I suggested looks like this:
(1) Signing:
gpg --sign $m > $m.sig
(echo @This Is A Crypto Signed Module; cat $m.sig) >> $m
(2) Verification:
size_t i;
if (i < modsign_magic)
return 1;
for (i = size - modsign_magic;
memcmp(data + i, modsign_magic, magic_size) != 0);
i++) {
if (i == 0)
return 1;
}
/* module: "data", size "i".
* sig: "data + i + magic_size", size "size - (i + magic_size)" */Quoted 5 lines
Quoted 3 lines
In fact, I'd modify this slightly, to allow multiple signatures.
This would work nicely with a deterministic strip. Find the signatures backward, and truncate as they fail.Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
Quoted 1 line
If you're in FIPS mode, you probably have to panic if any of them fail.
I had to look up what FIPS was, so I'm not qualified to comment.
Quoted 6 lines
I suppose I may as well punt the signature detection and removal to userspace and pass the signature as an argument to
init_module()as Dmitry suggested. Then the signature need not be in the file at all (he wants to use an xattr or hardware, I think). mkinitrd and rpmbuild/kernel spec have to be changed to accommodate enablement of these patches, so why not module-init-tools, dracut and busybox whilst we're at it?
In some ways that is cleaner, but it's also nice to avoid adding another syscall.
Cheers,
Rusty.
David Howells
maintainerQuoted 6 lines · Rusty Russell
(1) Your scheme signing looks something like this:
gpg --sign $m > $m.sig MSIZE=`ls -l $m | awk '{ print $5 }'` SSIZE=`ls -l $m.sig | awk '{ print $5 }'` printf '@%-10i@%-10i@This Is A Crypto Signed Module' $MSIZE $SSIZE >> $m
It doesn't really need the @ signs or the MSIZE; they can be dropped.
gpg --batch --no-greeting $(KEYFLAGS) -b $< && \ stat --printf %-5s $<.sig >[email protected] && \ echo -n "This Is A Crypto Signed Module" >>[email protected] && \ cat $< $<.sig [email protected] >$@
Further, the signature size field can be reduced to 5 decimal digits easily - if the signature is larger than 99999 bytes, there's very likely a problem somewhere.
Oh, and I should use --printf, not -c with stat as the newline char is unneeded.
That then adds 5 bytes to the magic string. Is that really so bad?
And if you object to generating a foo.ko.trailer file, then:
gpg --batch --no-greeting $(KEYFLAGS) -b $< && \ (cat $< $<.sig && \ stat --printf %-5s $<.sig && \ echo -n "This Is A Crypto Signed Module" && \ ) >$@
Note that this scheme does not preclude using multiple signatures as you desire, but since you have no record of the module length you'd either have to parse all the signature records first to find the end of the module, or include each preceding signature and marker in the digest for the next one (which shouldn't be a problem). You should still check all signatures anyway and verify all for which you have the public key.
You could even stick other types of record in with different magic strings terminating them, provided you include a length.
Quoted 1 line
(2) Your verification scheme looks like this:
A chunk of which can be discarded with the above reductions.
Quoted 8 lines
Now, the scheme I suggested looks like this:
...for (i = size - modsign_magic; memcmp(data + i, modsign_magic, magic_size) != 0); i++) { if (i == 0) return 1; }
Which will likely oops. You need to decrement i, not increment it, but that's a minor detail. You're also subtracting a pointer from a size.
And no, I won't do this. It's unnecessary and a potentially large overhead. Say you've got a module that's 7.7M in size (an unstripped, unsigned CIFS module for example)... That's nearly eight *million* calls to memcmp() if there's no signature. I suspect that's on the order of a tenth of a second or longer on most machines.
Stripped, CIFS is still on the order of half a meg - which in itself translates to half a million calls to memcmp() if there's no signature.
Furthermore, the data cache may be of limited utility as it can't do readahead as you're scanning backwards through the image. You'd be much better off doing a memchr() or just open-coding a forward search for 'T', and then doing the memcmp() at each instance. Better still, don't do the scan at all.
Doing a SHA digest on some machines will be done with hardware assistance (s390, for example) - so this scan may take longer than the digest there.
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
More importantly, a major problem with (multiple) signatures is that each signing event has to risk exposing the private key - so you really only want to sign once unless you cannot avoid it. Further, in an automated system, the private key cannot be protected by a password as all the secrets have to be passed to the signer.
Trying to automatically save a during-build generated private key or trying to get a private key into the build from within the RHEL and Fedora automated build systems risks having a key stolen or having someone substitute their own key - and also makes it more complicated to build a kernel outside of the build system.
The way I handle the private key in these patches is with transience: A fresh key is generated during a build from a clean tree and then discarded when the build tree is deleted. This key is then a one-off. If it is stolen or cracked, it can only affect a single build of the kernel.
Note that we _do_ allow extra public keys to be installed in the kernel as there's much less risk there, and further they have to be there to permit signature verification.
David
Quoted 77 lines · Rusty Russell
Quoted 9 lines · David Howells
Quoted 4 lines · Rusty Russell
That's pretty weird. Why not put the "@This Is A Crypto Signed Module\n" before the signature? Then module-size is implied: everything before that signature. The signature size is implied: everything after that signature.
This makes it simpler. No scanning required. The magic number can only be in one place and you can find it by dead reckoning.
Scanning isn't complicated. Slow, sure, but I doubt you can really measure it when you're doing crypto.
Compare:
(1) Your scheme signing looks something like this:
gpg --sign $m > $m.sig
MSIZE=ls -l $m | awk '{ print $5 }'SSIZE=ls -l $m.sig | awk '{ print $5 }'printf '@%-10i@%-10i@This Is A Crypto Signed Module' $MSIZE $SSIZE >> $m
(2) Your verification scheme looks like this:
+ magic_size =
sizeof(modsign_magic)- 1;
+ if (size <= 11 + 11 +magic_size)
+ return 1;
+
+ if (memcmp(data + size - magic_size, modsign_magic, magic_size)!= 0)
+ return 1;
+ size -= 11 + 11 +magic_size;
+
+ cp = data + size;
+ if (cp[ 0] != '@' && cp[ 9] != '@' && cp[10] != '\n' &&
+ cp[11] != '@' && cp[20] != '@' && cp[21] != '\n')
+ return-ELIBBAD;
+ mod_size =simple_strtoul(cp + 1, &end, 10);
+ if (mod_size> size || (*end != ' ' && *end != '@'))
+ return-ELIBBAD;
+ sig_size =simple_strtoul(cp + 12, &end, 10);
+ if (sig_size> size || (*end != ' ' && *end != '@'))
+ return-ELIBBAD;
+
+ pr_devel("sig at %zu, size %zu (to %zu)\n",mod_size,sig_size, size);
+ if (size -mod_size!=sig_size)
+ return-ELIBBAD;Now, the scheme I suggested looks like this:
(1) Signing:
gpg --sign $m > $m.sig
(echo @This Is A Crypto Signed Module; cat $m.sig) >> $m(2) Verification:
size_t i;if (i <
modsign_magic)
return 1;for (i = size -
modsign_magic;
memcmp(data + i, modsign_magic, magic_size)!= 0); i++) {
if (i == 0)
return 1;
}/* module: "data", size "i".
* sig: "data + i +magic_size", size "size - (i +magic_size)" */Quoted 5 lines
Quoted 3 lines
In fact, I'd modify this slightly, to allow multiple signatures. This would work nicely with a deterministic strip. Find the signatures backward, and truncate as they fail.
Why would you want multiple signatures? That just complicates things.
Quoted 15 lines
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
Quoted 1 line
If you're in FIPS mode, you probably have to panic if any of them fail.
I had to look up what FIPS was, so I'm not qualified to comment.
Quoted 6 lines
I suppose I may as well punt the signature detection and removal to userspace and pass the signature as an argument to
init_module()as Dmitry suggested. Then the signature need not be in the file at all (he wants to use an xattr or hardware, I think). mkinitrd and rpmbuild/kernel spec have to be changed to accommodate enablement of these patches, so why not module-init-tools, dracut and busybox whilst we're at it?
Actually it is not for hw.
I have implemented reading of signature from security.ima xattr and from .sig file.
http://linux-ima.git.sourceforge.net/git/gitweb.cgi?p=linux-ima/module-init-tools.git;a=summary
Quoted 3 lines
In some ways that is cleaner, but it's also nice to avoid adding another syscall.
There is no additional syscall.
signature is passed is 'ima=' parameter to init_module() like
----------------------------------------------------------
root@ubuntu:~# modprobe -v button insmod /lib/modules/3.4.0-rc5-kds+/kernel/drivers/acpi/button.ko ima=016e7cbb4f00005d2b05fc633ee3e8010400ad30f2e50d52456ef4a4f0c540f3c8d9955b7ea125cd2dd0cb41216d1388801427c6bddc1431c82e4e82372e6a2101afdcf0daa4f59e1b3d9581d9f1fd0f003fede88d6679814a0887e056a7ddabf070e96cdf5901201d7a6cd4717af68500bd2af88d078a9f1cfc136f5e2d8d0df710121fbb5658c248714f77bb6879aba7b4 ----------------------------------------------------------
- Dmitry
Quoted 7 lines
Cheers,
Rusty.
--
To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
David Howells
maintainerQuoted 6 lines · Dmitry
Quoted 2 lines
In some ways that is cleaner, but it's also nice to avoid adding another syscall.
There is no additional syscall.
signature is passed is 'ima=' parameter toinit_module()like
Exactly what I was thinking of, though I wouldn't call it "ima=" as that doesn't seem specific enough.
You could also append it to the binary image and have the kernel extract it from there as if the module file had had the signature attached during the build.
I don't particularly favour holding the signature in an xattr, though, as that assumes that underlying fs has the capability to hold it and means that the package installation mechanism must know how to fill in xattrs.
David
David Howells
maintainerI've posted a new version with Tetsuo's comments fixed and module_verify_signature() reduced to:
static int module_verify_signature(const void *data, size_t size)
{
struct crypto_key_verify_context *mod_sig;
const char *cp, *sig;
char *end;
size_t magic_size, sig_size, mod_size;
int ret;
magic_size = sizeof(modsign_magic) - 1;
if (size <= 5 + magic_size)
return 1;
if (memcmp(data + size - magic_size, modsign_magic, magic_size) != 0)
return 1;
size -= 5 + magic_size;
cp = data + size;
sig_size = simple_strtoul(cp, &end, 10);
if (sig_size >= size || (*end != ' ' && *end != 'T'))
return -ELIBBAD;
mod_size = size - sig_size;
sig = data + mod_size;
/* Find the crypto key for the module signature
* - !!! if this tries to load the required hash algorithm module,
* we will deadlock!!!
*/
mod_sig = verify_sig_begin(modsign_keyring, sig, sig_size);
if (IS_ERR(mod_sig)) {
pr_err("Couldn't initiate module signature verification: %ld\n",
PTR_ERR(mod_sig));
return PTR_ERR(mod_sig);
}
/* Load the module contents into the digest */
ret = verify_sig_add_data(mod_sig, data, mod_size);
if (ret < 0) {
verify_sig_cancel(mod_sig);
return ret;
}
/* Do the actual signature verification */
ret = verify_sig_end(mod_sig, sig, sig_size);
pr_devel("verify-sig : %d\n", ret);
return ret;
}See:
David
Quoted 11 lines · David Howells
Quoted 6 lines · Dmitry
Quoted 2 lines
In some ways that is cleaner, but it's also nice to avoid adding another syscall.
There is no additional syscall.
signature is passed is 'ima=' parameter toinit_module()likeExactly what I was thinking of, though I wouldn't call it "ima=" as that doesn't seem specific enough.
IMA-appraisal maintains the file integrity metadata.
Quoted 7 lines
You could also append it to the binary image and have the kernel extract it from there as if the module file had had the signature attached during the build.
I don't particularly favour holding the signature in an xattr, though, as that assumes that underlying fs has the capability to hold it and means that the package installation mechanism must know how to fill in xattrs.
Labeling files for integrity is a general issue, not limited to kernel modules/ELF files. For this reason, we need a generic mechanism that works for all files, not only those that are executables. For local files, such as configuration files, which are system specific, files are labeled with hashes(IMA-appraisal) and HMAC(EVM).
Yes, the package update mechanisms will need to be modified to install both the file data and the associated file metadata - hash, signature. Tar supports xattrs. The original CPIO format doesn't, but there are extensions that do.
The issue here is whether we want the integrity metadata for kernel modules to be stored differently than for all other files.
Mimi
David Howells
maintainerQuoted 2 lines · Mimi Zohar
The issue here is whether we want the integrity metadata for kernel modules to be stored differently than for all other files.
Surely it's handled differently. The kernel is told by insmod what the signature should be in your scheme rather than going looking for it itself. In such a case, why not include the signature in the module file? It's more efficient on the filesystem, doesn't require xattr support and is easier for things like the initramfs composer to deal with.
Btw, am I right in thinking that with IMA, the kernel itself normally goes and finds the signature (if there is one) for a file when it needs to open a file? Do you only check the IMA when exec'ing a file or whenever you open it?
David
Quoted 10 lines · David Howells
Quoted 2 lines · Mimi Zohar
The issue here is whether we want the integrity metadata for kernel modules to be stored differently than for all other files.
Surely it's handled differently. The kernel is told by insmod what the signature should be in your scheme rather than going looking for it itself. In such a case, why not include the signature in the module file? It's more efficient on the filesystem, doesn't require xattr support and is easier for things like the initramfs composer to deal with.
Yes, unfortunately, it is handled differently. Instead of passing a file descriptor, a buffer containing the file data is passed. Without the file descriptor, you also need to pass the file metadata, in this case, the signature as well. Whether the signature is passed as a separate parameter or appended to the file, it still is being passed to the kernel.
Quoted 5 lines
Btw, am I right in thinking that with IMA, the kernel itself normally goes and finds the signature (if there is one) for a file when it needs to open a file? Do you only check the IMA when exec'ing a file or whenever you open it?
David
IMA measures a file and appraises file data integrity based on the IMA measurement/appraisal policy. There are currently 3 hooks: open - ima_file_check(), exec - ima_bprm_check() and mmap - ima_file_mapp().
I don't know the reasons or history for passing the file data content, instead of a file descriptor, but if a file descriptor were passed, then module integrity appraisal could simply be another integrity hook.
Mimi
David Howells
maintainerHi Rusty,
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
You can use it with the attached patch to kmod.git. I've passed the signature length in the argument as it permits the kernel to preallocate the buffer it decodes the signature into, but that's not actually necessary.
David
---
commit e4c9290fc949bc41f942f00a1460d9d90fc1775c
Author: David Howells <[email protected]> Date: Fri May 25 16:35:19 2012 +0100
libkmod: Extract module signature and prepend on module argument list
Extract the module signature from the module image, if present, and prepend on the module argument list hexcoded as
"modsign=l,x "
Where "l" is the length of the signature as a decimal number and "x" is the hex-encoded signature data.
libkmod/libkmod-module.c +90 -0
@@ -756,6 +756,88 @@ KMOD_EXPORT int kmod_module_remove_module(struct kmod_module *mod,return err; } +static const char kmod_modsign_magic[] ="This Is A Crypto Signed Module" ; +static const char kmod_arg_key[] ="modsign=" ; + +/** +* kmod_find_signature: +* @mod: kmod module +* @mem: The module contents +* @_size: The size of the module contents (updated if sig removed) +* @args: Argument string +* @_new_args: Where to place the updated argument list +* +* Returns: 0 on success or < 0 on failure. -ELIBBAD is returned is the module +* format cannot be parsed. +*/ +static int kmod_find_signature (struct kmod_module *mod, +const void *mem,off_t *_size, +const char *args,char **_new_args) +{ +const unsigned char *sig, *data = mem; +const char *cp; +char *new_args, *dp, *end; +size_t magic_size, sig_size, mod_size, arg_size, new_arg_size, size = *_size; + +INFO (mod->ctx,"Look for signature in module image\n" ); + + magic_size =sizeof (kmod_modsign_magic) -1 ; +if (size <=5 + magic_size) +return 0 ; + +if (memcmp (data + size - magic_size, kmod_modsign_magic, magic_size) !=0 ) +/* Probably want to check for IMA signature file or xattr here */ +return 0 ; + size -=5 + magic_size; + +INFO (mod->ctx,"Signature marker found in module\n" ); + + cp = (const char *)data + size; + sig_size =strtoul (cp, &end,10 ); +if (sig_size >= size || (*end !=' ' && *end !='T' )) +return -ELIBBAD ; + + mod_size = size - sig_size; +INFO (mod->ctx,"Module size %zu Signature size %zu\n" , mod_size, sig_size); +if (sig_size <=0 ) +return -ENOMSG ; +if (sig_size >65535 ) +return -EMSGSIZE ; + + sig = data + mod_size; +INFO (mod->ctx,"Signature dump: %02x%02x%02x%02x%02x%02x%02x%02x\n" , + sig[0 ], sig[1 ], sig[2 ], sig[3 ], + sig[4 ], sig[5 ], sig[6 ], sig[7 ]); + + arg_size =strlen (args) +1 ; + new_arg_size =sizeof (kmod_arg_key) -1 +5 +1 + sig_size *2 +1 + arg_size; + new_args =malloc (new_arg_size); +if (!new_args) +return -ENOMEM ; + +/* Hex encode the signature as "modsign=l,xxxxxx " at the front of the +* argument list. +*/ + dp =memcpy (new_args, kmod_arg_key,sizeof (kmod_arg_key) -1 ); + dp +=sizeof (kmod_arg_key) -1 ; + dp +=sprintf (dp,"%zu," , sig_size); +do { + dp +=sprintf (dp,"%02x" , *sig++); + }while (--sig_size >0 ); + *dp++ =' ' ; +memcpy (dp, args, arg_size); + + dp += arg_size; +if (dp > new_args + new_arg_size) { +fprintf (stderr,"%p > %p\n" , dp, new_args + new_arg_size); +abort (); + } + + *_new_args = new_args; + *_size = mod_size; +return 0 ; +} +extern long init_module (const void *mem,unsigned long len,const char *args);/**
@@ -782,6 +864,7 @@ KMOD_EXPORT int kmod_module_insert_module(struct kmod_module *mod,struct kmod_elf *elf =NULL ;const char *path;const char *args = options ? options :"" ; +char *new_args =NULL ;if (mod ==NULL )return -ENOENT ;
@@ -823,6 +906,12 @@ KMOD_EXPORT int kmod_module_insert_module(struct kmod_module *mod, mem =kmod_elf_get_memory (elf); } + err =kmod_find_signature (mod, mem, &size, args, &new_args); +if (err <0 ) + goto elf_failed; +if (new_args) + args = new_args; + err =init_module (mem, size, args);if (err <0 ) { err = -errno;
@@ -831,6 +920,7 @@ KMOD_EXPORT int kmod_module_insert_module(struct kmod_module *mod,if (elf !=NULL )kmod_elf_unref (elf); +free (new_args); elf_failed:kmod_file_unref (file);
Quoted 1 line · David Howells
It doesn't really need the @ signs or the MSIZE; they can be dropped.
...
Quoted 1 line
That then adds 5 bytes to the magic string. Is that really so bad?
Yes, because it's unnecessary.
Now you've decided to encode some data, you need to decide how. And you discovered that they all sucked in different ways. Binary is a PITA for the shell, so you chose to put ASCII (in the middle of an otherwise-binary blob). Then you chose a fixed length with space-based padding as the least of all evils.
But it's still completely tasteless.
Sure, my code didn't even compile. And yes, it takes about 70ms on an 8M file on my laptop, and yes, that drops to about 6ms if we check one char manually. It would drop further if we searched forwards, using memchr then memcmp, but it's already below my care factor.
Quoted 11 lines
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
One loop is a lot easier to justify that the ELF-parsing mess. And it can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
Cheers,
Rusty.
David Howells
maintainerQuoted 3 lines · Rusty Russell
Quoted 1 line
That then adds 5 bytes to the magic string. Is that really so bad?
Yes, because it's unnecessary.
I'm sorry Rusty, but this argument is disingenuous.
Yes, a length field in the file is unnecessary - BUT SO TOO is scanning! By this argument, your idea is really so bad too. It's all about the trade off one chooses to make. I do not accept your chosen trade off[*] as being the best one.
David
[*] And, yes, it *is* a trade off: you are trading CPU time and permanently
resident kernel code space in order to save a tiny amount of disk space[**].
[**] Assuming 512 byte blocks and a 5 byte size field, probably fewer than 1%
of modules will expand sufficiently to consume an extra block. Further, making it a 2-byte binary field would make it even less intrusive, both in the file and in the module verifier.
Quoted 13 lines · Rusty Russell
Quoted 11 lines · David Howells
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
Quoted 6 lines
One loop is a lot easier to justify that the ELF-parsing mess. And it can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
Could you elaborate on this part a bit? Do you mean integrate a standalone strip utility in the kernel sources and maintain that for use during module builds? Or am I misunderstanding and you meant something else?
I can see how that sounds simple and desirable from one aspect, but it seems somewhat odd to me to duplicate the existing (or create from scratch) strip utilities.
josh
Quoted 7 lines · David Howells
Hi Rusty,
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Should we just bite the bullet and create a new syscall:
SYSCALL_DEFINE5(init_module2, void __user *, umod,
unsigned long, len, const char __user *, uargs, unsigned int, siglen, const char __user *, sig)
But I'm easily swayed if you prefer the current approach.
Thanks,
Rusty.
Quoted 18 lines · Josh Boyer
Quoted 17 lines · Rusty Russell
Quoted 11 lines · David Howells
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
One loop is a lot easier to justify that the ELF-parsing mess. And it can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
Quoted 7 lines
Quoted 2 lines
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
Could you elaborate on this part a bit? Do you mean integrate a standalone strip utility in the kernel sources and maintain that for use during module builds? Or am I misunderstanding and you meant something else?
In the kernel sources, no. But could RH maintain such a thing? Surely.
Whether they want to guarantee that their strip is stable on kernel modules, or create a minimal 'kmod-strip' is up to them.
Quoted 3 lines
I can see how that sounds simple and desirable from one aspect, but it seems somewhat odd to me to duplicate the existing (or create from scratch) strip utilities.
Mangling a module after it is signed is very odd, and odd things aren't nice for security features. That's how we got here; I'm trying to move the oddness out of the verification path.
Cheers,
Rusty.
Quoted 14 lines · Rusty Russell
Quoted 7 lines · David Howells
Hi Rusty,
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Should we just bite the bullet and create a new syscall:
Quoted 8 lines
SYSCALL_DEFINE5(init_module2, void
__user*, umod,
unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
Thanks,
Rusty.
If you're really considering creating a new syscall, then perhaps this discussion should include passing the file descriptor instead of a buffer and signature. As I said https://lkml.org/lkml/2012/5/25/261, I don't know the historical reasons for passing a buffer instead of the file descriptor itself. If the file descriptor was passed, it would allow IMA-appraisal, which is in the process of being upstreamed, to verify and enforce file data and metadata integrity like on the other hooks open, execve, and mmap.
thanks,
Mimi
Quoted 9 lines · Rusty Russell
Quoted 7 lines
Quoted 2 lines
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
Could you elaborate on this part a bit? Do you mean integrate a standalone strip utility in the kernel sources and maintain that for use during module builds? Or am I misunderstanding and you meant something else?
In the kernel sources, no. But could RH maintain such a thing? Surely.
Sure. RH could continue to maintain the original modsign patch too. I thought the point was to get the mechanism into the upstream kernel so that it was generally available though. Having the patches in the mainline kernel but not the strip tool seems somewhat unhelpful. I would think such a tool would be part of the Kbuild infrastructure.
Quoted 10 lines
Whether they want to guarantee that their strip is stable on kernel modules, or create a minimal 'kmod-strip' is up to them.
Quoted 3 lines
I can see how that sounds simple and desirable from one aspect, but it seems somewhat odd to me to duplicate the existing (or create from scratch) strip utilities.
Mangling a module after it is signed is very odd, and odd things aren't nice for security features. That's how we got here; I'm trying to move the oddness out of the verification path.
It's unfortunate, yes. The biggest case I can think of is splitting the debug symbols out of the modules after they are built (David might have other cases). Perhaps we could upstream that as well and organize it such that the modules are built, split for debuginfo, and then signed?
josh
Quoted 24 lines · Mimi Zohar
Quoted 14 lines · Rusty Russell
Quoted 7 lines · David Howells
Hi Rusty,
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Should we just bite the bullet and create a new syscall:
Quoted 8 lines
SYSCALL_DEFINE5(init_module2, void
__user*, umod,
unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
Thanks,
Rusty.
Quoted 8 lines
If you're really considering creating a new syscall, then perhaps this discussion should include passing the file descriptor instead of a buffer and signature. As I said https://lkml.org/lkml/2012/5/25/261, I don't know the historical reasons for passing a buffer instead of the file descriptor itself. If the file descriptor was passed, it would allow IMA-appraisal, which is in the process of being upstreamed, to verify and enforce file data and metadata integrity like on the other hooks open, execve, and mmap.
It's flexible. Compressed modules, for example. And who knew if we would be runtime generating modules? But I don't think even the ksplice guys generate modules on the fly for insertion.
modprobe has --force-vermagic and --force-modversion, but frankly that could be replaced by a single "force" flag handed to the kernel.
If there's real benefit, it could be done. Do we still want a separate signature blob?
SYSCALL_DEFINE5(init_module_fd,
int, fd,
unsigned int, flags,
const char *__user *, uargs,
unsigned int, siglen,
const char __user *, sig);
Cheers,
Rusty.
Quoted 10 lines · Josh Boyer
Quoted 3 lines · Rusty Russell
Mangling a module after it is signed is very odd, and odd things aren't nice for security features. That's how we got here; I'm trying to move the oddness out of the verification path.
It's unfortunate, yes. The biggest case I can think of is splitting the debug symbols out of the modules after they are built (David might have other cases). Perhaps we could upstream that as well and organize it such that the modules are built, split for debuginfo, and then signed?
That was my original suggestion. Just prepare all the module variants at build time, and sign them all.
See: https://lkml.org/lkml/2011/12/10/16
Cheers,
Rusty.
Quoted 44 lines · Rusty Russell
Quoted 24 lines · Mimi Zohar
Quoted 14 lines · Rusty Russell
Quoted 7 lines · David Howells
Hi Rusty,
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Should we just bite the bullet and create a new syscall:
Quoted 8 lines
SYSCALL_DEFINE5(init_module2, void
__user*, umod,
unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
Thanks,
Rusty.Quoted 8 lines
If you're really considering creating a new syscall, then perhaps this discussion should include passing the file descriptor instead of a buffer and signature. As I said https://lkml.org/lkml/2012/5/25/261, I don't know the historical reasons for passing a buffer instead of the file descriptor itself. If the file descriptor was passed, it would allow IMA-appraisal, which is in the process of being upstreamed, to verify and enforce file data and metadata integrity like on the other hooks open, execve, and mmap.
It's flexible. Compressed modules, for example. And who knew if we would be runtime generating modules? But I don't think even the ksplice guys generate modules on the fly for insertion.
modprobe has --force-vermagic and --force-modversion, but frankly that could be replaced by a single "force" flag handed to the kernel.
If there's real benefit, it could be done. Do we still want a separate signature blob?
Quoted 6 lines
SYSCALL_DEFINE5(init_module_fd,
int, fd,
unsigned int, flags,
const char*__user*, uargs,
unsigned int, siglen,
const char__user*, sig);
As the signature would be stored as an extended attribute, we wouldn't need to pass it. Unfortunately not all filesystems have xattr support, nor do all of the package installation mechanims. The benefit of storing the signature as an extended attribute, however, is that there is a consistent mechanism for verifying file data integrity for all files, not only ELF.
Mimi
David Howells
maintainerQuoted 7 lines · Rusty Russell
Quoted 4 lines
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Not really. The signature still has to be created by the kernel build. It's just that you no longer have to care about the trade off when it comes to parsing it.
Quoted 7 lines
Should we just bite the bullet and create a new syscall:
SYSCALL_DEFINE5(init_module2, void
__user*, umod,
unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
"The current approach" being to attach signature to the blob? Or to pass the signature separately but in the uargs?
I would very much prefer to keep the signature in the blob and have the kernel extract it as there's no particular need for it to be detached - even if you are using IMA.
However, I don't think an extra syscall would hurt particularly - except that it uses up more space in the syscall table... It would, however, be smaller in the signature verification department as the signature neither needs decoding from uargs nor extracting from the blob.
David
David Howells
maintainerQuoted 6 lines · Mimi Zohar
As the signature would be stored as an extended attribute, we wouldn't need to pass it. Unfortunately not all filesystems have xattr support, nor do all of the package installation mechanims. The benefit of storing the signature as an extended attribute, however, is that there is a consistent mechanism for verifying file data integrity for all files, not only ELF.
We also want to be able to do module signature verification with CONFIG_IMA=n.
David
Quoted 10 lines · David Howells
Quoted 6 lines · Mimi Zohar
As the signature would be stored as an extended attribute, we wouldn't need to pass it. Unfortunately not all filesystems have xattr support, nor do all of the package installation mechanims. The benefit of storing the signature as an extended attribute, however, is that there is a consistent mechanism for verifying file data integrity for all files, not only ELF.
We also want to be able to do module signature verification with
CONFIG_IMA=n.
Sure. In the patchset I sent some time ago, signature verification does not require CONFIG_IMA=y.
modprobe reads signature from xattr or .sig file and pass it as kernel module parameter.
- Dmitry
Quoted 2 lines
David
Quoted 5 lines · David Howells
Quoted 3 lines · Rusty Russell
Quoted 3 lines
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
Quoted 8 lines
Quoted 4 lines
Quoted 1 line
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Not really. The signature still has to be created by the kernel build. It's just that you no longer have to care about the trade off when it comes to parsing it.
Yes, exactly.
Quoted 10 lines
Quoted 7 lines
Should we just bite the bullet and create a new syscall:
SYSCALL_DEFINE5(init_module2, void
__user*, umod,
unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
"The current approach" being to attach signature to the blob? Or to pass the signature separately but in the uargs?
The former.
Quoted 8 lines
I would very much prefer to keep the signature in the blob and have the kernel extract it as there's no particular need for it to be detached - even if you are using IMA.
However, I don't think an extra syscall would hurt particularly - except that it uses up more space in the syscall table... It would, however, be smaller in the signature verification department as the signature neither needs decoding from uargs nor extracting from the blob.
Good. Let's have init_module2(), and let userspace decide where to get the signature from.
Thanks,
Rusty.
Quoted 34 lines · Rusty Russell
Quoted 5 lines · David Howells
Quoted 3 lines · Rusty Russell
Quoted 3 lines
If you prefer to have userspace extract the module signature and pass it in uargs, here's a tree that will do that:
Quoted 8 lines
Quoted 4 lines
Quoted 1 line
OK, there's merit in this approach: it certainly moves the argument about how to encode the signature out of my backyard :)
Not really. The signature still has to be created by the kernel build. It's just that you no longer have to care about the trade off when it comes to parsing it.
Yes, exactly.
Quoted 10 lines
Quoted 7 lines
Should we just bite the bullet and create a new syscall:
SYSCALL_DEFINE5(init_module2, void
__user*, umod, unsigned long, len, const char__user*, uargs, unsigned int, siglen, const char__user*, sig)But I'm easily swayed if you prefer the current approach.
"The current approach" being to attach signature to the blob? Or to pass the signature separately but in the uargs?
The former.
Quoted 4 lines
I would very much prefer to keep the signature in the blob and have the kernel extract it as there's no particular need for it to be detached - even if you are using IMA.
Quoted 8 lines
Quoted 4 lines
However, I don't think an extra syscall would hurt particularly - except that it uses up more space in the syscall table... It would, however, be smaller in the signature verification department as the signature neither needs decoding from uargs nor extracting from the blob.
Good. Let's have
init_module2(), and let userspace decide where to get the signature from.
Nice.
Quoted 6 lines
Thanks,
Rusty.
--
To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html
Quoted 12 lines · Rusty Russell
Quoted 11 lines
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
Quoted 6 lines
One loop is a lot easier to justify that the ELF-parsing mess. And it can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
To dig an old thread up, but what really is wrong with the original ELF section stuff? Why encode "magic" values on the end of the kernel module that then require all userspace tools to be modified in order to properly handle this?
When I first did this so many many years ago an elf section made it so easy to handle. Userspace didn't need to be modified, and everyone knows how to handle elf sections, even the kernel does :)
And I think we really want the ability to have multiple signatures, the whole "chain of trust" thing that is needed will work out much better if multiple signatures are allowed. Putting it in an elf section allows this to work out easier, right?
confused,
greg k-h
Hi,
Sorry to jump into this discussion only now, but [email protected] was not CC'ed and I was not following LKML last month.
On Thu, Jun 21, 2012 at 10:53 PM, Greg KH <[email protected]> wrot= e:
Quoted 2 lines · Rusty Russell
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
Why would you want multiple signatures? =C2=A0That just complicate=
s things.
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
The code above stays pretty simple; if the signature fails, you set =
size
Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line
to i, and loop again. =C2=A0As I said, if you know exactly how you'r=
e going
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
Quoted 2 lines
to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. =C2=A0One of your arguments about reje=
cting the ELF
Quoted 1 line
Quoted 1 line
Quoted 1 line
parsing version was that it was too big for no useful extra value that=
I could
Quoted 1 line
Quoted 1 line
Quoted 1 line
justify. =C2=A0Supporting multiple signatures adds extra size and comp=
lexity for no
Quoted 3 lines
Quoted 3 lines
Quoted 1 line
obvious value.
One loop is a lot easier to justify that the ELF-parsing mess. =C2=A0And=
it
Quoted 6 lines
Quoted 5 lines
can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. =C2=A0I guess not.
Quoted 8 lines
To dig an old thread up, but what really is wrong with the original ELF section stuff? =C2=A0Why encode "magic" values on the end of the kernel module that then require all userspace tools to be modified in order to properly handle this?
When I first did this so many many years ago an elf section made it so easy to handle. =C2=A0Userspace didn't need to be modified, and everyone knows how to handle elf sections, even the kernel does :)
Indeed. What's wrong with creating an ELF section for this and let kernel deal with it? I fail to see the need for init_module2()
I need to catch up with this discussion though since I was not aware of tha= t.
Lucas De Marchi
Quoted 4 lines
And I think we really want the ability to have multiple signatures, the whole "chain of trust" thing that is needed will work out much better if multiple signatures are allowed. =C2=A0Putting it in an elf section allow=
s
Quoted 3 lines
this to work out easier, right?
confused,
me too.
Lucas De Marchi
Quoted 17 lines · Greg KH
Quoted 16 lines · Rusty Russell
Quoted 11 lines
Quoted 6 lines
Quoted 1 line
Why would you want multiple signatures? That just complicates things.
The code above stays pretty simple; if the signature fails, you set size to i, and loop again. As I said, if you know exactly how you're going to strip the modules, you can avoid storing the stripped module and simply append both signatures.
You still haven't justified it. One of your arguments about rejecting the ELF parsing version was that it was too big for no useful extra value that I could justify. Supporting multiple signatures adds extra size and complexity for no obvious value.
One loop is a lot easier to justify that the ELF-parsing mess. And it can be done in a backwards compatible way tomorrow: old kernels will only check the last signature.
Quoted 7 lines
Quoted 2 lines
I had assumed you'd rather maintain a stable strip util which you can use on kernel modules than rework your module builds. I guess not.
To dig an old thread up, but what really is wrong with the original ELF section stuff? Why encode "magic" values on the end of the kernel module that then require all userspace tools to be modified in order to properly handle this?
1) No userspace needs to be modified to use the appended signature. modprobe doesn't. depmod doesn't. Even strip doesn't (not that that's much use).
2) It's far easier to add an appended signature than to add an elf section.
3) It's far easier to generate an appended signature than to generate a signature for the module which will change when you add the signature section (roughly: gpg --sign module.ko > sig && echo '@@sig@@ >> module.ko && cat sig >> module.ko).
4) It's trivial to verify a module with an appended signature before you touch it. With a section you need to carefully parse the module, make sure you don't include the could-be-modified stuff in the signature, and avoid any possible overflows or exploits.
5) It wasn't just that they wanted an elf section. They wanted the signature to work against both a stripped and unstripped module, so only the unstrippable parts of the module were signed.
Quoted 3 lines
When I first did this so many many years ago an elf section made it so easy to handle. Userspace didn't need to be modified, and everyone knows how to handle elf sections, even the kernel does :)
And there have been bugs in the kernel elf handling code. There will undoubtedly be bugs in this, and for what? A more complex kernel to match our more complex userspace?
Quoted 4 lines
And I think we really want the ability to have multiple signatures, the whole "chain of trust" thing that is needed will work out much better if multiple signatures are allowed. Putting it in an elf section allows this to work out easier, right?
Not at all. Multiple appended signatures is trivial. Figuring out the semantics (do they chain, or is any one sufficient?), well that's the same whether you're talking about an ELF section or not.
Hope that clarifies,
Rusty.
David Howells
maintainerQuoted 3 lines · Rusty Russell
1) No userspace needs to be modified to use the appended signature. modprobe doesn't. depmod doesn't. Even strip doesn't (not that that's much use).
Anything that currently automatically strips the module: mkinitrd perhaps?
If we use a new system call, then the list includes a few more things.
Your idea of providing multiple variants of the module, each signed and each with different levels of strippedness makes things more complicated - both at build/package generation time and at usage time (where 'use' may be loading the module or packaging it into a initrd).
Quoted 2 lines
2) It's far easier to add an appended signature than to add an elf section.
That's not true. That bit of complexity in my implementation comes because I'm adding it as an ELF Note - which someone suggested I should do instead of just using an unstructured section.
If we reverted to an unstructured section, it's just one objcopy command, eg:
objcopy \ --add-section .modsign=/etc/redhat-release \ --set-section-flags .modsign=load \ /bin/ls /tmp/ls
And for debugging purposes, removing it is:
objcopy \ -R .modsign \ /bin/ls /tmp/ls
Quoted 4 lines
3) It's far easier to generate an appended signature than to generate a signature for the module which will change when you add the signature section (roughly: gpg --sign module.ko > sig && echo '@@sig@@ >> module.ko && cat sig >> module.ko).
You would be better off putting the magic number last and including a length field right before. That's much more efficient and much simpler.
Quoted 4 lines
4) It's trivial to verify a module with an appended signature before you touch it. With a section you need to carefully parse the module, make sure you don't include the could-be-modified stuff in the signature, and avoid any possible overflows or exploits.
I have to say that here Rusty is correct. If the signature is embedded in the ELF, then the ELF needs a bit of careful checking first. But, excluding the crypto bits which are the same in all cases, I managed to get the entire ELF parser/checker/canonicaliser, digest extractor and policy determiner down to a little over 2K of x86_64 code.
Since the ELF loader/linker has to parse much of this stuff anyway, it might be possible to combine the two to some extent.
Quoted 3 lines
5) It wasn't just that they wanted an elf section. They wanted the signature to work against both a stripped and unstripped module, so only the unstrippable parts of the module were signed.
Yes. Those are the bits that the module loader needs...
This is quite a good a trade off. It simplifies building and installation a lot. There is only one binary for each module. That binary can be stripped quite aggressively - any strip that would ordinarily leave the module functional won't affect the signature verification. Any content or metadata change that affects the module's operational code and data is detected.
Quoted 8 lines
Quoted 4 lines
And I think we really want the ability to have multiple signatures, the whole "chain of trust" thing that is needed will work out much better if multiple signatures are allowed. Putting it in an elf section allows this to work out easier, right?
Not at all. Multiple appended signatures is trivial. Figuring out the semantics (do they chain, or is any one sufficient?), well that's the same whether you're talking about an ELF section or not.
Agreed, it makes no difference either way.
But it doesn't necessarily work with a new syscall that has an extra pair of args for passing a signature. The kernel really wants to have all the available sigs available in one go so that it can implement its policy (which might be to panic in FIPS mode).
David
Quoted 7 lines · David Howells
Quoted 3 lines · Rusty Russell
1) No userspace needs to be modified to use the appended signature. modprobe doesn't. depmod doesn't. Even strip doesn't (not that that's much use).
Anything that currently automatically strips the module: mkinitrd perhaps?
True, if mkinitrd strips the module, it will break the signature.
Quoted 1 line
If we use a new system call, then the list includes a few more things.
Sure, but that's kind of independent of what Greg was asking.
Quoted 4 lines
Your idea of providing multiple variants of the module, each signed and each with different levels of strippedness makes things more complicated - both at build/package generation time and at usage time (where 'use' may be loading the module or packaging it into a initrd).
Userspace a bit more complex. Kernel simpler. Win.
Quoted 14 lines
Quoted 2 lines
2) It's far easier to add an appended signature than to add an elf section.
That's not true. That bit of complexity in my implementation comes because I'm adding it as an ELF Note - which someone suggested I should do instead of just using an unstructured section.
If we reverted to an unstructured section, it's just one objcopy command, eg:
objcopy \ --add-section .modsign=/etc/redhat-release \ --set-section-flags .modsign=load \ /bin/ls /tmp/ls
Quoted 5 lines
And for debugging purposes, removing it is:
objcopy \ -R .modsign \ /bin/ls /tmp/ls
OK, s/far//. We already rely on objcopy for kernel builds, so no additional requirements.
Quoted 7 lines
Quoted 4 lines
3) It's far easier to generate an appended signature than to generate a signature for the module which will change when you add the signature section (roughly: gpg --sign module.ko > sig && echo '@@sig@@ >> module.ko && cat sig >> module.ko).
You would be better off putting the magic number last and including a length field right before. That's much more efficient and much simpler.
No, that was more complex and tasteless.
Quoted 10 lines
Quoted 4 lines
4) It's trivial to verify a module with an appended signature before you touch it. With a section you need to carefully parse the module, make sure you don't include the could-be-modified stuff in the signature, and avoid any possible overflows or exploits.
I have to say that here Rusty is correct. If the signature is embedded in the ELF, then the ELF needs a bit of careful checking first. But, excluding the crypto bits which are the same in all cases, I managed to get the entire ELF parser/checker/canonicaliser, digest extractor and policy determiner down to a little over 2K of
x86_64code.
I've been tempted to search for a hole in your parsing code. But while finding one would be satisfying, not finding one isn't conclusive. So it's a waste of time.
Quoted 4 lines
This is quite a good a trade off. It simplifies building and installation a lot. There is only one binary for each module. That binary can be stripped quite aggressively - any strip that would ordinarily leave the module functional won't affect the signature verification.
Wouldn't it be nice if strip removed nop padding at the end of text sections?
Cheers,
Rusty.