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