xref: /linux/security/integrity/ima/ima_template_lib.c (revision 5a25d8ceb8611c06797b74e22d04af2b9fefd130)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2013 Politecnico di Torino, Italy
4  *                    TORSEC group -- https://security.polito.it
5  *
6  * Author: Roberto Sassu <roberto.sassu@polito.it>
7  *
8  * File: ima_template_lib.c
9  *      Library of supported template fields.
10  */
11 
12 #include "ima_template_lib.h"
13 #include <linux/xattr.h>
14 
15 static bool ima_template_hash_algo_allowed(u8 algo)
16 {
17 	if (algo == HASH_ALGO_SHA1 || algo == HASH_ALGO_MD5)
18 		return true;
19 
20 	return false;
21 }
22 
23 enum data_formats {
24 	DATA_FMT_DIGEST = 0,
25 	DATA_FMT_DIGEST_WITH_ALGO,
26 	DATA_FMT_STRING,
27 	DATA_FMT_HEX
28 };
29 
30 static int ima_write_template_field_data(const void *data, const u32 datalen,
31 					 enum data_formats datafmt,
32 					 struct ima_field_data *field_data)
33 {
34 	u8 *buf, *buf_ptr;
35 	u32 buflen = datalen;
36 
37 	if (datafmt == DATA_FMT_STRING)
38 		buflen = datalen + 1;
39 
40 	buf = kzalloc(buflen, GFP_KERNEL);
41 	if (!buf)
42 		return -ENOMEM;
43 
44 	memcpy(buf, data, datalen);
45 
46 	/*
47 	 * Replace all space characters with underscore for event names and
48 	 * strings. This avoid that, during the parsing of a measurements list,
49 	 * filenames with spaces or that end with the suffix ' (deleted)' are
50 	 * split into multiple template fields (the space is the delimitator
51 	 * character for measurements lists in ASCII format).
52 	 */
53 	if (datafmt == DATA_FMT_STRING) {
54 		for (buf_ptr = buf; buf_ptr - buf < datalen; buf_ptr++)
55 			if (*buf_ptr == ' ')
56 				*buf_ptr = '_';
57 	}
58 
59 	field_data->data = buf;
60 	field_data->len = buflen;
61 	return 0;
62 }
63 
64 static void ima_show_template_data_ascii(struct seq_file *m,
65 					 enum ima_show_type show,
66 					 enum data_formats datafmt,
67 					 struct ima_field_data *field_data)
68 {
69 	u8 *buf_ptr = field_data->data;
70 	u32 buflen = field_data->len;
71 
72 	switch (datafmt) {
73 	case DATA_FMT_DIGEST_WITH_ALGO:
74 		buf_ptr = strnchr(field_data->data, buflen, ':');
75 		if (buf_ptr != field_data->data)
76 			seq_printf(m, "%s", field_data->data);
77 
78 		/* skip ':' and '\0' */
79 		buf_ptr += 2;
80 		buflen -= buf_ptr - field_data->data;
81 		fallthrough;
82 	case DATA_FMT_DIGEST:
83 	case DATA_FMT_HEX:
84 		if (!buflen)
85 			break;
86 		ima_print_digest(m, buf_ptr, buflen);
87 		break;
88 	case DATA_FMT_STRING:
89 		seq_printf(m, "%s", buf_ptr);
90 		break;
91 	default:
92 		break;
93 	}
94 }
95 
96 static void ima_show_template_data_binary(struct seq_file *m,
97 					  enum ima_show_type show,
98 					  enum data_formats datafmt,
99 					  struct ima_field_data *field_data)
100 {
101 	u32 len = (show == IMA_SHOW_BINARY_OLD_STRING_FMT) ?
102 	    strlen(field_data->data) : field_data->len;
103 
104 	if (show != IMA_SHOW_BINARY_NO_FIELD_LEN) {
105 		u32 field_len = !ima_canonical_fmt ? len : cpu_to_le32(len);
106 
107 		ima_putc(m, &field_len, sizeof(field_len));
108 	}
109 
110 	if (!len)
111 		return;
112 
113 	ima_putc(m, field_data->data, len);
114 }
115 
116 static void ima_show_template_field_data(struct seq_file *m,
117 					 enum ima_show_type show,
118 					 enum data_formats datafmt,
119 					 struct ima_field_data *field_data)
120 {
121 	switch (show) {
122 	case IMA_SHOW_ASCII:
123 		ima_show_template_data_ascii(m, show, datafmt, field_data);
124 		break;
125 	case IMA_SHOW_BINARY:
126 	case IMA_SHOW_BINARY_NO_FIELD_LEN:
127 	case IMA_SHOW_BINARY_OLD_STRING_FMT:
128 		ima_show_template_data_binary(m, show, datafmt, field_data);
129 		break;
130 	default:
131 		break;
132 	}
133 }
134 
135 void ima_show_template_digest(struct seq_file *m, enum ima_show_type show,
136 			      struct ima_field_data *field_data)
137 {
138 	ima_show_template_field_data(m, show, DATA_FMT_DIGEST, field_data);
139 }
140 
141 void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show,
142 				 struct ima_field_data *field_data)
143 {
144 	ima_show_template_field_data(m, show, DATA_FMT_DIGEST_WITH_ALGO,
145 				     field_data);
146 }
147 
148 void ima_show_template_string(struct seq_file *m, enum ima_show_type show,
149 			      struct ima_field_data *field_data)
150 {
151 	ima_show_template_field_data(m, show, DATA_FMT_STRING, field_data);
152 }
153 
154 void ima_show_template_sig(struct seq_file *m, enum ima_show_type show,
155 			   struct ima_field_data *field_data)
156 {
157 	ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data);
158 }
159 
160 void ima_show_template_buf(struct seq_file *m, enum ima_show_type show,
161 			   struct ima_field_data *field_data)
162 {
163 	ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data);
164 }
165 
166 /**
167  * ima_parse_buf() - Parses lengths and data from an input buffer
168  * @bufstartp:       Buffer start address.
169  * @bufendp:         Buffer end address.
170  * @bufcurp:         Pointer to remaining (non-parsed) data.
171  * @maxfields:       Length of fields array.
172  * @fields:          Array containing lengths and pointers of parsed data.
173  * @curfields:       Number of array items containing parsed data.
174  * @len_mask:        Bitmap (if bit is set, data length should not be parsed).
175  * @enforce_mask:    Check if curfields == maxfields and/or bufcurp == bufendp.
176  * @bufname:         String identifier of the input buffer.
177  *
178  * Return: 0 on success, -EINVAL on error.
179  */
180 int ima_parse_buf(void *bufstartp, void *bufendp, void **bufcurp,
181 		  int maxfields, struct ima_field_data *fields, int *curfields,
182 		  unsigned long *len_mask, int enforce_mask, char *bufname)
183 {
184 	void *bufp = bufstartp;
185 	int i;
186 
187 	for (i = 0; i < maxfields; i++) {
188 		if (len_mask == NULL || !test_bit(i, len_mask)) {
189 			if (bufp > (bufendp - sizeof(u32)))
190 				break;
191 
192 			fields[i].len = *(u32 *)bufp;
193 			if (ima_canonical_fmt)
194 				fields[i].len = le32_to_cpu(fields[i].len);
195 
196 			bufp += sizeof(u32);
197 		}
198 
199 		if (bufp > (bufendp - fields[i].len))
200 			break;
201 
202 		fields[i].data = bufp;
203 		bufp += fields[i].len;
204 	}
205 
206 	if ((enforce_mask & ENFORCE_FIELDS) && i != maxfields) {
207 		pr_err("%s: nr of fields mismatch: expected: %d, current: %d\n",
208 		       bufname, maxfields, i);
209 		return -EINVAL;
210 	}
211 
212 	if ((enforce_mask & ENFORCE_BUFEND) && bufp != bufendp) {
213 		pr_err("%s: buf end mismatch: expected: %p, current: %p\n",
214 		       bufname, bufendp, bufp);
215 		return -EINVAL;
216 	}
217 
218 	if (curfields)
219 		*curfields = i;
220 
221 	if (bufcurp)
222 		*bufcurp = bufp;
223 
224 	return 0;
225 }
226 
227 static int ima_eventdigest_init_common(const u8 *digest, u32 digestsize,
228 				       u8 hash_algo,
229 				       struct ima_field_data *field_data)
230 {
231 	/*
232 	 * digest formats:
233 	 *  - DATA_FMT_DIGEST: digest
234 	 *  - DATA_FMT_DIGEST_WITH_ALGO: [<hash algo>] + ':' + '\0' + digest,
235 	 *    where <hash algo> is provided if the hash algoritm is not
236 	 *    SHA1 or MD5
237 	 */
238 	u8 buffer[CRYPTO_MAX_ALG_NAME + 2 + IMA_MAX_DIGEST_SIZE] = { 0 };
239 	enum data_formats fmt = DATA_FMT_DIGEST;
240 	u32 offset = 0;
241 
242 	if (hash_algo < HASH_ALGO__LAST) {
243 		fmt = DATA_FMT_DIGEST_WITH_ALGO;
244 		offset += snprintf(buffer, CRYPTO_MAX_ALG_NAME + 1, "%s",
245 				   hash_algo_name[hash_algo]);
246 		buffer[offset] = ':';
247 		offset += 2;
248 	}
249 
250 	if (digest)
251 		memcpy(buffer + offset, digest, digestsize);
252 	else
253 		/*
254 		 * If digest is NULL, the event being recorded is a violation.
255 		 * Make room for the digest by increasing the offset of
256 		 * IMA_DIGEST_SIZE.
257 		 */
258 		offset += IMA_DIGEST_SIZE;
259 
260 	return ima_write_template_field_data(buffer, offset + digestsize,
261 					     fmt, field_data);
262 }
263 
264 /*
265  * This function writes the digest of an event (with size limit).
266  */
267 int ima_eventdigest_init(struct ima_event_data *event_data,
268 			 struct ima_field_data *field_data)
269 {
270 	struct {
271 		struct ima_digest_data hdr;
272 		char digest[IMA_MAX_DIGEST_SIZE];
273 	} hash;
274 	u8 *cur_digest = NULL;
275 	u32 cur_digestsize = 0;
276 	struct inode *inode;
277 	int result;
278 
279 	memset(&hash, 0, sizeof(hash));
280 
281 	if (event_data->violation)	/* recording a violation. */
282 		goto out;
283 
284 	if (ima_template_hash_algo_allowed(event_data->iint->ima_hash->algo)) {
285 		cur_digest = event_data->iint->ima_hash->digest;
286 		cur_digestsize = event_data->iint->ima_hash->length;
287 		goto out;
288 	}
289 
290 	if ((const char *)event_data->filename == boot_aggregate_name) {
291 		if (ima_tpm_chip) {
292 			hash.hdr.algo = HASH_ALGO_SHA1;
293 			result = ima_calc_boot_aggregate(&hash.hdr);
294 
295 			/* algo can change depending on available PCR banks */
296 			if (!result && hash.hdr.algo != HASH_ALGO_SHA1)
297 				result = -EINVAL;
298 
299 			if (result < 0)
300 				memset(&hash, 0, sizeof(hash));
301 		}
302 
303 		cur_digest = hash.hdr.digest;
304 		cur_digestsize = hash_digest_size[HASH_ALGO_SHA1];
305 		goto out;
306 	}
307 
308 	if (!event_data->file)	/* missing info to re-calculate the digest */
309 		return -EINVAL;
310 
311 	inode = file_inode(event_data->file);
312 	hash.hdr.algo = ima_template_hash_algo_allowed(ima_hash_algo) ?
313 	    ima_hash_algo : HASH_ALGO_SHA1;
314 	result = ima_calc_file_hash(event_data->file, &hash.hdr);
315 	if (result) {
316 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
317 				    event_data->filename, "collect_data",
318 				    "failed", result, 0);
319 		return result;
320 	}
321 	cur_digest = hash.hdr.digest;
322 	cur_digestsize = hash.hdr.length;
323 out:
324 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
325 					   HASH_ALGO__LAST, field_data);
326 }
327 
328 /*
329  * This function writes the digest of an event (without size limit).
330  */
331 int ima_eventdigest_ng_init(struct ima_event_data *event_data,
332 			    struct ima_field_data *field_data)
333 {
334 	u8 *cur_digest = NULL, hash_algo = HASH_ALGO_SHA1;
335 	u32 cur_digestsize = 0;
336 
337 	if (event_data->violation)	/* recording a violation. */
338 		goto out;
339 
340 	cur_digest = event_data->iint->ima_hash->digest;
341 	cur_digestsize = event_data->iint->ima_hash->length;
342 
343 	hash_algo = event_data->iint->ima_hash->algo;
344 out:
345 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
346 					   hash_algo, field_data);
347 }
348 
349 /*
350  * This function writes the digest of the file which is expected to match the
351  * digest contained in the file's appended signature.
352  */
353 int ima_eventdigest_modsig_init(struct ima_event_data *event_data,
354 				struct ima_field_data *field_data)
355 {
356 	enum hash_algo hash_algo;
357 	const u8 *cur_digest;
358 	u32 cur_digestsize;
359 
360 	if (!event_data->modsig)
361 		return 0;
362 
363 	if (event_data->violation) {
364 		/* Recording a violation. */
365 		hash_algo = HASH_ALGO_SHA1;
366 		cur_digest = NULL;
367 		cur_digestsize = 0;
368 	} else {
369 		int rc;
370 
371 		rc = ima_get_modsig_digest(event_data->modsig, &hash_algo,
372 					   &cur_digest, &cur_digestsize);
373 		if (rc)
374 			return rc;
375 		else if (hash_algo == HASH_ALGO__LAST || cur_digestsize == 0)
376 			/* There was some error collecting the digest. */
377 			return -EINVAL;
378 	}
379 
380 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
381 					   hash_algo, field_data);
382 }
383 
384 static int ima_eventname_init_common(struct ima_event_data *event_data,
385 				     struct ima_field_data *field_data,
386 				     bool size_limit)
387 {
388 	const char *cur_filename = NULL;
389 	u32 cur_filename_len = 0;
390 
391 	BUG_ON(event_data->filename == NULL && event_data->file == NULL);
392 
393 	if (event_data->filename) {
394 		cur_filename = event_data->filename;
395 		cur_filename_len = strlen(event_data->filename);
396 
397 		if (!size_limit || cur_filename_len <= IMA_EVENT_NAME_LEN_MAX)
398 			goto out;
399 	}
400 
401 	if (event_data->file) {
402 		cur_filename = event_data->file->f_path.dentry->d_name.name;
403 		cur_filename_len = strlen(cur_filename);
404 	} else
405 		/*
406 		 * Truncate filename if the latter is too long and
407 		 * the file descriptor is not available.
408 		 */
409 		cur_filename_len = IMA_EVENT_NAME_LEN_MAX;
410 out:
411 	return ima_write_template_field_data(cur_filename, cur_filename_len,
412 					     DATA_FMT_STRING, field_data);
413 }
414 
415 /*
416  * This function writes the name of an event (with size limit).
417  */
418 int ima_eventname_init(struct ima_event_data *event_data,
419 		       struct ima_field_data *field_data)
420 {
421 	return ima_eventname_init_common(event_data, field_data, true);
422 }
423 
424 /*
425  * This function writes the name of an event (without size limit).
426  */
427 int ima_eventname_ng_init(struct ima_event_data *event_data,
428 			  struct ima_field_data *field_data)
429 {
430 	return ima_eventname_init_common(event_data, field_data, false);
431 }
432 
433 /*
434  *  ima_eventsig_init - include the file signature as part of the template data
435  */
436 int ima_eventsig_init(struct ima_event_data *event_data,
437 		      struct ima_field_data *field_data)
438 {
439 	struct evm_ima_xattr_data *xattr_value = event_data->xattr_value;
440 
441 	if ((!xattr_value) || (xattr_value->type != EVM_IMA_XATTR_DIGSIG))
442 		return ima_eventevmsig_init(event_data, field_data);
443 
444 	return ima_write_template_field_data(xattr_value, event_data->xattr_len,
445 					     DATA_FMT_HEX, field_data);
446 }
447 
448 /*
449  *  ima_eventbuf_init - include the buffer(kexec-cmldine) as part of the
450  *  template data.
451  */
452 int ima_eventbuf_init(struct ima_event_data *event_data,
453 		      struct ima_field_data *field_data)
454 {
455 	if ((!event_data->buf) || (event_data->buf_len == 0))
456 		return 0;
457 
458 	return ima_write_template_field_data(event_data->buf,
459 					     event_data->buf_len, DATA_FMT_HEX,
460 					     field_data);
461 }
462 
463 /*
464  *  ima_eventmodsig_init - include the appended file signature as part of the
465  *  template data
466  */
467 int ima_eventmodsig_init(struct ima_event_data *event_data,
468 			 struct ima_field_data *field_data)
469 {
470 	const void *data;
471 	u32 data_len;
472 	int rc;
473 
474 	if (!event_data->modsig)
475 		return 0;
476 
477 	/*
478 	 * modsig is a runtime structure containing pointers. Get its raw data
479 	 * instead.
480 	 */
481 	rc = ima_get_raw_modsig(event_data->modsig, &data, &data_len);
482 	if (rc)
483 		return rc;
484 
485 	return ima_write_template_field_data(data, data_len, DATA_FMT_HEX,
486 					     field_data);
487 }
488 
489 /*
490  *  ima_eventevmsig_init - include the EVM portable signature as part of the
491  *  template data
492  */
493 int ima_eventevmsig_init(struct ima_event_data *event_data,
494 			 struct ima_field_data *field_data)
495 {
496 	struct evm_ima_xattr_data *xattr_data = NULL;
497 	int rc = 0;
498 
499 	if (!event_data->file)
500 		return 0;
501 
502 	rc = vfs_getxattr_alloc(&init_user_ns, file_dentry(event_data->file),
503 				XATTR_NAME_EVM, (char **)&xattr_data, 0,
504 				GFP_NOFS);
505 	if (rc <= 0)
506 		return 0;
507 
508 	if (xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG) {
509 		kfree(xattr_data);
510 		return 0;
511 	}
512 
513 	rc = ima_write_template_field_data((char *)xattr_data, rc, DATA_FMT_HEX,
514 					   field_data);
515 	kfree(xattr_data);
516 	return rc;
517 }
518