xref: /linux/security/integrity/ima/ima_api.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
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 	 * Detecting file change is based on i_version. On filesystems
273 	 * which do not support i_version, support was originally limited
274 	 * to an initial measurement/appraisal/audit, but was modified to
275 	 * assume the file changed.
276 	 */
277 	result = vfs_getattr_nosec(&file->f_path, &stat, STATX_CHANGE_COOKIE,
278 				   AT_STATX_SYNC_AS_STAT);
279 	if (!result && (stat.result_mask & STATX_CHANGE_COOKIE))
280 		i_version = stat.change_cookie;
281 	hash.hdr.algo = algo;
282 	hash.hdr.length = hash_digest_size[algo];
283 
284 	/* Initialize hash digest to 0's in case of failure */
285 	memset(&hash.digest, 0, sizeof(hash.digest));
286 
287 	if (iint->flags & IMA_VERITY_REQUIRED) {
288 		if (!ima_get_verity_digest(iint, inode, &hash)) {
289 			audit_cause = "no-verity-digest";
290 			result = -ENODATA;
291 		}
292 	} else if (buf) {
293 		result = ima_calc_buffer_hash(buf, size, hash_hdr);
294 	} else {
295 		result = ima_calc_file_hash(file, hash_hdr);
296 	}
297 
298 	if (result && result != -EBADF && result != -EINVAL)
299 		goto out;
300 
301 	length = sizeof(hash.hdr) + hash.hdr.length;
302 	tmpbuf = krealloc(iint->ima_hash, length, GFP_NOFS);
303 	if (!tmpbuf) {
304 		result = -ENOMEM;
305 		goto out;
306 	}
307 
308 	iint->ima_hash = tmpbuf;
309 	memcpy(iint->ima_hash, &hash, length);
310 	if (real_inode == inode)
311 		iint->real_inode.version = i_version;
312 	else
313 		integrity_inode_attrs_store(&iint->real_inode, i_version,
314 					    real_inode);
315 
316 	/* Possibly temporary failure due to type of read (eg. O_DIRECT) */
317 	if (!result)
318 		iint->flags |= IMA_COLLECTED;
319 out:
320 	if (result) {
321 		if (file->f_flags & O_DIRECT)
322 			audit_cause = "failed(directio)";
323 
324 		take_dentry_name_snapshot(&filename, file->f_path.dentry);
325 
326 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
327 				    filename.name.name, "collect_data",
328 				    audit_cause, result, 0);
329 
330 		release_dentry_name_snapshot(&filename);
331 	}
332 	return result;
333 }
334 
335 /*
336  * ima_store_measurement - store file measurement
337  *
338  * Create an "ima" template and then store the template by calling
339  * ima_store_template.
340  *
341  * We only get here if the inode has not already been measured,
342  * but the measurement could already exist:
343  *	- multiple copies of the same file on either the same or
344  *	  different filesystems.
345  *	- the inode was previously flushed as well as the iint info,
346  *	  containing the hashing info.
347  *
348  * Must be called with iint->mutex held.
349  */
350 void ima_store_measurement(struct ima_iint_cache *iint, struct file *file,
351 			   const unsigned char *filename,
352 			   struct evm_ima_xattr_data *xattr_value,
353 			   int xattr_len, const struct modsig *modsig, int pcr,
354 			   struct ima_template_desc *template_desc)
355 {
356 	static const char op[] = "add_template_measure";
357 	static const char audit_cause[] = "ENOMEM";
358 	int result = -ENOMEM;
359 	struct inode *inode = file_inode(file);
360 	struct ima_template_entry *entry;
361 	struct ima_event_data event_data = { .iint = iint,
362 					     .file = file,
363 					     .filename = filename,
364 					     .xattr_value = xattr_value,
365 					     .xattr_len = xattr_len,
366 					     .modsig = modsig };
367 	int violation = 0;
368 
369 	/*
370 	 * We still need to store the measurement in the case of MODSIG because
371 	 * we only have its contents to put in the list at the time of
372 	 * appraisal, but a file measurement from earlier might already exist in
373 	 * the measurement list.
374 	 */
375 	if (iint->measured_pcrs & (0x1 << pcr) && !modsig)
376 		return;
377 
378 	result = ima_alloc_init_template(&event_data, &entry, template_desc);
379 	if (result < 0) {
380 		integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename,
381 				    op, audit_cause, result, 0);
382 		return;
383 	}
384 
385 	result = ima_store_template(entry, violation, inode, filename, pcr);
386 	if ((!result || result == -EEXIST) && !(file->f_flags & O_DIRECT)) {
387 		iint->flags |= IMA_MEASURED;
388 		iint->measured_pcrs |= (0x1 << pcr);
389 	}
390 	if (result < 0)
391 		ima_free_template_entry(entry);
392 }
393 
394 void ima_audit_measurement(struct ima_iint_cache *iint,
395 			   const unsigned char *filename)
396 {
397 	struct audit_buffer *ab;
398 	char *hash;
399 	const char *algo_name = hash_algo_name[iint->ima_hash->algo];
400 	int i;
401 
402 	if (iint->flags & IMA_AUDITED)
403 		return;
404 
405 	hash = kzalloc((iint->ima_hash->length * 2) + 1, GFP_KERNEL);
406 	if (!hash)
407 		return;
408 
409 	for (i = 0; i < iint->ima_hash->length; i++)
410 		hex_byte_pack(hash + (i * 2), iint->ima_hash->digest[i]);
411 	hash[i * 2] = '\0';
412 
413 	ab = audit_log_start(audit_context(), GFP_KERNEL,
414 			     AUDIT_INTEGRITY_RULE);
415 	if (!ab)
416 		goto out;
417 
418 	audit_log_format(ab, "file=");
419 	audit_log_untrustedstring(ab, filename);
420 	audit_log_format(ab, " hash=\"%s:%s\"", algo_name, hash);
421 
422 	audit_log_task_info(ab);
423 	audit_log_end(ab);
424 
425 	iint->flags |= IMA_AUDITED;
426 out:
427 	kfree(hash);
428 	return;
429 }
430 
431 /*
432  * ima_d_path - return a pointer to the full pathname
433  *
434  * Attempt to return a pointer to the full pathname for use in the
435  * IMA measurement list, IMA audit records, and auditing logs.
436  *
437  * On failure, return a pointer to a copy of the filename, not dname.
438  * Returning a pointer to dname, could result in using the pointer
439  * after the memory has been freed.
440  */
441 const char *ima_d_path(const struct path *path, char **pathbuf, char *namebuf)
442 {
443 	struct name_snapshot filename;
444 	char *pathname = NULL;
445 
446 	*pathbuf = __getname();
447 	if (*pathbuf) {
448 		pathname = d_absolute_path(path, *pathbuf, PATH_MAX);
449 		if (IS_ERR(pathname)) {
450 			__putname(*pathbuf);
451 			*pathbuf = NULL;
452 			pathname = NULL;
453 		}
454 	}
455 
456 	if (!pathname) {
457 		take_dentry_name_snapshot(&filename, path->dentry);
458 		strscpy(namebuf, filename.name.name, NAME_MAX);
459 		release_dentry_name_snapshot(&filename);
460 
461 		pathname = namebuf;
462 	}
463 
464 	return pathname;
465 }
466