1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Copyright (C) 2005-2010 IBM Corporation
4 *
5 * Authors:
6 * Mimi Zohar <zohar@us.ibm.com>
7 * Kylene Hall <kjhall@us.ibm.com>
8 *
9 * File: evm_crypto.c
10 *	 Using root's kernel master key (kmk), calculate the HMAC
11 */
12
13#define pr_fmt(fmt) "EVM: "fmt
14
15#include <linux/export.h>
16#include <linux/crypto.h>
17#include <linux/xattr.h>
18#include <linux/evm.h>
19#include <keys/encrypted-type.h>
20#include <crypto/hash.h>
21#include <crypto/hash_info.h>
22#include "evm.h"
23
24#define EVMKEY "evm-key"
25#define MAX_KEY_SIZE 128
26static unsigned char evmkey[MAX_KEY_SIZE];
27static const int evmkey_len = MAX_KEY_SIZE;
28
29static struct crypto_shash *hmac_tfm;
30static struct crypto_shash *evm_tfm[HASH_ALGO__LAST];
31
32static DEFINE_MUTEX(mutex);
33
34#define EVM_SET_KEY_BUSY 0
35
36static unsigned long evm_set_key_flags;
37
38static const char evm_hmac[] = "hmac(sha1)";
39
40/**
41 * evm_set_key() - set EVM HMAC key from the kernel
42 * @key: pointer to a buffer with the key data
43 * @keylen: length of the key data
44 *
45 * This function allows setting the EVM HMAC key from the kernel
46 * without using the "encrypted" key subsystem keys. It can be used
47 * by the crypto HW kernel module which has its own way of managing
48 * keys.
49 *
50 * key length should be between 32 and 128 bytes long
51 */
52int evm_set_key(void *key, size_t keylen)
53{
54	int rc;
55
56	rc = -EBUSY;
57	if (test_and_set_bit(EVM_SET_KEY_BUSY, &evm_set_key_flags))
58		goto busy;
59	rc = -EINVAL;
60	if (keylen > MAX_KEY_SIZE)
61		goto inval;
62	memcpy(evmkey, key, keylen);
63	evm_initialized |= EVM_INIT_HMAC;
64	pr_info("key initialized\n");
65	return 0;
66inval:
67	clear_bit(EVM_SET_KEY_BUSY, &evm_set_key_flags);
68busy:
69	pr_err("key initialization failed\n");
70	return rc;
71}
72EXPORT_SYMBOL_GPL(evm_set_key);
73
74static struct shash_desc *init_desc(char type, uint8_t hash_algo)
75{
76	long rc;
77	const char *algo;
78	struct crypto_shash **tfm, *tmp_tfm;
79	struct shash_desc *desc;
80
81	if (type == EVM_XATTR_HMAC) {
82		if (!(evm_initialized & EVM_INIT_HMAC)) {
83			pr_err_once("HMAC key is not set\n");
84			return ERR_PTR(-ENOKEY);
85		}
86		tfm = &hmac_tfm;
87		algo = evm_hmac;
88	} else {
89		if (hash_algo >= HASH_ALGO__LAST)
90			return ERR_PTR(-EINVAL);
91
92		tfm = &evm_tfm[hash_algo];
93		algo = hash_algo_name[hash_algo];
94	}
95
96	if (*tfm)
97		goto alloc;
98	mutex_lock(&mutex);
99	if (*tfm)
100		goto unlock;
101
102	tmp_tfm = crypto_alloc_shash(algo, 0, CRYPTO_NOLOAD);
103	if (IS_ERR(tmp_tfm)) {
104		pr_err("Can not allocate %s (reason: %ld)\n", algo,
105		       PTR_ERR(tmp_tfm));
106		mutex_unlock(&mutex);
107		return ERR_CAST(tmp_tfm);
108	}
109	if (type == EVM_XATTR_HMAC) {
110		rc = crypto_shash_setkey(tmp_tfm, evmkey, evmkey_len);
111		if (rc) {
112			crypto_free_shash(tmp_tfm);
113			mutex_unlock(&mutex);
114			return ERR_PTR(rc);
115		}
116	}
117	*tfm = tmp_tfm;
118unlock:
119	mutex_unlock(&mutex);
120alloc:
121	desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(*tfm),
122			GFP_KERNEL);
123	if (!desc)
124		return ERR_PTR(-ENOMEM);
125
126	desc->tfm = *tfm;
127
128	rc = crypto_shash_init(desc);
129	if (rc) {
130		kfree(desc);
131		return ERR_PTR(rc);
132	}
133	return desc;
134}
135
136/* Protect against 'cutting & pasting' security.evm xattr, include inode
137 * specific info.
138 *
139 * (Additional directory/file metadata needs to be added for more complete
140 * protection.)
141 */
142static void hmac_add_misc(struct shash_desc *desc, struct inode *inode,
143			  char type, char *digest)
144{
145	struct h_misc {
146		unsigned long ino;
147		__u32 generation;
148		uid_t uid;
149		gid_t gid;
150		umode_t mode;
151	} hmac_misc;
152
153	memset(&hmac_misc, 0, sizeof(hmac_misc));
154	/* Don't include the inode or generation number in portable
155	 * signatures
156	 */
157	if (type != EVM_XATTR_PORTABLE_DIGSIG) {
158		hmac_misc.ino = inode->i_ino;
159		hmac_misc.generation = inode->i_generation;
160	}
161	/* The hmac uid and gid must be encoded in the initial user
162	 * namespace (not the filesystems user namespace) as encoding
163	 * them in the filesystems user namespace allows an attack
164	 * where first they are written in an unprivileged fuse mount
165	 * of a filesystem and then the system is tricked to mount the
166	 * filesystem for real on next boot and trust it because
167	 * everything is signed.
168	 */
169	hmac_misc.uid = from_kuid(&init_user_ns, inode->i_uid);
170	hmac_misc.gid = from_kgid(&init_user_ns, inode->i_gid);
171	hmac_misc.mode = inode->i_mode;
172	crypto_shash_update(desc, (const u8 *)&hmac_misc, sizeof(hmac_misc));
173	if ((evm_hmac_attrs & EVM_ATTR_FSUUID) &&
174	    type != EVM_XATTR_PORTABLE_DIGSIG)
175		crypto_shash_update(desc, (u8 *)&inode->i_sb->s_uuid, UUID_SIZE);
176	crypto_shash_final(desc, digest);
177
178	pr_debug("hmac_misc: (%zu) [%*phN]\n", sizeof(struct h_misc),
179		 (int)sizeof(struct h_misc), &hmac_misc);
180}
181
182/*
183 * Dump large security xattr values as a continuous ascii hexademical string.
184 * (pr_debug is limited to 64 bytes.)
185 */
186static void dump_security_xattr_l(const char *prefix, const void *src,
187				  size_t count)
188{
189#if defined(DEBUG) || defined(CONFIG_DYNAMIC_DEBUG)
190	char *asciihex, *p;
191
192	p = asciihex = kmalloc(count * 2 + 1, GFP_KERNEL);
193	if (!asciihex)
194		return;
195
196	p = bin2hex(p, src, count);
197	*p = 0;
198	pr_debug("%s: (%zu) %.*s\n", prefix, count, (int)count * 2, asciihex);
199	kfree(asciihex);
200#endif
201}
202
203static void dump_security_xattr(const char *name, const char *value,
204				size_t value_len)
205{
206	if (value_len < 64)
207		pr_debug("%s: (%zu) [%*phN]\n", name, value_len,
208			 (int)value_len, value);
209	else
210		dump_security_xattr_l(name, value, value_len);
211}
212
213/*
214 * Calculate the HMAC value across the set of protected security xattrs.
215 *
216 * Instead of retrieving the requested xattr, for performance, calculate
217 * the hmac using the requested xattr value. Don't alloc/free memory for
218 * each xattr, but attempt to re-use the previously allocated memory.
219 */
220static int evm_calc_hmac_or_hash(struct dentry *dentry,
221				 const char *req_xattr_name,
222				 const char *req_xattr_value,
223				 size_t req_xattr_value_len,
224				 uint8_t type, struct evm_digest *data)
225{
226	struct inode *inode = d_backing_inode(dentry);
227	struct xattr_list *xattr;
228	struct shash_desc *desc;
229	size_t xattr_size = 0;
230	char *xattr_value = NULL;
231	int error;
232	int size, user_space_size;
233	bool ima_present = false;
234
235	if (!(inode->i_opflags & IOP_XATTR) ||
236	    inode->i_sb->s_user_ns != &init_user_ns)
237		return -EOPNOTSUPP;
238
239	desc = init_desc(type, data->hdr.algo);
240	if (IS_ERR(desc))
241		return PTR_ERR(desc);
242
243	data->hdr.length = crypto_shash_digestsize(desc->tfm);
244
245	error = -ENODATA;
246	list_for_each_entry_lockless(xattr, &evm_config_xattrnames, list) {
247		bool is_ima = false;
248
249		if (strcmp(xattr->name, XATTR_NAME_IMA) == 0)
250			is_ima = true;
251
252		/*
253		 * Skip non-enabled xattrs for locally calculated
254		 * signatures/HMACs.
255		 */
256		if (type != EVM_XATTR_PORTABLE_DIGSIG && !xattr->enabled)
257			continue;
258
259		if ((req_xattr_name && req_xattr_value)
260		    && !strcmp(xattr->name, req_xattr_name)) {
261			error = 0;
262			crypto_shash_update(desc, (const u8 *)req_xattr_value,
263					     req_xattr_value_len);
264			if (is_ima)
265				ima_present = true;
266
267			dump_security_xattr(req_xattr_name,
268					    req_xattr_value,
269					    req_xattr_value_len);
270			continue;
271		}
272		size = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, xattr->name,
273					  &xattr_value, xattr_size, GFP_NOFS);
274		if (size == -ENOMEM) {
275			error = -ENOMEM;
276			goto out;
277		}
278		if (size < 0)
279			continue;
280
281		user_space_size = vfs_getxattr(&nop_mnt_idmap, dentry,
282					       xattr->name, NULL, 0);
283		if (user_space_size != size)
284			pr_debug("file %s: xattr %s size mismatch (kernel: %d, user: %d)\n",
285				 dentry->d_name.name, xattr->name, size,
286				 user_space_size);
287		error = 0;
288		xattr_size = size;
289		crypto_shash_update(desc, (const u8 *)xattr_value, xattr_size);
290		if (is_ima)
291			ima_present = true;
292
293		dump_security_xattr(xattr->name, xattr_value, xattr_size);
294	}
295	hmac_add_misc(desc, inode, type, data->digest);
296
297	/* Portable EVM signatures must include an IMA hash */
298	if (type == EVM_XATTR_PORTABLE_DIGSIG && !ima_present)
299		error = -EPERM;
300out:
301	kfree(xattr_value);
302	kfree(desc);
303	return error;
304}
305
306int evm_calc_hmac(struct dentry *dentry, const char *req_xattr_name,
307		  const char *req_xattr_value, size_t req_xattr_value_len,
308		  struct evm_digest *data)
309{
310	return evm_calc_hmac_or_hash(dentry, req_xattr_name, req_xattr_value,
311				    req_xattr_value_len, EVM_XATTR_HMAC, data);
312}
313
314int evm_calc_hash(struct dentry *dentry, const char *req_xattr_name,
315		  const char *req_xattr_value, size_t req_xattr_value_len,
316		  char type, struct evm_digest *data)
317{
318	return evm_calc_hmac_or_hash(dentry, req_xattr_name, req_xattr_value,
319				     req_xattr_value_len, type, data);
320}
321
322static int evm_is_immutable(struct dentry *dentry, struct inode *inode)
323{
324	const struct evm_ima_xattr_data *xattr_data = NULL;
325	struct evm_iint_cache *iint;
326	int rc = 0;
327
328	iint = evm_iint_inode(inode);
329	if (iint && (iint->flags & EVM_IMMUTABLE_DIGSIG))
330		return 1;
331
332	/* Do this the hard way */
333	rc = vfs_getxattr_alloc(&nop_mnt_idmap, dentry, XATTR_NAME_EVM,
334				(char **)&xattr_data, 0, GFP_NOFS);
335	if (rc <= 0) {
336		if (rc == -ENODATA)
337			rc = 0;
338		goto out;
339	}
340	if (xattr_data->type == EVM_XATTR_PORTABLE_DIGSIG)
341		rc = 1;
342	else
343		rc = 0;
344
345out:
346	kfree(xattr_data);
347	return rc;
348}
349
350
351/*
352 * Calculate the hmac and update security.evm xattr
353 *
354 * Expects to be called with i_mutex locked.
355 */
356int evm_update_evmxattr(struct dentry *dentry, const char *xattr_name,
357			const char *xattr_value, size_t xattr_value_len)
358{
359	struct inode *inode = d_backing_inode(dentry);
360	struct evm_digest data;
361	int rc = 0;
362
363	/*
364	 * Don't permit any transformation of the EVM xattr if the signature
365	 * is of an immutable type
366	 */
367	rc = evm_is_immutable(dentry, inode);
368	if (rc < 0)
369		return rc;
370	if (rc)
371		return -EPERM;
372
373	data.hdr.algo = HASH_ALGO_SHA1;
374	rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
375			   xattr_value_len, &data);
376	if (rc == 0) {
377		data.hdr.xattr.sha1.type = EVM_XATTR_HMAC;
378		rc = __vfs_setxattr_noperm(&nop_mnt_idmap, dentry,
379					   XATTR_NAME_EVM,
380					   &data.hdr.xattr.data[1],
381					   SHA1_DIGEST_SIZE + 1, 0);
382	} else if (rc == -ENODATA && (inode->i_opflags & IOP_XATTR)) {
383		rc = __vfs_removexattr(&nop_mnt_idmap, dentry, XATTR_NAME_EVM);
384	}
385	return rc;
386}
387
388int evm_init_hmac(struct inode *inode, const struct xattr *xattrs,
389		  char *hmac_val)
390{
391	struct shash_desc *desc;
392	const struct xattr *xattr;
393
394	desc = init_desc(EVM_XATTR_HMAC, HASH_ALGO_SHA1);
395	if (IS_ERR(desc)) {
396		pr_info("init_desc failed\n");
397		return PTR_ERR(desc);
398	}
399
400	for (xattr = xattrs; xattr->name; xattr++) {
401		if (!evm_protected_xattr(xattr->name))
402			continue;
403
404		crypto_shash_update(desc, xattr->value, xattr->value_len);
405	}
406
407	hmac_add_misc(desc, inode, EVM_XATTR_HMAC, hmac_val);
408	kfree(desc);
409	return 0;
410}
411
412/*
413 * Get the key from the TPM for the SHA1-HMAC
414 */
415int evm_init_key(void)
416{
417	struct key *evm_key;
418	struct encrypted_key_payload *ekp;
419	int rc;
420
421	evm_key = request_key(&key_type_encrypted, EVMKEY, NULL);
422	if (IS_ERR(evm_key))
423		return -ENOENT;
424
425	down_read(&evm_key->sem);
426	ekp = evm_key->payload.data[0];
427
428	rc = evm_set_key(ekp->decrypted_data, ekp->decrypted_datalen);
429
430	/* burn the original key contents */
431	memset(ekp->decrypted_data, 0, ekp->decrypted_datalen);
432	up_read(&evm_key->sem);
433	key_put(evm_key);
434	return rc;
435}
436