1 /*
2  * Copyright (C) 2005,2006,2007,2008 IBM Corporation
3  *
4  * Authors:
5  * Reiner Sailer <sailer@watson.ibm.com>
6  * Serge Hallyn <serue@us.ibm.com>
7  * Kylene Hall <kylene@us.ibm.com>
8  * Mimi Zohar <zohar@us.ibm.com>
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as
12  * published by the Free Software Foundation, version 2 of the
13  * License.
14  *
15  * File: ima_main.c
16  *	implements the IMA hooks: ima_bprm_check, ima_file_mmap,
17  *	and ima_path_check.
18  */
19 #include <linux/module.h>
20 #include <linux/file.h>
21 #include <linux/binfmts.h>
22 #include <linux/mount.h>
23 #include <linux/mman.h>
24 
25 #include "ima.h"
26 
27 int ima_initialized;
28 
29 char *ima_hash = "sha1";
30 static int __init hash_setup(char *str)
31 {
32 	if (strncmp(str, "md5", 3) == 0)
33 		ima_hash = "md5";
34 	return 1;
35 }
36 __setup("ima_hash=", hash_setup);
37 
38 struct ima_imbalance {
39 	struct hlist_node node;
40 	unsigned long fsmagic;
41 };
42 
43 /*
44  * ima_limit_imbalance - emit one imbalance message per filesystem type
45  *
46  * Maintain list of filesystem types that do not measure files properly.
47  * Return false if unknown, true if known.
48  */
49 static bool ima_limit_imbalance(struct file *file)
50 {
51 	static DEFINE_SPINLOCK(ima_imbalance_lock);
52 	static HLIST_HEAD(ima_imbalance_list);
53 
54 	struct super_block *sb = file->f_dentry->d_sb;
55 	struct ima_imbalance *entry;
56 	struct hlist_node *node;
57 	bool found = false;
58 
59 	rcu_read_lock();
60 	hlist_for_each_entry_rcu(entry, node, &ima_imbalance_list, node) {
61 		if (entry->fsmagic == sb->s_magic) {
62 			found = true;
63 			break;
64 		}
65 	}
66 	rcu_read_unlock();
67 	if (found)
68 		goto out;
69 
70 	entry = kmalloc(sizeof(*entry), GFP_NOFS);
71 	if (!entry)
72 		goto out;
73 	entry->fsmagic = sb->s_magic;
74 	spin_lock(&ima_imbalance_lock);
75 	/*
76 	 * we could have raced and something else might have added this fs
77 	 * to the list, but we don't really care
78 	 */
79 	hlist_add_head_rcu(&entry->node, &ima_imbalance_list);
80 	spin_unlock(&ima_imbalance_lock);
81 	printk(KERN_INFO "IMA: unmeasured files on fsmagic: %lX\n",
82 	       entry->fsmagic);
83 out:
84 	return found;
85 }
86 
87 /*
88  * Update the counts given an fmode_t
89  */
90 static void ima_inc_counts(struct ima_iint_cache *iint, fmode_t mode)
91 {
92 	BUG_ON(!mutex_is_locked(&iint->mutex));
93 
94 	iint->opencount++;
95 	if ((mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
96 		iint->readcount++;
97 	if (mode & FMODE_WRITE)
98 		iint->writecount++;
99 }
100 
101 /*
102  * Decrement ima counts
103  */
104 static void ima_dec_counts(struct ima_iint_cache *iint, struct inode *inode,
105 			   struct file *file)
106 {
107 	mode_t mode = file->f_mode;
108 	BUG_ON(!mutex_is_locked(&iint->mutex));
109 
110 	iint->opencount--;
111 	if ((mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
112 		iint->readcount--;
113 	if (mode & FMODE_WRITE) {
114 		iint->writecount--;
115 		if (iint->writecount == 0) {
116 			if (iint->version != inode->i_version)
117 				iint->flags &= ~IMA_MEASURED;
118 		}
119 	}
120 
121 	if (((iint->opencount < 0) ||
122 	     (iint->readcount < 0) ||
123 	     (iint->writecount < 0)) &&
124 	    !ima_limit_imbalance(file)) {
125 		printk(KERN_INFO "%s: open/free imbalance (r:%ld w:%ld o:%ld)\n",
126 		       __FUNCTION__, iint->readcount, iint->writecount,
127 		       iint->opencount);
128 		dump_stack();
129 	}
130 }
131 
132 /**
133  * ima_file_free - called on __fput()
134  * @file: pointer to file structure being freed
135  *
136  * Flag files that changed, based on i_version;
137  * and decrement the iint readcount/writecount.
138  */
139 void ima_file_free(struct file *file)
140 {
141 	struct inode *inode = file->f_dentry->d_inode;
142 	struct ima_iint_cache *iint;
143 
144 	if (!ima_initialized || !S_ISREG(inode->i_mode))
145 		return;
146 	iint = ima_iint_find_get(inode);
147 	if (!iint)
148 		return;
149 
150 	mutex_lock(&iint->mutex);
151 	ima_dec_counts(iint, inode, file);
152 	mutex_unlock(&iint->mutex);
153 	kref_put(&iint->refcount, iint_free);
154 }
155 
156 /* ima_read_write_check - reflect possible reading/writing errors in the PCR.
157  *
158  * When opening a file for read, if the file is already open for write,
159  * the file could change, resulting in a file measurement error.
160  *
161  * Opening a file for write, if the file is already open for read, results
162  * in a time of measure, time of use (ToMToU) error.
163  *
164  * In either case invalidate the PCR.
165  */
166 enum iint_pcr_error { TOMTOU, OPEN_WRITERS };
167 static void ima_read_write_check(enum iint_pcr_error error,
168 				 struct ima_iint_cache *iint,
169 				 struct inode *inode,
170 				 const unsigned char *filename)
171 {
172 	switch (error) {
173 	case TOMTOU:
174 		if (iint->readcount > 0)
175 			ima_add_violation(inode, filename, "invalid_pcr",
176 					  "ToMToU");
177 		break;
178 	case OPEN_WRITERS:
179 		if (iint->writecount > 0)
180 			ima_add_violation(inode, filename, "invalid_pcr",
181 					  "open_writers");
182 		break;
183 	}
184 }
185 
186 static int get_path_measurement(struct ima_iint_cache *iint, struct file *file,
187 				const unsigned char *filename)
188 {
189 	int rc = 0;
190 
191 	ima_inc_counts(iint, file->f_mode);
192 
193 	rc = ima_collect_measurement(iint, file);
194 	if (!rc)
195 		ima_store_measurement(iint, file, filename);
196 	return rc;
197 }
198 
199 /**
200  * ima_path_check - based on policy, collect/store measurement.
201  * @path: contains a pointer to the path to be measured
202  * @mask: contains MAY_READ, MAY_WRITE or MAY_EXECUTE
203  *
204  * Measure the file being open for readonly, based on the
205  * ima_must_measure() policy decision.
206  *
207  * Keep read/write counters for all files, but only
208  * invalidate the PCR for measured files:
209  * 	- Opening a file for write when already open for read,
210  *	  results in a time of measure, time of use (ToMToU) error.
211  *	- Opening a file for read when already open for write,
212  * 	  could result in a file measurement error.
213  *
214  * Always return 0 and audit dentry_open failures.
215  * (Return code will be based upon measurement appraisal.)
216  */
217 int ima_path_check(struct path *path, int mask)
218 {
219 	struct inode *inode = path->dentry->d_inode;
220 	struct ima_iint_cache *iint;
221 	struct file *file = NULL;
222 	int rc;
223 
224 	if (!ima_initialized || !S_ISREG(inode->i_mode))
225 		return 0;
226 	iint = ima_iint_find_get(inode);
227 	if (!iint)
228 		return 0;
229 
230 	mutex_lock(&iint->mutex);
231 
232 	rc = ima_must_measure(iint, inode, MAY_READ, PATH_CHECK);
233 	if (rc < 0)
234 		goto out;
235 
236 	if ((mask & MAY_WRITE) || (mask == 0))
237 		ima_read_write_check(TOMTOU, iint, inode,
238 				     path->dentry->d_name.name);
239 
240 	if ((mask & (MAY_WRITE | MAY_READ | MAY_EXEC)) != MAY_READ)
241 		goto out;
242 
243 	ima_read_write_check(OPEN_WRITERS, iint, inode,
244 			     path->dentry->d_name.name);
245 	if (!(iint->flags & IMA_MEASURED)) {
246 		struct dentry *dentry = dget(path->dentry);
247 		struct vfsmount *mnt = mntget(path->mnt);
248 
249 		file = dentry_open(dentry, mnt, O_RDONLY | O_LARGEFILE,
250 				   current_cred());
251 		if (IS_ERR(file)) {
252 			int audit_info = 0;
253 
254 			integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode,
255 					    dentry->d_name.name,
256 					    "add_measurement",
257 					    "dentry_open failed",
258 					    1, audit_info);
259 			file = NULL;
260 			goto out;
261 		}
262 		rc = get_path_measurement(iint, file, dentry->d_name.name);
263 	}
264 out:
265 	mutex_unlock(&iint->mutex);
266 	if (file)
267 		fput(file);
268 	kref_put(&iint->refcount, iint_free);
269 	return 0;
270 }
271 EXPORT_SYMBOL_GPL(ima_path_check);
272 
273 static int process_measurement(struct file *file, const unsigned char *filename,
274 			       int mask, int function)
275 {
276 	struct inode *inode = file->f_dentry->d_inode;
277 	struct ima_iint_cache *iint;
278 	int rc;
279 
280 	if (!ima_initialized || !S_ISREG(inode->i_mode))
281 		return 0;
282 	iint = ima_iint_find_get(inode);
283 	if (!iint)
284 		return -ENOMEM;
285 
286 	mutex_lock(&iint->mutex);
287 	rc = ima_must_measure(iint, inode, mask, function);
288 	if (rc != 0)
289 		goto out;
290 
291 	rc = ima_collect_measurement(iint, file);
292 	if (!rc)
293 		ima_store_measurement(iint, file, filename);
294 out:
295 	mutex_unlock(&iint->mutex);
296 	kref_put(&iint->refcount, iint_free);
297 	return rc;
298 }
299 
300 /*
301  * ima_counts_get - increment file counts
302  *
303  * - for IPC shm and shmat file.
304  * - for nfsd exported files.
305  *
306  * Increment the counts for these files to prevent unnecessary
307  * imbalance messages.
308  */
309 void ima_counts_get(struct file *file)
310 {
311 	struct inode *inode = file->f_dentry->d_inode;
312 	struct ima_iint_cache *iint;
313 
314 	if (!ima_initialized || !S_ISREG(inode->i_mode))
315 		return;
316 	iint = ima_iint_find_get(inode);
317 	if (!iint)
318 		return;
319 	mutex_lock(&iint->mutex);
320 	ima_inc_counts(iint, file->f_mode);
321 	mutex_unlock(&iint->mutex);
322 
323 	kref_put(&iint->refcount, iint_free);
324 }
325 EXPORT_SYMBOL_GPL(ima_counts_get);
326 
327 /**
328  * ima_file_mmap - based on policy, collect/store measurement.
329  * @file: pointer to the file to be measured (May be NULL)
330  * @prot: contains the protection that will be applied by the kernel.
331  *
332  * Measure files being mmapped executable based on the ima_must_measure()
333  * policy decision.
334  *
335  * Return 0 on success, an error code on failure.
336  * (Based on the results of appraise_measurement().)
337  */
338 int ima_file_mmap(struct file *file, unsigned long prot)
339 {
340 	int rc;
341 
342 	if (!file)
343 		return 0;
344 	if (prot & PROT_EXEC)
345 		rc = process_measurement(file, file->f_dentry->d_name.name,
346 					 MAY_EXEC, FILE_MMAP);
347 	return 0;
348 }
349 
350 /**
351  * ima_bprm_check - based on policy, collect/store measurement.
352  * @bprm: contains the linux_binprm structure
353  *
354  * The OS protects against an executable file, already open for write,
355  * from being executed in deny_write_access() and an executable file,
356  * already open for execute, from being modified in get_write_access().
357  * So we can be certain that what we verify and measure here is actually
358  * what is being executed.
359  *
360  * Return 0 on success, an error code on failure.
361  * (Based on the results of appraise_measurement().)
362  */
363 int ima_bprm_check(struct linux_binprm *bprm)
364 {
365 	int rc;
366 
367 	rc = process_measurement(bprm->file, bprm->filename,
368 				 MAY_EXEC, BPRM_CHECK);
369 	return 0;
370 }
371 
372 static int __init init_ima(void)
373 {
374 	int error;
375 
376 	ima_iintcache_init();
377 	error = ima_init();
378 	ima_initialized = 1;
379 	return error;
380 }
381 
382 static void __exit cleanup_ima(void)
383 {
384 	ima_cleanup();
385 }
386 
387 late_initcall(init_ima);	/* Start IMA after the TPM is available */
388 
389 MODULE_DESCRIPTION("Integrity Measurement Architecture");
390 MODULE_LICENSE("GPL");
391