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 algoritm 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 {
311 		struct ima_digest_data hdr;
312 		char digest[IMA_MAX_DIGEST_SIZE];
313 	} hash;
314 	u8 *cur_digest = NULL;
315 	u32 cur_digestsize = 0;
316 	struct inode *inode;
317 	int result;
318 
319 	memset(&hash, 0, sizeof(hash));
320 
321 	if (event_data->violation)	/* recording a violation. */
322 		goto out;
323 
324 	if (ima_template_hash_algo_allowed(event_data->iint->ima_hash->algo)) {
325 		cur_digest = event_data->iint->ima_hash->digest;
326 		cur_digestsize = event_data->iint->ima_hash->length;
327 		goto out;
328 	}
329 
330 	if ((const char *)event_data->filename == boot_aggregate_name) {
331 		if (ima_tpm_chip) {
332 			hash.hdr.algo = HASH_ALGO_SHA1;
333 			result = ima_calc_boot_aggregate(&hash.hdr);
334 
335 			/* algo can change depending on available PCR banks */
336 			if (!result && hash.hdr.algo != HASH_ALGO_SHA1)
337 				result = -EINVAL;
338 
339 			if (result < 0)
340 				memset(&hash, 0, sizeof(hash));
341 		}
342 
343 		cur_digest = hash.hdr.digest;
344 		cur_digestsize = hash_digest_size[HASH_ALGO_SHA1];
345 		goto out;
346 	}
347 
348 	if (!event_data->file)	/* missing info to re-calculate the digest */
349 		return -EINVAL;
350 
351 	inode = file_inode(event_data->file);
352 	hash.hdr.algo = ima_template_hash_algo_allowed(ima_hash_algo) ?
353 	    ima_hash_algo : HASH_ALGO_SHA1;
354 	result = ima_calc_file_hash(event_data->file, &hash.hdr);
355 	if (result) {
356 		integrity_audit_msg(AUDIT_INTEGRITY_DATA, inode,
357 				    event_data->filename, "collect_data",
358 				    "failed", result, 0);
359 		return result;
360 	}
361 	cur_digest = hash.hdr.digest;
362 	cur_digestsize = hash.hdr.length;
363 out:
364 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
365 					   HASH_ALGO__LAST, field_data);
366 }
367 
368 /*
369  * This function writes the digest of an event (without size limit).
370  */
371 int ima_eventdigest_ng_init(struct ima_event_data *event_data,
372 			    struct ima_field_data *field_data)
373 {
374 	u8 *cur_digest = NULL, hash_algo = HASH_ALGO_SHA1;
375 	u32 cur_digestsize = 0;
376 
377 	if (event_data->violation)	/* recording a violation. */
378 		goto out;
379 
380 	cur_digest = event_data->iint->ima_hash->digest;
381 	cur_digestsize = event_data->iint->ima_hash->length;
382 
383 	hash_algo = event_data->iint->ima_hash->algo;
384 out:
385 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
386 					   hash_algo, field_data);
387 }
388 
389 /*
390  * This function writes the digest of the file which is expected to match the
391  * digest contained in the file's appended signature.
392  */
393 int ima_eventdigest_modsig_init(struct ima_event_data *event_data,
394 				struct ima_field_data *field_data)
395 {
396 	enum hash_algo hash_algo;
397 	const u8 *cur_digest;
398 	u32 cur_digestsize;
399 
400 	if (!event_data->modsig)
401 		return 0;
402 
403 	if (event_data->violation) {
404 		/* Recording a violation. */
405 		hash_algo = HASH_ALGO_SHA1;
406 		cur_digest = NULL;
407 		cur_digestsize = 0;
408 	} else {
409 		int rc;
410 
411 		rc = ima_get_modsig_digest(event_data->modsig, &hash_algo,
412 					   &cur_digest, &cur_digestsize);
413 		if (rc)
414 			return rc;
415 		else if (hash_algo == HASH_ALGO__LAST || cur_digestsize == 0)
416 			/* There was some error collecting the digest. */
417 			return -EINVAL;
418 	}
419 
420 	return ima_eventdigest_init_common(cur_digest, cur_digestsize,
421 					   hash_algo, field_data);
422 }
423 
424 static int ima_eventname_init_common(struct ima_event_data *event_data,
425 				     struct ima_field_data *field_data,
426 				     bool size_limit)
427 {
428 	const char *cur_filename = NULL;
429 	u32 cur_filename_len = 0;
430 
431 	BUG_ON(event_data->filename == NULL && event_data->file == NULL);
432 
433 	if (event_data->filename) {
434 		cur_filename = event_data->filename;
435 		cur_filename_len = strlen(event_data->filename);
436 
437 		if (!size_limit || cur_filename_len <= IMA_EVENT_NAME_LEN_MAX)
438 			goto out;
439 	}
440 
441 	if (event_data->file) {
442 		cur_filename = event_data->file->f_path.dentry->d_name.name;
443 		cur_filename_len = strlen(cur_filename);
444 	} else
445 		/*
446 		 * Truncate filename if the latter is too long and
447 		 * the file descriptor is not available.
448 		 */
449 		cur_filename_len = IMA_EVENT_NAME_LEN_MAX;
450 out:
451 	return ima_write_template_field_data(cur_filename, cur_filename_len,
452 					     DATA_FMT_STRING, field_data);
453 }
454 
455 /*
456  * This function writes the name of an event (with size limit).
457  */
458 int ima_eventname_init(struct ima_event_data *event_data,
459 		       struct ima_field_data *field_data)
460 {
461 	return ima_eventname_init_common(event_data, field_data, true);
462 }
463 
464 /*
465  * This function writes the name of an event (without size limit).
466  */
467 int ima_eventname_ng_init(struct ima_event_data *event_data,
468 			  struct ima_field_data *field_data)
469 {
470 	return ima_eventname_init_common(event_data, field_data, false);
471 }
472 
473 /*
474  *  ima_eventsig_init - include the file signature as part of the template data
475  */
476 int ima_eventsig_init(struct ima_event_data *event_data,
477 		      struct ima_field_data *field_data)
478 {
479 	struct evm_ima_xattr_data *xattr_value = event_data->xattr_value;
480 
481 	if ((!xattr_value) || (xattr_value->type != EVM_IMA_XATTR_DIGSIG))
482 		return ima_eventevmsig_init(event_data, field_data);
483 
484 	return ima_write_template_field_data(xattr_value, event_data->xattr_len,
485 					     DATA_FMT_HEX, field_data);
486 }
487 
488 /*
489  *  ima_eventbuf_init - include the buffer(kexec-cmldine) as part of the
490  *  template data.
491  */
492 int ima_eventbuf_init(struct ima_event_data *event_data,
493 		      struct ima_field_data *field_data)
494 {
495 	if ((!event_data->buf) || (event_data->buf_len == 0))
496 		return 0;
497 
498 	return ima_write_template_field_data(event_data->buf,
499 					     event_data->buf_len, DATA_FMT_HEX,
500 					     field_data);
501 }
502 
503 /*
504  *  ima_eventmodsig_init - include the appended file signature as part of the
505  *  template data
506  */
507 int ima_eventmodsig_init(struct ima_event_data *event_data,
508 			 struct ima_field_data *field_data)
509 {
510 	const void *data;
511 	u32 data_len;
512 	int rc;
513 
514 	if (!event_data->modsig)
515 		return 0;
516 
517 	/*
518 	 * modsig is a runtime structure containing pointers. Get its raw data
519 	 * instead.
520 	 */
521 	rc = ima_get_raw_modsig(event_data->modsig, &data, &data_len);
522 	if (rc)
523 		return rc;
524 
525 	return ima_write_template_field_data(data, data_len, DATA_FMT_HEX,
526 					     field_data);
527 }
528 
529 /*
530  *  ima_eventevmsig_init - include the EVM portable signature as part of the
531  *  template data
532  */
533 int ima_eventevmsig_init(struct ima_event_data *event_data,
534 			 struct ima_field_data *field_data)
535 {
536 	struct evm_ima_xattr_data *xattr_data = NULL;
537 	int rc = 0;
538 
539 	if (!event_data->file)
540 		return 0;
541 
542 	rc = vfs_getxattr_alloc(&init_user_ns, file_dentry(event_data->file),
543 				XATTR_NAME_EVM, (char **)&xattr_data, 0,
544 				GFP_NOFS);
545 	if (rc <= 0)
546 		return 0;
547 
548 	if (xattr_data->type != EVM_XATTR_PORTABLE_DIGSIG) {
549 		kfree(xattr_data);
550 		return 0;
551 	}
552 
553 	rc = ima_write_template_field_data((char *)xattr_data, rc, DATA_FMT_HEX,
554 					   field_data);
555 	kfree(xattr_data);
556 	return rc;
557 }
558 
559 static int ima_eventinodedac_init_common(struct ima_event_data *event_data,
560 					 struct ima_field_data *field_data,
561 					 bool get_uid)
562 {
563 	unsigned int id;
564 
565 	if (!event_data->file)
566 		return 0;
567 
568 	if (get_uid)
569 		id = i_uid_read(file_inode(event_data->file));
570 	else
571 		id = i_gid_read(file_inode(event_data->file));
572 
573 	if (ima_canonical_fmt) {
574 		if (sizeof(id) == sizeof(u16))
575 			id = (__force u16)cpu_to_le16(id);
576 		else
577 			id = (__force u32)cpu_to_le32(id);
578 	}
579 
580 	return ima_write_template_field_data((void *)&id, sizeof(id),
581 					     DATA_FMT_UINT, field_data);
582 }
583 
584 /*
585  *  ima_eventinodeuid_init - include the inode UID as part of the template
586  *  data
587  */
588 int ima_eventinodeuid_init(struct ima_event_data *event_data,
589 			   struct ima_field_data *field_data)
590 {
591 	return ima_eventinodedac_init_common(event_data, field_data, true);
592 }
593 
594 /*
595  *  ima_eventinodegid_init - include the inode GID as part of the template
596  *  data
597  */
598 int ima_eventinodegid_init(struct ima_event_data *event_data,
599 			   struct ima_field_data *field_data)
600 {
601 	return ima_eventinodedac_init_common(event_data, field_data, false);
602 }
603 
604 /*
605  *  ima_eventinodemode_init - include the inode mode as part of the template
606  *  data
607  */
608 int ima_eventinodemode_init(struct ima_event_data *event_data,
609 			    struct ima_field_data *field_data)
610 {
611 	struct inode *inode;
612 	u16 mode;
613 
614 	if (!event_data->file)
615 		return 0;
616 
617 	inode = file_inode(event_data->file);
618 	mode = inode->i_mode;
619 	if (ima_canonical_fmt)
620 		mode = (__force u16)cpu_to_le16(mode);
621 
622 	return ima_write_template_field_data((char *)&mode, sizeof(mode),
623 					     DATA_FMT_UINT, field_data);
624 }
625 
626 static int ima_eventinodexattrs_init_common(struct ima_event_data *event_data,
627 					    struct ima_field_data *field_data,
628 					    char type)
629 {
630 	u8 *buffer = NULL;
631 	int rc;
632 
633 	if (!event_data->file)
634 		return 0;
635 
636 	rc = evm_read_protected_xattrs(file_dentry(event_data->file), NULL, 0,
637 				       type, ima_canonical_fmt);
638 	if (rc < 0)
639 		return 0;
640 
641 	buffer = kmalloc(rc, GFP_KERNEL);
642 	if (!buffer)
643 		return 0;
644 
645 	rc = evm_read_protected_xattrs(file_dentry(event_data->file), buffer,
646 				       rc, type, ima_canonical_fmt);
647 	if (rc < 0) {
648 		rc = 0;
649 		goto out;
650 	}
651 
652 	rc = ima_write_template_field_data((char *)buffer, rc, DATA_FMT_HEX,
653 					   field_data);
654 out:
655 	kfree(buffer);
656 	return rc;
657 }
658 
659 /*
660  *  ima_eventinodexattrnames_init - include a list of xattr names as part of the
661  *  template data
662  */
663 int ima_eventinodexattrnames_init(struct ima_event_data *event_data,
664 				  struct ima_field_data *field_data)
665 {
666 	return ima_eventinodexattrs_init_common(event_data, field_data, 'n');
667 }
668 
669 /*
670  *  ima_eventinodexattrlengths_init - include a list of xattr lengths as part of
671  *  the template data
672  */
673 int ima_eventinodexattrlengths_init(struct ima_event_data *event_data,
674 				    struct ima_field_data *field_data)
675 {
676 	return ima_eventinodexattrs_init_common(event_data, field_data, 'l');
677 }
678 
679 /*
680  *  ima_eventinodexattrvalues_init - include a list of xattr values as part of
681  *  the template data
682  */
683 int ima_eventinodexattrvalues_init(struct ima_event_data *event_data,
684 				   struct ima_field_data *field_data)
685 {
686 	return ima_eventinodexattrs_init_common(event_data, field_data, 'v');
687 }
688