1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2019 Microsoft Corporation
4  *
5  * Author: Lakshmi Ramasubramanian (nramas@linux.microsoft.com)
6  *
7  * File: ima_asymmetric_keys.c
8  *       Defines an IMA hook to measure asymmetric keys on key
9  *       create or update.
10  */
11 
12 #include <keys/asymmetric-type.h>
13 #include <linux/user_namespace.h>
14 #include "ima.h"
15 
16 /**
17  * ima_post_key_create_or_update - measure asymmetric keys
18  * @keyring: keyring to which the key is linked to
19  * @key: created or updated key
20  * @payload: The data used to instantiate or update the key.
21  * @payload_len: The length of @payload.
22  * @flags: key flags
23  * @create: flag indicating whether the key was created or updated
24  *
25  * Keys can only be measured, not appraised.
26  * The payload data used to instantiate or update the key is measured.
27  */
28 void ima_post_key_create_or_update(struct key *keyring, struct key *key,
29 				   const void *payload, size_t payload_len,
30 				   unsigned long flags, bool create)
31 {
32 	bool queued = false;
33 
34 	/* Only asymmetric keys are handled by this hook. */
35 	if (key->type != &key_type_asymmetric)
36 		return;
37 
38 	if (!payload || (payload_len == 0))
39 		return;
40 
41 	if (ima_should_queue_key())
42 		queued = ima_queue_key(keyring, payload, payload_len);
43 
44 	if (queued)
45 		return;
46 
47 	/*
48 	 * keyring->description points to the name of the keyring
49 	 * (such as ".builtin_trusted_keys", ".ima", etc.) to
50 	 * which the given key is linked to.
51 	 *
52 	 * The name of the keyring is passed in the "eventname"
53 	 * parameter to process_buffer_measurement() and is set
54 	 * in the "eventname" field in ima_event_data for
55 	 * the key measurement IMA event.
56 	 *
57 	 * The name of the keyring is also passed in the "keyring"
58 	 * parameter to process_buffer_measurement() to check
59 	 * if the IMA policy is configured to measure a key linked
60 	 * to the given keyring.
61 	 */
62 	process_buffer_measurement(&init_user_ns, NULL, payload, payload_len,
63 				   keyring->description, KEY_CHECK, 0,
64 				   keyring->description, false);
65 }
66