xref: /linux/security/integrity/ima/ima_api.c (revision e2683c8868d03382da7e1ce8453b543a043066d1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2008 IBM Corporation
4  *
5  * Author: Mimi Zohar <zohar@us.ibm.com>
6  *
7  * File: ima_api.c
8  *	Implements must_appraise_or_measure, collect_measurement,
9  *	appraise_measurement, store_measurement and store_template.
10  */
11 #include <linux/slab.h>
12 #include <linux/file.h>
13 #include <linux/fs.h>
14 #include <linux/hex.h>
15 #include <linux/xattr.h>
16 #include <linux/evm.h>
17 #include <linux/fsverity.h>
18 
19 #include "ima.h"
20 
21 /*
22  * ima_free_template_entry - free an existing template entry
23  */
24 void ima_free_template_entry(struct ima_template_entry *entry)
25 {
26 	int i;
27 
28 	for (i = 0; i < entry->template_desc->num_fields; i++)
29 		kfree(entry->template_data[i].data);
30 
31 	kfree(entry->digests);
32 	kfree(entry);
33 }
34 
35 /*
36  * ima_alloc_init_template - create and initialize a new template entry
37  */
38 int ima_alloc_init_template(struct ima_event_data *event_data,
39 			    struct ima_template_entry **entry,
40 			    struct ima_template_desc *desc)
41 {
42 	struct ima_template_desc *template_desc;
43 	struct tpm_digest *digests;
44 	int i, result = 0;
45 
46 	if (desc)
47 		template_desc = desc;
48 	else
49 		template_desc = ima_template_desc_current();
50 
51 	*entry = kzalloc_flex(**entry, template_data, template_desc->num_fields,
52 			      GFP_NOFS);
53 	if (!*entry)
54 		return -ENOMEM;
55 
56 	digests = kzalloc_objs(*digests,
57 			       NR_BANKS(ima_tpm_chip) + ima_extra_slots,
58 			       GFP_NOFS);
59 	if (!digests) {
60 		kfree(*entry);
61 		*entry = NULL;
62 		return -ENOMEM;
63 	}
64 
65 	(*entry)->digests = digests;
66 	(*entry)->template_desc = template_desc;
67 	for (i = 0; i < template_desc->num_fields; i++) {
68 		const struct ima_template_field *field =
69 			template_desc->fields[i];
70 		u32 len;
71 
72 		result = field->field_init(event_data,
73 					   &((*entry)->template_data[i]));
74 		if (result != 0)
75 			goto out;
76 
77 		len = (*entry)->template_data[i].len;
78 		(*entry)->template_data_len += sizeof(len);
79 		(*entry)->template_data_len += len;
80 	}
81 	return 0;
82 out:
83 	ima_free_template_entry(*entry);
84 	*entry = NULL;
85 	return result;
86 }
87 
88 /*
89  * ima_store_template - store ima template measurements
90  *
91  * Calculate the hash of a template entry, add the template entry
92  * to an ordered list of measurement entries maintained inside the kernel,
93  * and also update the aggregate integrity value (maintained inside the
94  * configured TPM PCR) over the hashes of the current list of measurement
95  * entries.
96  *
97  * Applications retrieve the current kernel-held measurement list through
98  * the securityfs entries in /sys/kernel/security/ima. The signed aggregate
99  * TPM PCR (called quote) can be retrieved using a TPM user space library
100  * and is used to validate the measurement list.
101  *
102  * Returns 0 on success, error code otherwise
103  */
104 int ima_store_template(struct ima_template_entry *entry,
105 		       int violation, struct inode *inode,
106 		       const unsigned char *filename, int pcr)
107 {
108 	static const char op[] = "add_template_measure";
109 	static const char audit_cause[] = "hashing_error";
110 	char *template_name = entry->template_desc->name;
111 	int result;
112 
113 	if (!violation) {
114 		result = ima_calc_field_array_hash(&entry->template_data[0],
115 						   entry);
116 		if (result < 0) {
117 			integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode,
118 					    template_name, op,
119 					    audit_cause, result, 0);
120 			return result;
121 		}
122 	}
123 	entry->pcr = pcr;
124 	result = ima_add_template_entry(entry, violation, op, inode, filename);
125 	return result;
126 }
127 
128 /*
129  * ima_add_violation - add violation to measurement list.
130  *
131  * Violations are flagged in the measurement list with zero hash values.
132  * By extending the PCR with 0xFF's instead of with zeroes, the PCR
133  * value is invalidated.
134  */
135 void ima_add_violation(struct file *file, const unsigned char *filename,
136 		       struct ima_iint_cache *iint, const char *op,
137 		       const char *cause)
138 {
139 	struct ima_template_entry *entry;
140 	struct inode *inode = file_inode(file);
141 	struct ima_event_data event_data = { .iint = iint,
142 					     .file = file,
143 					     .filename = filename,
144 					     .violation = cause };
145 	int violation = 1;
146 	int result;
147 
148 	/* can overflow, only indicator */
149 	atomic_long_inc(&ima_htable.violations);
150 
151 	result = ima_alloc_init_template(&event_data, &entry, NULL);
152 	if (result < 0) {
153 		result = -ENOMEM;
154 		goto err_out;
155 	}
156 	result = ima_store_template(entry, violation, inode,
157 				    filename, CONFIG_IMA_MEASURE_PCR_IDX);
158 	if (result < 0)
159 		ima_free_template_entry(entry);
160 err_out:
161 	integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename,
162 			    op, cause, result, 0);
163 }
164 
165 /**
166  * ima_get_action - appraise & measure decision based on policy.
167  * @idmap: idmap of the mount the inode was found from
168  * @inode: pointer to the inode associated with the object being validated
169  * @cred: pointer to credentials structure to validate
170  * @prop: properties of the task being validated
171  * @mask: contains the permission mask (MAY_READ, MAY_WRITE, MAY_EXEC,
172  *        MAY_APPEND)
173  * @func: caller identifier
174  * @pcr: pointer filled in if matched measure policy sets pcr=
175  * @template_desc: pointer filled in if matched measure policy sets template=
176  * @func_data: func specific data, may be NULL
177  * @allowed_algos: allowlist of hash algorithms for the IMA xattr
178  *
179  * The policy is defined in terms of keypairs:
180  *		subj=, obj=, type=, func=, mask=, fsmagic=
181  *	subj,obj, and type: are LSM specific.
182  *	func: FILE_CHECK | BPRM_CHECK | CREDS_CHECK | MMAP_CHECK | MODULE_CHECK
183  *	| KEXEC_CMDLINE | KEY_CHECK | CRITICAL_DATA | SETXATTR_CHECK
184  *	| MMAP_CHECK_REQPROT
185  *	mask: contains the permission mask
186  *	fsmagic: hex value
187  *
188  * Returns IMA_MEASURE, IMA_APPRAISE mask.
189  *
190  */
191 int ima_get_action(struct mnt_idmap *idmap, struct inode *inode,
192 		   const struct cred *cred, struct lsm_prop *prop, int mask,
193 		   enum ima_hooks func, int *pcr,
194 		   struct ima_template_desc **template_desc,
195 		   const char *func_data, unsigned int *allowed_algos)
196 {
197 	int flags = IMA_MEASURE | IMA_AUDIT | IMA_APPRAISE | IMA_HASH;
198 
199 	flags &= ima_policy_flag;
200 
201 	return ima_match_policy(idmap, inode, cred, prop, func, mask,
202 				flags, pcr, template_desc, func_data,
203 				allowed_algos);
204 }
205 
206 static bool ima_get_verity_digest(struct ima_iint_cache *iint,
207 				  struct inode *inode,
208 				  struct ima_max_digest_data *hash)
209 {
210 	enum hash_algo alg;
211 	int digest_len;
212 
213 	/*
214 	 * On failure, 'measure' policy rules will result in a file data
215 	 * hash containing 0's.
216 	 */
217 	digest_len = fsverity_get_digest(inode, hash->digest, NULL, &alg);
218 	if (digest_len == 0)
219 		return false;
220 
221 	/*
222 	 * Unlike in the case of actually calculating the file hash, in
223 	 * the fsverity case regardless of the hash algorithm, return
224 	 * the verity digest to be included in the measurement list. A
225 	 * mismatch between the verity algorithm and the xattr signature
226 	 * algorithm, if one exists, will be detected later.
227 	 */
228 	hash->hdr.algo = alg;
229 	hash->hdr.length = digest_len;
230 	return true;
231 }
232 
233 /*
234  * ima_collect_measurement - collect file measurement
235  *
236  * Calculate the file hash, if it doesn't already exist,
237  * storing the measurement and i_version in the iint.
238  *
239  * Must be called with iint->mutex held.
240  *
241  * Return 0 on success, error code otherwise
242  */
243 int ima_collect_measurement(struct ima_iint_cache *iint, struct file *file,
244 			    void *buf, loff_t size, enum hash_algo algo,
245 			    struct modsig *modsig)
246 {
247 	const char *audit_cause = "failed";
248 	struct inode *inode = file_inode(file);
249 	struct inode *real_inode = d_real_inode(file_dentry(file));
250 	struct ima_max_digest_data hash;
251 	struct ima_digest_data *hash_hdr = container_of(&hash.hdr,
252 						struct ima_digest_data, hdr);
253 	struct name_snapshot filename;
254 	struct kstat stat;
255 	int result = 0;
256 	int length;
257 	void *tmpbuf;
258 	u64 i_version = 0;
259 
260 	/*
261 	 * Always collect the modsig, because IMA might have already collected
262 	 * the file digest without collecting the modsig in a previous
263 	 * measurement rule.
264 	 */
265 	if (modsig)
266 		ima_collect_modsig(modsig, buf, size);
267 
268 	if (iint->flags & IMA_COLLECTED)
269 		goto out;
270 
271 	/*
272 	 * Detect file change based on STATX_CHANGE_COOKIE, when supported,
273 	 * and fallback to detecting file change based on i_version.
274 	 *
275 	 * On filesystems which did not support i_version, support was
276 	 * originally limited to an initial measurement/appraisal/audit,
277 	 * but was later modified to assume the file changed.
278 	 */
279 	result = vfs_getattr_nosec(&file->f_path, &stat, STATX_CHANGE_COOKIE,
280 				   AT_STATX_SYNC_AS_STAT);
281 	if (!result && (stat.result_mask & STATX_CHANGE_COOKIE))
282 		i_version = stat.change_cookie;
283 	else if (IS_I_VERSION(real_inode))
284 		i_version = inode_peek_iversion(real_inode);
285 
286 	hash.hdr.algo = algo;
287 	hash.hdr.length = hash_digest_size[algo];
288 
289 	/* Initialize hash digest to 0's in case of failure */
290 	memset(&hash.digest, 0, sizeof(hash.digest));
291 
292 	if (iint->flags & IMA_VERITY_REQUIRED) {
293 		if (!ima_get_verity_digest(iint, inode, &hash)) {
294 			audit_cause = "no-verity-digest";
295 			result = -ENODATA;
296 		}
297 	} else if (buf) {
298 		result = ima_calc_buffer_hash(buf, size, hash_hdr);
299 	} else {
300 		result = ima_calc_file_hash(file, hash_hdr);
301 	}
302 
303 	if (result && result != -EBADF && result != -EINVAL)
304 		goto out;
305 
306 	length = sizeof(hash.hdr) + hash.hdr.length;
307 	tmpbuf = krealloc(iint->ima_hash, length, GFP_NOFS);
308 	if (!tmpbuf) {
309 		result = -ENOMEM;
310 		goto out;
311 	}
312 
313 	iint->ima_hash = tmpbuf;
314 	memcpy(iint->ima_hash, &hash, length);
315 	if (real_inode == inode)
316 		iint->real_inode.version = i_version;
317 	else
318 		integrity_inode_attrs_store(&iint->real_inode, i_version,
319 					    real_inode);
320 
321 	/* Possibly temporary failure due to type of read (eg. O_DIRECT) */
322 	if (!result)
323 		iint->flags |= IMA_COLLECTED;
324 out:
325 	if (result) {
326 		if (file->f_flags & O_DIRECT)
327 			audit_cause = "failed(directio)";
328 
329 		take_dentry_name_snapshot(&filename, file->f_path.dentry);
330 
331 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
332 				    filename.name.name, "collect_data",
333 				    audit_cause, result, 0);
334 
335 		release_dentry_name_snapshot(&filename);
336 	}
337 	return result;
338 }
339 
340 /*
341  * ima_store_measurement - store file measurement
342  *
343  * Create an "ima" template and then store the template by calling
344  * ima_store_template.
345  *
346  * We only get here if the inode has not already been measured,
347  * but the measurement could already exist:
348  *	- multiple copies of the same file on either the same or
349  *	  different filesystems.
350  *	- the inode was previously flushed as well as the iint info,
351  *	  containing the hashing info.
352  *
353  * Must be called with iint->mutex held.
354  */
355 void ima_store_measurement(struct ima_iint_cache *iint, struct file *file,
356 			   const unsigned char *filename,
357 			   struct evm_ima_xattr_data *xattr_value,
358 			   int xattr_len, const struct modsig *modsig, int pcr,
359 			   struct ima_template_desc *template_desc)
360 {
361 	static const char op[] = "add_template_measure";
362 	static const char audit_cause[] = "ENOMEM";
363 	int result = -ENOMEM;
364 	struct inode *inode = file_inode(file);
365 	struct ima_template_entry *entry;
366 	struct ima_event_data event_data = { .iint = iint,
367 					     .file = file,
368 					     .filename = filename,
369 					     .xattr_value = xattr_value,
370 					     .xattr_len = xattr_len,
371 					     .modsig = modsig };
372 	int violation = 0;
373 
374 	/*
375 	 * We still need to store the measurement in the case of MODSIG because
376 	 * we only have its contents to put in the list at the time of
377 	 * appraisal, but a file measurement from earlier might already exist in
378 	 * the measurement list.
379 	 */
380 	if (iint->measured_pcrs & (0x1 << pcr) && !modsig)
381 		return;
382 
383 	result = ima_alloc_init_template(&event_data, &entry, template_desc);
384 	if (result < 0) {
385 		integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename,
386 				    op, audit_cause, result, 0);
387 		return;
388 	}
389 
390 	result = ima_store_template(entry, violation, inode, filename, pcr);
391 	if ((!result || result == -EEXIST) && !(file->f_flags & O_DIRECT)) {
392 		iint->flags |= IMA_MEASURED;
393 		iint->measured_pcrs |= (0x1 << pcr);
394 	}
395 	if (result < 0)
396 		ima_free_template_entry(entry);
397 }
398 
399 void ima_audit_measurement(struct ima_iint_cache *iint,
400 			   const unsigned char *filename)
401 {
402 	struct audit_buffer *ab;
403 	char *hash;
404 	const char *algo_name = hash_algo_name[iint->ima_hash->algo];
405 	int i;
406 
407 	if (iint->flags & IMA_AUDITED)
408 		return;
409 
410 	hash = kzalloc((iint->ima_hash->length * 2) + 1, GFP_KERNEL);
411 	if (!hash)
412 		return;
413 
414 	for (i = 0; i < iint->ima_hash->length; i++)
415 		hex_byte_pack(hash + (i * 2), iint->ima_hash->digest[i]);
416 	hash[i * 2] = '\0';
417 
418 	ab = audit_log_start(audit_context(), GFP_KERNEL,
419 			     AUDIT_INTEGRITY_RULE);
420 	if (!ab)
421 		goto out;
422 
423 	audit_log_format(ab, "file=");
424 	audit_log_untrustedstring(ab, filename);
425 	audit_log_format(ab, " hash=\"%s:%s\"", algo_name, hash);
426 
427 	audit_log_task_info(ab);
428 	audit_log_end(ab);
429 
430 	iint->flags |= IMA_AUDITED;
431 out:
432 	kfree(hash);
433 	return;
434 }
435 
436 /*
437  * ima_d_path - return a pointer to the full pathname
438  *
439  * Attempt to return a pointer to the full pathname for use in the
440  * IMA measurement list, IMA audit records, and auditing logs.
441  *
442  * On failure, return a pointer to a copy of the filename, not dname.
443  * Returning a pointer to dname, could result in using the pointer
444  * after the memory has been freed.
445  */
446 const char *ima_d_path(const struct path *path, char **pathbuf, char *namebuf)
447 {
448 	struct name_snapshot filename;
449 	char *pathname = NULL;
450 
451 	*pathbuf = __getname();
452 	if (*pathbuf) {
453 		pathname = d_absolute_path(path, *pathbuf, PATH_MAX);
454 		if (IS_ERR(pathname)) {
455 			__putname(*pathbuf);
456 			*pathbuf = NULL;
457 			pathname = NULL;
458 		}
459 	}
460 
461 	if (!pathname) {
462 		take_dentry_name_snapshot(&filename, path->dentry);
463 		strscpy(namebuf, filename.name.name, NAME_MAX);
464 		release_dentry_name_snapshot(&filename);
465 
466 		pathname = namebuf;
467 	}
468 
469 	return pathname;
470 }
471