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 #include <linux/evm.h>
15 
16 static bool ima_template_hash_algo_allowed(u8 algo)
17 {
18 	if (algo == HASH_ALGO_SHA1 || algo == HASH_ALGO_MD5)
19 		return true;
20 
21 	return false;
22 }
23 
24 enum data_formats {
25 	DATA_FMT_DIGEST = 0,
26 	DATA_FMT_DIGEST_WITH_ALGO,
27 	DATA_FMT_STRING,
28 	DATA_FMT_HEX,
29 	DATA_FMT_UINT
30 };
31 
32 static int ima_write_template_field_data(const void *data, const u32 datalen,
33 					 enum data_formats datafmt,
34 					 struct ima_field_data *field_data)
35 {
36 	u8 *buf, *buf_ptr;
37 	u32 buflen = datalen;
38 
39 	if (datafmt == DATA_FMT_STRING)
40 		buflen = datalen + 1;
41 
42 	buf = kzalloc(buflen, GFP_KERNEL);
43 	if (!buf)
44 		return -ENOMEM;
45 
46 	memcpy(buf, data, datalen);
47 
48 	/*
49 	 * Replace all space characters with underscore for event names and
50 	 * strings. This avoid that, during the parsing of a measurements list,
51 	 * filenames with spaces or that end with the suffix ' (deleted)' are
52 	 * split into multiple template fields (the space is the delimitator
53 	 * character for measurements lists in ASCII format).
54 	 */
55 	if (datafmt == DATA_FMT_STRING) {
56 		for (buf_ptr = buf; buf_ptr - buf < datalen; buf_ptr++)
57 			if (*buf_ptr == ' ')
58 				*buf_ptr = '_';
59 	}
60 
61 	field_data->data = buf;
62 	field_data->len = buflen;
63 	return 0;
64 }
65 
66 static void ima_show_template_data_ascii(struct seq_file *m,
67 					 enum ima_show_type show,
68 					 enum data_formats datafmt,
69 					 struct ima_field_data *field_data)
70 {
71 	u8 *buf_ptr = field_data->data;
72 	u32 buflen = field_data->len;
73 
74 	switch (datafmt) {
75 	case DATA_FMT_DIGEST_WITH_ALGO:
76 		buf_ptr = strnchr(field_data->data, buflen, ':');
77 		if (buf_ptr != field_data->data)
78 			seq_printf(m, "%s", field_data->data);
79 
80 		/* skip ':' and '\0' */
81 		buf_ptr += 2;
82 		buflen -= buf_ptr - field_data->data;
83 		fallthrough;
84 	case DATA_FMT_DIGEST:
85 	case DATA_FMT_HEX:
86 		if (!buflen)
87 			break;
88 		ima_print_digest(m, buf_ptr, buflen);
89 		break;
90 	case DATA_FMT_STRING:
91 		seq_printf(m, "%s", buf_ptr);
92 		break;
93 	case DATA_FMT_UINT:
94 		switch (field_data->len) {
95 		case sizeof(u8):
96 			seq_printf(m, "%u", *(u8 *)buf_ptr);
97 			break;
98 		case sizeof(u16):
99 			if (ima_canonical_fmt)
100 				seq_printf(m, "%u",
101 					   le16_to_cpu(*(__le16 *)buf_ptr));
102 			else
103 				seq_printf(m, "%u", *(u16 *)buf_ptr);
104 			break;
105 		case sizeof(u32):
106 			if (ima_canonical_fmt)
107 				seq_printf(m, "%u",
108 					   le32_to_cpu(*(__le32 *)buf_ptr));
109 			else
110 				seq_printf(m, "%u", *(u32 *)buf_ptr);
111 			break;
112 		case sizeof(u64):
113 			if (ima_canonical_fmt)
114 				seq_printf(m, "%llu",
115 					   le64_to_cpu(*(__le64 *)buf_ptr));
116 			else
117 				seq_printf(m, "%llu", *(u64 *)buf_ptr);
118 			break;
119 		default:
120 			break;
121 		}
122 		break;
123 	default:
124 		break;
125 	}
126 }
127 
128 static void ima_show_template_data_binary(struct seq_file *m,
129 					  enum ima_show_type show,
130 					  enum data_formats datafmt,
131 					  struct ima_field_data *field_data)
132 {
133 	u32 len = (show == IMA_SHOW_BINARY_OLD_STRING_FMT) ?
134 	    strlen(field_data->data) : field_data->len;
135 
136 	if (show != IMA_SHOW_BINARY_NO_FIELD_LEN) {
137 		u32 field_len = !ima_canonical_fmt ?
138 				len : (__force u32)cpu_to_le32(len);
139 
140 		ima_putc(m, &field_len, sizeof(field_len));
141 	}
142 
143 	if (!len)
144 		return;
145 
146 	ima_putc(m, field_data->data, len);
147 }
148 
149 static void ima_show_template_field_data(struct seq_file *m,
150 					 enum ima_show_type show,
151 					 enum data_formats datafmt,
152 					 struct ima_field_data *field_data)
153 {
154 	switch (show) {
155 	case IMA_SHOW_ASCII:
156 		ima_show_template_data_ascii(m, show, datafmt, field_data);
157 		break;
158 	case IMA_SHOW_BINARY:
159 	case IMA_SHOW_BINARY_NO_FIELD_LEN:
160 	case IMA_SHOW_BINARY_OLD_STRING_FMT:
161 		ima_show_template_data_binary(m, show, datafmt, field_data);
162 		break;
163 	default:
164 		break;
165 	}
166 }
167 
168 void ima_show_template_digest(struct seq_file *m, enum ima_show_type show,
169 			      struct ima_field_data *field_data)
170 {
171 	ima_show_template_field_data(m, show, DATA_FMT_DIGEST, field_data);
172 }
173 
174 void ima_show_template_digest_ng(struct seq_file *m, enum ima_show_type show,
175 				 struct ima_field_data *field_data)
176 {
177 	ima_show_template_field_data(m, show, DATA_FMT_DIGEST_WITH_ALGO,
178 				     field_data);
179 }
180 
181 void ima_show_template_string(struct seq_file *m, enum ima_show_type show,
182 			      struct ima_field_data *field_data)
183 {
184 	ima_show_template_field_data(m, show, DATA_FMT_STRING, field_data);
185 }
186 
187 void ima_show_template_sig(struct seq_file *m, enum ima_show_type show,
188 			   struct ima_field_data *field_data)
189 {
190 	ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data);
191 }
192 
193 void ima_show_template_buf(struct seq_file *m, enum ima_show_type show,
194 			   struct ima_field_data *field_data)
195 {
196 	ima_show_template_field_data(m, show, DATA_FMT_HEX, field_data);
197 }
198 
199 void ima_show_template_uint(struct seq_file *m, enum ima_show_type show,
200 			    struct ima_field_data *field_data)
201 {
202 	ima_show_template_field_data(m, show, DATA_FMT_UINT, field_data);
203 }
204 
205 /**
206  * ima_parse_buf() - Parses lengths and data from an input buffer
207  * @bufstartp:       Buffer start address.
208  * @bufendp:         Buffer end address.
209  * @bufcurp:         Pointer to remaining (non-parsed) data.
210  * @maxfields:       Length of fields array.
211  * @fields:          Array containing lengths and pointers of parsed data.
212  * @curfields:       Number of array items containing parsed data.
213  * @len_mask:        Bitmap (if bit is set, data length should not be parsed).
214  * @enforce_mask:    Check if curfields == maxfields and/or bufcurp == bufendp.
215  * @bufname:         String identifier of the input buffer.
216  *
217  * Return: 0 on success, -EINVAL on error.
218  */
219 int ima_parse_buf(void *bufstartp, void *bufendp, void **bufcurp,
220 		  int maxfields, struct ima_field_data *fields, int *curfields,
221 		  unsigned long *len_mask, int enforce_mask, char *bufname)
222 {
223 	void *bufp = bufstartp;
224 	int i;
225 
226 	for (i = 0; i < maxfields; i++) {
227 		if (len_mask == NULL || !test_bit(i, len_mask)) {
228 			if (bufp > (bufendp - sizeof(u32)))
229 				break;
230 
231 			if (ima_canonical_fmt)
232 				fields[i].len = le32_to_cpu(*(__le32 *)bufp);
233 			else
234 				fields[i].len = *(u32 *)bufp;
235 
236 			bufp += sizeof(u32);
237 		}
238 
239 		if (bufp > (bufendp - fields[i].len))
240 			break;
241 
242 		fields[i].data = bufp;
243 		bufp += fields[i].len;
244 	}
245 
246 	if ((enforce_mask & ENFORCE_FIELDS) && i != maxfields) {
247 		pr_err("%s: nr of fields mismatch: expected: %d, current: %d\n",
248 		       bufname, maxfields, i);
249 		return -EINVAL;
250 	}
251 
252 	if ((enforce_mask & ENFORCE_BUFEND) && bufp != bufendp) {
253 		pr_err("%s: buf end mismatch: expected: %p, current: %p\n",
254 		       bufname, bufendp, bufp);
255 		return -EINVAL;
256 	}
257 
258 	if (curfields)
259 		*curfields = i;
260 
261 	if (bufcurp)
262 		*bufcurp = bufp;
263 
264 	return 0;
265 }
266 
267 static int ima_eventdigest_init_common(const u8 *digest, u32 digestsize,
268 				       u8 hash_algo,
269 				       struct ima_field_data *field_data)
270 {
271 	/*
272 	 * digest formats:
273 	 *  - DATA_FMT_DIGEST: digest
274 	 *  - DATA_FMT_DIGEST_WITH_ALGO: [<hash algo>] + ':' + '\0' + digest,
275 	 *    where <hash algo> is provided if the hash algorithm is not
276 	 *    SHA1 or MD5
277 	 */
278 	u8 buffer[CRYPTO_MAX_ALG_NAME + 2 + IMA_MAX_DIGEST_SIZE] = { 0 };
279 	enum data_formats fmt = DATA_FMT_DIGEST;
280 	u32 offset = 0;
281 
282 	if (hash_algo < HASH_ALGO__LAST) {
283 		fmt = DATA_FMT_DIGEST_WITH_ALGO;
284 		offset += snprintf(buffer, CRYPTO_MAX_ALG_NAME + 1, "%s",
285 				   hash_algo_name[hash_algo]);
286 		buffer[offset] = ':';
287 		offset += 2;
288 	}
289 
290 	if (digest)
291 		memcpy(buffer + offset, digest, digestsize);
292 	else
293 		/*
294 		 * If digest is NULL, the event being recorded is a violation.
295 		 * Make room for the digest by increasing the offset of
296 		 * IMA_DIGEST_SIZE.
297 		 */
298 		offset += IMA_DIGEST_SIZE;
299 
300 	return ima_write_template_field_data(buffer, offset + digestsize,
301 					     fmt, field_data);
302 }
303 
304 /*
305  * This function writes the digest of an event (with size limit).
306  */
307 int ima_eventdigest_init(struct ima_event_data *event_data,
308 			 struct ima_field_data *field_data)
309 {
310 	struct ima_max_digest_data hash;
311 	u8 *cur_digest = NULL;
312 	u32 cur_digestsize = 0;
313 	struct inode *inode;
314 	int result;
315 
316 	memset(&hash, 0, sizeof(hash));
317 
318 	if (event_data->violation)	/* recording a violation. */
319 		goto out;
320 
321 	if (ima_template_hash_algo_allowed(event_data->iint->ima_hash->algo)) {
322 		cur_digest = event_data->iint->ima_hash->digest;
323 		cur_digestsize = event_data->iint->ima_hash->length;
324 		goto out;
325 	}
326 
327 	if ((const char *)event_data->filename == boot_aggregate_name) {
328 		if (ima_tpm_chip) {
329 			hash.hdr.algo = HASH_ALGO_SHA1;
330 			result = ima_calc_boot_aggregate(&hash.hdr);
331 
332 			/* algo can change depending on available PCR banks */
333 			if (!result && hash.hdr.algo != HASH_ALGO_SHA1)
334 				result = -EINVAL;
335 
336 			if (result < 0)
337 				memset(&hash, 0, sizeof(hash));
338 		}
339 
340 		cur_digest = hash.hdr.digest;
341 		cur_digestsize = hash_digest_size[HASH_ALGO_SHA1];
342 		goto out;
343 	}
344 
345 	if (!event_data->file)	/* missing info to re-calculate the digest */
346 		return -EINVAL;
347 
348 	inode = file_inode(event_data->file);
349 	hash.hdr.algo = ima_template_hash_algo_allowed(ima_hash_algo) ?
350 	    ima_hash_algo : HASH_ALGO_SHA1;
351 	result = ima_calc_file_hash(event_data->file, &hash.hdr);
352 	if (result) {
353 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
354 				    event_data->filename, "collect_data",
355 				    "failed", result, 0);
356 		return result;
357 	}
358 	cur_digest = hash.hdr.digest;
359 	cur_digestsize = hash.hdr.length;
360 out:
361 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
362 					   HASH_ALGO__LAST, field_data);
363 }
364 
365 /*
366  * This function writes the digest of an event (without size limit).
367  */
368 int ima_eventdigest_ng_init(struct ima_event_data *event_data,
369 			    struct ima_field_data *field_data)
370 {
371 	u8 *cur_digest = NULL, hash_algo = HASH_ALGO_SHA1;
372 	u32 cur_digestsize = 0;
373 
374 	if (event_data->violation)	/* recording a violation. */
375 		goto out;
376 
377 	cur_digest = event_data->iint->ima_hash->digest;
378 	cur_digestsize = event_data->iint->ima_hash->length;
379 
380 	hash_algo = event_data->iint->ima_hash->algo;
381 out:
382 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
383 					   hash_algo, field_data);
384 }
385 
386 /*
387  * This function writes the digest of the file which is expected to match the
388  * digest contained in the file's appended signature.
389  */
390 int ima_eventdigest_modsig_init(struct ima_event_data *event_data,
391 				struct ima_field_data *field_data)
392 {
393 	enum hash_algo hash_algo;
394 	const u8 *cur_digest;
395 	u32 cur_digestsize;
396 
397 	if (!event_data->modsig)
398 		return 0;
399 
400 	if (event_data->violation) {
401 		/* Recording a violation. */
402 		hash_algo = HASH_ALGO_SHA1;
403 		cur_digest = NULL;
404 		cur_digestsize = 0;
405 	} else {
406 		int rc;
407 
408 		rc = ima_get_modsig_digest(event_data->modsig, &hash_algo,
409 					   &cur_digest, &cur_digestsize);
410 		if (rc)
411 			return rc;
412 		else if (hash_algo == HASH_ALGO__LAST || cur_digestsize == 0)
413 			/* There was some error collecting the digest. */
414 			return -EINVAL;
415 	}
416 
417 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
418 					   hash_algo, field_data);
419 }
420 
421 static int ima_eventname_init_common(struct ima_event_data *event_data,
422 				     struct ima_field_data *field_data,
423 				     bool size_limit)
424 {
425 	const char *cur_filename = NULL;
426 	u32 cur_filename_len = 0;
427 
428 	BUG_ON(event_data->filename == NULL && event_data->file == NULL);
429 
430 	if (event_data->filename) {
431 		cur_filename = event_data->filename;
432 		cur_filename_len = strlen(event_data->filename);
433 
434 		if (!size_limit || cur_filename_len <= IMA_EVENT_NAME_LEN_MAX)
435 			goto out;
436 	}
437 
438 	if (event_data->file) {
439 		cur_filename = event_data->file->f_path.dentry->d_name.name;
440 		cur_filename_len = strlen(cur_filename);
441 	} else
442 		/*
443 		 * Truncate filename if the latter is too long and
444 		 * the file descriptor is not available.
445 		 */
446 		cur_filename_len = IMA_EVENT_NAME_LEN_MAX;
447 out:
448 	return ima_write_template_field_data(cur_filename, cur_filename_len,
449 					     DATA_FMT_STRING, field_data);
450 }
451 
452 /*
453  * This function writes the name of an event (with size limit).
454  */
455 int ima_eventname_init(struct ima_event_data *event_data,
456 		       struct ima_field_data *field_data)
457 {
458 	return ima_eventname_init_common(event_data, field_data, true);
459 }
460 
461 /*
462  * This function writes the name of an event (without size limit).
463  */
464 int ima_eventname_ng_init(struct ima_event_data *event_data,
465 			  struct ima_field_data *field_data)
466 {
467 	return ima_eventname_init_common(event_data, field_data, false);
468 }
469 
470 /*
471  *  ima_eventsig_init - include the file signature as part of the template data
472  */
473 int ima_eventsig_init(struct ima_event_data *event_data,
474 		      struct ima_field_data *field_data)
475 {
476 	struct evm_ima_xattr_data *xattr_value = event_data->xattr_value;
477 
478 	if ((!xattr_value) || (xattr_value->type != EVM_IMA_XATTR_DIGSIG))
479 		return ima_eventevmsig_init(event_data, field_data);
480 
481 	return ima_write_template_field_data(xattr_value, event_data->xattr_len,
482 					     DATA_FMT_HEX, field_data);
483 }
484 
485 /*
486  *  ima_eventbuf_init - include the buffer(kexec-cmldine) as part of the
487  *  template data.
488  */
489 int ima_eventbuf_init(struct ima_event_data *event_data,
490 		      struct ima_field_data *field_data)
491 {
492 	if ((!event_data->buf) || (event_data->buf_len == 0))
493 		return 0;
494 
495 	return ima_write_template_field_data(event_data->buf,
496 					     event_data->buf_len, DATA_FMT_HEX,
497 					     field_data);
498 }
499 
500 /*
501  *  ima_eventmodsig_init - include the appended file signature as part of the
502  *  template data
503  */
504 int ima_eventmodsig_init(struct ima_event_data *event_data,
505 			 struct ima_field_data *field_data)
506 {
507 	const void *data;
508 	u32 data_len;
509 	int rc;
510 
511 	if (!event_data->modsig)
512 		return 0;
513 
514 	/*
515 	 * modsig is a runtime structure containing pointers. Get its raw data
516 	 * instead.
517 	 */
518 	rc = ima_get_raw_modsig(event_data->modsig, &data, &data_len);
519 	if (rc)
520 		return rc;
521 
522 	return ima_write_template_field_data(data, data_len, DATA_FMT_HEX,
523 					     field_data);
524 }
525 
526 /*
527  *  ima_eventevmsig_init - include the EVM portable signature as part of the
528  *  template data
529  */
530 int ima_eventevmsig_init(struct ima_event_data *event_data,
531 			 struct ima_field_data *field_data)
532 {
533 	struct evm_ima_xattr_data *xattr_data = NULL;
534 	int rc = 0;
535 
536 	if (!event_data->file)
537 		return 0;
538 
539 	rc = vfs_getxattr_alloc(&init_user_ns, file_dentry(event_data->file),
540 				XATTR_NAME_EVM, (char **)&xattr_data, 0,
541 				GFP_NOFS);
542 	if (rc <= 0)
543 		return 0;
544 
545 	if (xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG) {
546 		kfree(xattr_data);
547 		return 0;
548 	}
549 
550 	rc = ima_write_template_field_data((char *)xattr_data, rc, DATA_FMT_HEX,
551 					   field_data);
552 	kfree(xattr_data);
553 	return rc;
554 }
555 
556 static int ima_eventinodedac_init_common(struct ima_event_data *event_data,
557 					 struct ima_field_data *field_data,
558 					 bool get_uid)
559 {
560 	unsigned int id;
561 
562 	if (!event_data->file)
563 		return 0;
564 
565 	if (get_uid)
566 		id = i_uid_read(file_inode(event_data->file));
567 	else
568 		id = i_gid_read(file_inode(event_data->file));
569 
570 	if (ima_canonical_fmt) {
571 		if (sizeof(id) == sizeof(u16))
572 			id = (__force u16)cpu_to_le16(id);
573 		else
574 			id = (__force u32)cpu_to_le32(id);
575 	}
576 
577 	return ima_write_template_field_data((void *)&id, sizeof(id),
578 					     DATA_FMT_UINT, field_data);
579 }
580 
581 /*
582  *  ima_eventinodeuid_init - include the inode UID as part of the template
583  *  data
584  */
585 int ima_eventinodeuid_init(struct ima_event_data *event_data,
586 			   struct ima_field_data *field_data)
587 {
588 	return ima_eventinodedac_init_common(event_data, field_data, true);
589 }
590 
591 /*
592  *  ima_eventinodegid_init - include the inode GID as part of the template
593  *  data
594  */
595 int ima_eventinodegid_init(struct ima_event_data *event_data,
596 			   struct ima_field_data *field_data)
597 {
598 	return ima_eventinodedac_init_common(event_data, field_data, false);
599 }
600 
601 /*
602  *  ima_eventinodemode_init - include the inode mode as part of the template
603  *  data
604  */
605 int ima_eventinodemode_init(struct ima_event_data *event_data,
606 			    struct ima_field_data *field_data)
607 {
608 	struct inode *inode;
609 	u16 mode;
610 
611 	if (!event_data->file)
612 		return 0;
613 
614 	inode = file_inode(event_data->file);
615 	mode = inode->i_mode;
616 	if (ima_canonical_fmt)
617 		mode = (__force u16)cpu_to_le16(mode);
618 
619 	return ima_write_template_field_data((char *)&mode, sizeof(mode),
620 					     DATA_FMT_UINT, field_data);
621 }
622 
623 static int ima_eventinodexattrs_init_common(struct ima_event_data *event_data,
624 					    struct ima_field_data *field_data,
625 					    char type)
626 {
627 	u8 *buffer = NULL;
628 	int rc;
629 
630 	if (!event_data->file)
631 		return 0;
632 
633 	rc = evm_read_protected_xattrs(file_dentry(event_data->file), NULL, 0,
634 				       type, ima_canonical_fmt);
635 	if (rc < 0)
636 		return 0;
637 
638 	buffer = kmalloc(rc, GFP_KERNEL);
639 	if (!buffer)
640 		return 0;
641 
642 	rc = evm_read_protected_xattrs(file_dentry(event_data->file), buffer,
643 				       rc, type, ima_canonical_fmt);
644 	if (rc < 0) {
645 		rc = 0;
646 		goto out;
647 	}
648 
649 	rc = ima_write_template_field_data((char *)buffer, rc, DATA_FMT_HEX,
650 					   field_data);
651 out:
652 	kfree(buffer);
653 	return rc;
654 }
655 
656 /*
657  *  ima_eventinodexattrnames_init - include a list of xattr names as part of the
658  *  template data
659  */
660 int ima_eventinodexattrnames_init(struct ima_event_data *event_data,
661 				  struct ima_field_data *field_data)
662 {
663 	return ima_eventinodexattrs_init_common(event_data, field_data, 'n');
664 }
665 
666 /*
667  *  ima_eventinodexattrlengths_init - include a list of xattr lengths as part of
668  *  the template data
669  */
670 int ima_eventinodexattrlengths_init(struct ima_event_data *event_data,
671 				    struct ima_field_data *field_data)
672 {
673 	return ima_eventinodexattrs_init_common(event_data, field_data, 'l');
674 }
675 
676 /*
677  *  ima_eventinodexattrvalues_init - include a list of xattr values as part of
678  *  the template data
679  */
680 int ima_eventinodexattrvalues_init(struct ima_event_data *event_data,
681 				   struct ima_field_data *field_data)
682 {
683 	return ima_eventinodexattrs_init_common(event_data, field_data, 'v');
684 }
685