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