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 <linux/ima.h>
15#include "ima.h"
16
17/**
18 * ima_post_key_create_or_update - measure asymmetric keys
19 * @keyring: keyring to which the key is linked to
20 * @key: created or updated key
21 * @payload: The data used to instantiate or update the key.
22 * @payload_len: The length of @payload.
23 * @flags: key flags
24 * @create: flag indicating whether the key was created or updated
25 *
26 * Keys can only be measured, not appraised.
27 * The payload data used to instantiate or update the key is measured.
28 */
29void ima_post_key_create_or_update(struct key *keyring, struct key *key,
30				   const void *payload, size_t payload_len,
31				   unsigned long flags, bool create)
32{
33	bool queued = false;
34
35	/* Only asymmetric keys are handled by this hook. */
36	if (key->type != &key_type_asymmetric)
37		return;
38
39	if (!payload || (payload_len == 0))
40		return;
41
42	if (ima_should_queue_key())
43		queued = ima_queue_key(keyring, payload, payload_len);
44
45	if (queued)
46		return;
47
48	/*
49	 * keyring->description points to the name of the keyring
50	 * (such as ".builtin_trusted_keys", ".ima", etc.) to
51	 * which the given key is linked to.
52	 *
53	 * The name of the keyring is passed in the "eventname"
54	 * parameter to process_buffer_measurement() and is set
55	 * in the "eventname" field in ima_event_data for
56	 * the key measurement IMA event.
57	 *
58	 * The name of the keyring is also passed in the "keyring"
59	 * parameter to process_buffer_measurement() to check
60	 * if the IMA policy is configured to measure a key linked
61	 * to the given keyring.
62	 */
63	process_buffer_measurement(&nop_mnt_idmap, NULL, payload, payload_len,
64				   keyring->description, KEY_CHECK, 0,
65				   keyring->description, false, NULL, 0);
66}
67