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.c
9  *      Helpers to manage template descriptors.
10  */
11 
12 #include <linux/rculist.h>
13 #include "ima.h"
14 #include "ima_template_lib.h"
15 
16 enum header_fields { HDR_PCR, HDR_DIGEST, HDR_TEMPLATE_NAME,
17 		     HDR_TEMPLATE_DATA, HDR__LAST };
18 
19 static struct ima_template_desc builtin_templates[] = {
20 	{.name = IMA_TEMPLATE_IMA_NAME, .fmt = IMA_TEMPLATE_IMA_FMT},
21 	{.name = "ima-ng", .fmt = "d-ng|n-ng"},
22 	{.name = "ima-sig", .fmt = "d-ng|n-ng|sig"},
23 	{.name = "ima-buf", .fmt = "d-ng|n-ng|buf"},
24 	{.name = "ima-modsig", .fmt = "d-ng|n-ng|sig|d-modsig|modsig"},
25 	{.name = "", .fmt = ""},	/* placeholder for a custom format */
26 };
27 
28 static LIST_HEAD(defined_templates);
29 static DEFINE_SPINLOCK(template_list);
30 
31 static const struct ima_template_field supported_fields[] = {
32 	{.field_id = "d", .field_init = ima_eventdigest_init,
33 	 .field_show = ima_show_template_digest},
34 	{.field_id = "n", .field_init = ima_eventname_init,
35 	 .field_show = ima_show_template_string},
36 	{.field_id = "d-ng", .field_init = ima_eventdigest_ng_init,
37 	 .field_show = ima_show_template_digest_ng},
38 	{.field_id = "n-ng", .field_init = ima_eventname_ng_init,
39 	 .field_show = ima_show_template_string},
40 	{.field_id = "sig", .field_init = ima_eventsig_init,
41 	 .field_show = ima_show_template_sig},
42 	{.field_id = "buf", .field_init = ima_eventbuf_init,
43 	 .field_show = ima_show_template_buf},
44 	{.field_id = "d-modsig", .field_init = ima_eventdigest_modsig_init,
45 	 .field_show = ima_show_template_digest_ng},
46 	{.field_id = "modsig", .field_init = ima_eventmodsig_init,
47 	 .field_show = ima_show_template_sig},
48 };
49 
50 /*
51  * Used when restoring measurements carried over from a kexec. 'd' and 'n' don't
52  * need to be accounted for since they shouldn't be defined in the same template
53  * description as 'd-ng' and 'n-ng' respectively.
54  */
55 #define MAX_TEMPLATE_NAME_LEN sizeof("d-ng|n-ng|sig|buf|d-modisg|modsig")
56 
57 static struct ima_template_desc *ima_template;
58 
59 /**
60  * ima_template_has_modsig - Check whether template has modsig-related fields.
61  * @ima_template: IMA template to check.
62  *
63  * Tells whether the given template has fields referencing a file's appended
64  * signature.
65  */
66 bool ima_template_has_modsig(const struct ima_template_desc *ima_template)
67 {
68 	int i;
69 
70 	for (i = 0; i < ima_template->num_fields; i++)
71 		if (!strcmp(ima_template->fields[i]->field_id, "modsig") ||
72 		    !strcmp(ima_template->fields[i]->field_id, "d-modsig"))
73 			return true;
74 
75 	return false;
76 }
77 
78 static int __init ima_template_setup(char *str)
79 {
80 	struct ima_template_desc *template_desc;
81 	int template_len = strlen(str);
82 
83 	if (ima_template)
84 		return 1;
85 
86 	ima_init_template_list();
87 
88 	/*
89 	 * Verify that a template with the supplied name exists.
90 	 * If not, use CONFIG_IMA_DEFAULT_TEMPLATE.
91 	 */
92 	template_desc = lookup_template_desc(str);
93 	if (!template_desc) {
94 		pr_err("template %s not found, using %s\n",
95 		       str, CONFIG_IMA_DEFAULT_TEMPLATE);
96 		return 1;
97 	}
98 
99 	/*
100 	 * Verify whether the current hash algorithm is supported
101 	 * by the 'ima' template.
102 	 */
103 	if (template_len == 3 && strcmp(str, IMA_TEMPLATE_IMA_NAME) == 0 &&
104 	    ima_hash_algo != HASH_ALGO_SHA1 && ima_hash_algo != HASH_ALGO_MD5) {
105 		pr_err("template does not support hash alg\n");
106 		return 1;
107 	}
108 
109 	ima_template = template_desc;
110 	return 1;
111 }
112 __setup("ima_template=", ima_template_setup);
113 
114 static int __init ima_template_fmt_setup(char *str)
115 {
116 	int num_templates = ARRAY_SIZE(builtin_templates);
117 
118 	if (ima_template)
119 		return 1;
120 
121 	if (template_desc_init_fields(str, NULL, NULL) < 0) {
122 		pr_err("format string '%s' not valid, using template %s\n",
123 		       str, CONFIG_IMA_DEFAULT_TEMPLATE);
124 		return 1;
125 	}
126 
127 	builtin_templates[num_templates - 1].fmt = str;
128 	ima_template = builtin_templates + num_templates - 1;
129 
130 	return 1;
131 }
132 __setup("ima_template_fmt=", ima_template_fmt_setup);
133 
134 struct ima_template_desc *lookup_template_desc(const char *name)
135 {
136 	struct ima_template_desc *template_desc;
137 	int found = 0;
138 
139 	rcu_read_lock();
140 	list_for_each_entry_rcu(template_desc, &defined_templates, list) {
141 		if ((strcmp(template_desc->name, name) == 0) ||
142 		    (strcmp(template_desc->fmt, name) == 0)) {
143 			found = 1;
144 			break;
145 		}
146 	}
147 	rcu_read_unlock();
148 	return found ? template_desc : NULL;
149 }
150 
151 static const struct ima_template_field *
152 lookup_template_field(const char *field_id)
153 {
154 	int i;
155 
156 	for (i = 0; i < ARRAY_SIZE(supported_fields); i++)
157 		if (strncmp(supported_fields[i].field_id, field_id,
158 			    IMA_TEMPLATE_FIELD_ID_MAX_LEN) == 0)
159 			return &supported_fields[i];
160 	return NULL;
161 }
162 
163 static int template_fmt_size(const char *template_fmt)
164 {
165 	char c;
166 	int template_fmt_len = strlen(template_fmt);
167 	int i = 0, j = 0;
168 
169 	while (i < template_fmt_len) {
170 		c = template_fmt[i];
171 		if (c == '|')
172 			j++;
173 		i++;
174 	}
175 
176 	return j + 1;
177 }
178 
179 int template_desc_init_fields(const char *template_fmt,
180 			      const struct ima_template_field ***fields,
181 			      int *num_fields)
182 {
183 	const char *template_fmt_ptr;
184 	const struct ima_template_field *found_fields[IMA_TEMPLATE_NUM_FIELDS_MAX];
185 	int template_num_fields;
186 	int i, len;
187 
188 	if (num_fields && *num_fields > 0) /* already initialized? */
189 		return 0;
190 
191 	template_num_fields = template_fmt_size(template_fmt);
192 
193 	if (template_num_fields > IMA_TEMPLATE_NUM_FIELDS_MAX) {
194 		pr_err("format string '%s' contains too many fields\n",
195 		       template_fmt);
196 		return -EINVAL;
197 	}
198 
199 	for (i = 0, template_fmt_ptr = template_fmt; i < template_num_fields;
200 	     i++, template_fmt_ptr += len + 1) {
201 		char tmp_field_id[IMA_TEMPLATE_FIELD_ID_MAX_LEN + 1];
202 
203 		len = strchrnul(template_fmt_ptr, '|') - template_fmt_ptr;
204 		if (len == 0 || len > IMA_TEMPLATE_FIELD_ID_MAX_LEN) {
205 			pr_err("Invalid field with length %d\n", len);
206 			return -EINVAL;
207 		}
208 
209 		memcpy(tmp_field_id, template_fmt_ptr, len);
210 		tmp_field_id[len] = '\0';
211 		found_fields[i] = lookup_template_field(tmp_field_id);
212 		if (!found_fields[i]) {
213 			pr_err("field '%s' not found\n", tmp_field_id);
214 			return -ENOENT;
215 		}
216 	}
217 
218 	if (fields && num_fields) {
219 		*fields = kmalloc_array(i, sizeof(*fields), GFP_KERNEL);
220 		if (*fields == NULL)
221 			return -ENOMEM;
222 
223 		memcpy(*fields, found_fields, i * sizeof(*fields));
224 		*num_fields = i;
225 	}
226 
227 	return 0;
228 }
229 
230 void ima_init_template_list(void)
231 {
232 	int i;
233 
234 	if (!list_empty(&defined_templates))
235 		return;
236 
237 	spin_lock(&template_list);
238 	for (i = 0; i < ARRAY_SIZE(builtin_templates); i++) {
239 		list_add_tail_rcu(&builtin_templates[i].list,
240 				  &defined_templates);
241 	}
242 	spin_unlock(&template_list);
243 }
244 
245 struct ima_template_desc *ima_template_desc_current(void)
246 {
247 	if (!ima_template) {
248 		ima_init_template_list();
249 		ima_template =
250 		    lookup_template_desc(CONFIG_IMA_DEFAULT_TEMPLATE);
251 	}
252 	return ima_template;
253 }
254 
255 int __init ima_init_template(void)
256 {
257 	struct ima_template_desc *template = ima_template_desc_current();
258 	int result;
259 
260 	result = template_desc_init_fields(template->fmt,
261 					   &(template->fields),
262 					   &(template->num_fields));
263 	if (result < 0)
264 		pr_err("template %s init failed, result: %d\n",
265 		       (strlen(template->name) ?
266 		       template->name : template->fmt), result);
267 
268 	return result;
269 }
270 
271 static struct ima_template_desc *restore_template_fmt(char *template_name)
272 {
273 	struct ima_template_desc *template_desc = NULL;
274 	int ret;
275 
276 	ret = template_desc_init_fields(template_name, NULL, NULL);
277 	if (ret < 0) {
278 		pr_err("attempting to initialize the template \"%s\" failed\n",
279 			template_name);
280 		goto out;
281 	}
282 
283 	template_desc = kzalloc(sizeof(*template_desc), GFP_KERNEL);
284 	if (!template_desc)
285 		goto out;
286 
287 	template_desc->name = "";
288 	template_desc->fmt = kstrdup(template_name, GFP_KERNEL);
289 	if (!template_desc->fmt)
290 		goto out;
291 
292 	spin_lock(&template_list);
293 	list_add_tail_rcu(&template_desc->list, &defined_templates);
294 	spin_unlock(&template_list);
295 out:
296 	return template_desc;
297 }
298 
299 static int ima_restore_template_data(struct ima_template_desc *template_desc,
300 				     void *template_data,
301 				     int template_data_size,
302 				     struct ima_template_entry **entry)
303 {
304 	struct tpm_digest *digests;
305 	int ret = 0;
306 	int i;
307 
308 	*entry = kzalloc(struct_size(*entry, template_data,
309 				     template_desc->num_fields), GFP_NOFS);
310 	if (!*entry)
311 		return -ENOMEM;
312 
313 	digests = kcalloc(NR_BANKS(ima_tpm_chip) + ima_extra_slots,
314 			  sizeof(*digests), GFP_NOFS);
315 	if (!digests) {
316 		kfree(*entry);
317 		return -ENOMEM;
318 	}
319 
320 	(*entry)->digests = digests;
321 
322 	ret = ima_parse_buf(template_data, template_data + template_data_size,
323 			    NULL, template_desc->num_fields,
324 			    (*entry)->template_data, NULL, NULL,
325 			    ENFORCE_FIELDS | ENFORCE_BUFEND, "template data");
326 	if (ret < 0) {
327 		kfree((*entry)->digests);
328 		kfree(*entry);
329 		return ret;
330 	}
331 
332 	(*entry)->template_desc = template_desc;
333 	for (i = 0; i < template_desc->num_fields; i++) {
334 		struct ima_field_data *field_data = &(*entry)->template_data[i];
335 		u8 *data = field_data->data;
336 
337 		(*entry)->template_data[i].data =
338 			kzalloc(field_data->len + 1, GFP_KERNEL);
339 		if (!(*entry)->template_data[i].data) {
340 			ret = -ENOMEM;
341 			break;
342 		}
343 		memcpy((*entry)->template_data[i].data, data, field_data->len);
344 		(*entry)->template_data_len += sizeof(field_data->len);
345 		(*entry)->template_data_len += field_data->len;
346 	}
347 
348 	if (ret < 0) {
349 		ima_free_template_entry(*entry);
350 		*entry = NULL;
351 	}
352 
353 	return ret;
354 }
355 
356 /* Restore the serialized binary measurement list without extending PCRs. */
357 int ima_restore_measurement_list(loff_t size, void *buf)
358 {
359 	char template_name[MAX_TEMPLATE_NAME_LEN];
360 	unsigned char zero[TPM_DIGEST_SIZE] = { 0 };
361 
362 	struct ima_kexec_hdr *khdr = buf;
363 	struct ima_field_data hdr[HDR__LAST] = {
364 		[HDR_PCR] = {.len = sizeof(u32)},
365 		[HDR_DIGEST] = {.len = TPM_DIGEST_SIZE},
366 	};
367 
368 	void *bufp = buf + sizeof(*khdr);
369 	void *bufendp;
370 	struct ima_template_entry *entry;
371 	struct ima_template_desc *template_desc;
372 	DECLARE_BITMAP(hdr_mask, HDR__LAST);
373 	unsigned long count = 0;
374 	int ret = 0;
375 
376 	if (!buf || size < sizeof(*khdr))
377 		return 0;
378 
379 	if (ima_canonical_fmt) {
380 		khdr->version = le16_to_cpu(khdr->version);
381 		khdr->count = le64_to_cpu(khdr->count);
382 		khdr->buffer_size = le64_to_cpu(khdr->buffer_size);
383 	}
384 
385 	if (khdr->version != 1) {
386 		pr_err("attempting to restore a incompatible measurement list");
387 		return -EINVAL;
388 	}
389 
390 	if (khdr->count > ULONG_MAX - 1) {
391 		pr_err("attempting to restore too many measurements");
392 		return -EINVAL;
393 	}
394 
395 	bitmap_zero(hdr_mask, HDR__LAST);
396 	bitmap_set(hdr_mask, HDR_PCR, 1);
397 	bitmap_set(hdr_mask, HDR_DIGEST, 1);
398 
399 	/*
400 	 * ima kexec buffer prefix: version, buffer size, count
401 	 * v1 format: pcr, digest, template-name-len, template-name,
402 	 *	      template-data-size, template-data
403 	 */
404 	bufendp = buf + khdr->buffer_size;
405 	while ((bufp < bufendp) && (count++ < khdr->count)) {
406 		int enforce_mask = ENFORCE_FIELDS;
407 
408 		enforce_mask |= (count == khdr->count) ? ENFORCE_BUFEND : 0;
409 		ret = ima_parse_buf(bufp, bufendp, &bufp, HDR__LAST, hdr, NULL,
410 				    hdr_mask, enforce_mask, "entry header");
411 		if (ret < 0)
412 			break;
413 
414 		if (hdr[HDR_TEMPLATE_NAME].len >= MAX_TEMPLATE_NAME_LEN) {
415 			pr_err("attempting to restore a template name that is too long\n");
416 			ret = -EINVAL;
417 			break;
418 		}
419 
420 		/* template name is not null terminated */
421 		memcpy(template_name, hdr[HDR_TEMPLATE_NAME].data,
422 		       hdr[HDR_TEMPLATE_NAME].len);
423 		template_name[hdr[HDR_TEMPLATE_NAME].len] = 0;
424 
425 		if (strcmp(template_name, "ima") == 0) {
426 			pr_err("attempting to restore an unsupported template \"%s\" failed\n",
427 			       template_name);
428 			ret = -EINVAL;
429 			break;
430 		}
431 
432 		template_desc = lookup_template_desc(template_name);
433 		if (!template_desc) {
434 			template_desc = restore_template_fmt(template_name);
435 			if (!template_desc)
436 				break;
437 		}
438 
439 		/*
440 		 * Only the running system's template format is initialized
441 		 * on boot.  As needed, initialize the other template formats.
442 		 */
443 		ret = template_desc_init_fields(template_desc->fmt,
444 						&(template_desc->fields),
445 						&(template_desc->num_fields));
446 		if (ret < 0) {
447 			pr_err("attempting to restore the template fmt \"%s\" failed\n",
448 			       template_desc->fmt);
449 			ret = -EINVAL;
450 			break;
451 		}
452 
453 		ret = ima_restore_template_data(template_desc,
454 						hdr[HDR_TEMPLATE_DATA].data,
455 						hdr[HDR_TEMPLATE_DATA].len,
456 						&entry);
457 		if (ret < 0)
458 			break;
459 
460 		if (memcmp(hdr[HDR_DIGEST].data, zero, sizeof(zero))) {
461 			ret = ima_calc_field_array_hash(
462 						&entry->template_data[0],
463 						entry);
464 			if (ret < 0) {
465 				pr_err("cannot calculate template digest\n");
466 				ret = -EINVAL;
467 				break;
468 			}
469 		}
470 
471 		entry->pcr = !ima_canonical_fmt ? *(hdr[HDR_PCR].data) :
472 			     le32_to_cpu(*(hdr[HDR_PCR].data));
473 		ret = ima_restore_measurement_entry(entry);
474 		if (ret < 0)
475 			break;
476 
477 	}
478 	return ret;
479 }
480