• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2021 Google LLC
4  * Author: Ard Biesheuvel <ardb@google.com>
5  *
6  * This file is the core of fips140.ko, which contains various crypto algorithms
7  * that are also built into vmlinux.  At load time, this module overrides the
8  * built-in implementations of these algorithms with its implementations.  It
9  * also runs self-tests on these algorithms and verifies the integrity of its
10  * code and data.  If either of these steps fails, the kernel will panic.
11  *
12  * This module is intended to be loaded at early boot time in order to meet
13  * FIPS 140 and NIAP FPT_TST_EXT.1 requirements.  It shouldn't be used if you
14  * don't need to meet these requirements.
15  */
16 
17 /*
18  * Since this .c file is the real entry point of fips140.ko, it needs to be
19  * compiled normally, so undo the hacks that were done in fips140-defs.h.
20  */
21 #define MODULE
22 #undef KBUILD_MODFILE
23 #undef __DISABLE_EXPORTS
24 
25 #include <linux/ctype.h>
26 #include <linux/debugfs.h>
27 #include <linux/module.h>
28 #include <crypto/aead.h>
29 #include <crypto/aes.h>
30 #include <crypto/hash.h>
31 #include <crypto/sha2.h>
32 #include <crypto/skcipher.h>
33 #include <crypto/rng.h>
34 #include <trace/hooks/fips140.h>
35 
36 #include "fips140-module.h"
37 #include "internal.h"
38 
39 /*
40  * FIPS 140-2 prefers the use of HMAC with a public key over a plain hash.
41  */
42 u8 __initdata fips140_integ_hmac_key[] = "The quick brown fox jumps over the lazy dog";
43 
44 /* this is populated by the build tool */
45 u8 __initdata fips140_integ_hmac_digest[SHA256_DIGEST_SIZE];
46 
47 const initcall_entry_t __fips140_initcalls_start __section(".initcalls._start");
48 const initcall_entry_t __fips140_initcalls_end __section(".initcalls._end");
49 
50 const u8 __fips140_text_start __section(".text.._start");
51 const u8 __fips140_text_end __section(".text.._end");
52 
53 const u8 __fips140_rodata_start __section(".rodata.._start");
54 const u8 __fips140_rodata_end __section(".rodata.._end");
55 
56 /*
57  * We need this little detour to prevent Clang from detecting out of bounds
58  * accesses to the above *_start symbols, which exist only to delineate the
59  * corresponding sections, and so their sizes are not relevant to us.
60  */
61 const initcall_entry_t *fips140_initcalls_start = &__fips140_initcalls_start;
62 const u8 *fips140_text_start = &__fips140_text_start;
63 const u8 *fips140_rodata_start = &__fips140_rodata_start;
64 
65 /*
66  * fips140_algs[] lists the algorithms that this module unregisters from the
67  * kernel crypto API so that it can register its own implementation(s) of them.
68  *
69  * There are two reasons to do the unregistration, i.e. replace the kernel's
70  * algorithms instead of just adding more algorithms.  First, the kernel crypto
71  * API doesn't allow algorithms with duplicate driver names.  Second, for FIPS
72  * approved algorithms we have to ensure that the FIPS copies are actually used.
73  */
74 static struct fips140_alg {
75 	/*
76 	 * Either cra_name or cra_driver_name is set.
77 	 *
78 	 * cra_name makes the entry match all software implementations of a
79 	 * given algorithm.  This is used when the module is meant to replace
80 	 * *all* software implementations of the algorithm.  This is required
81 	 * for FIPS approved algorithms (approved=true).  When using this style
82 	 * of matching, it must be ensured that the module contains all the same
83 	 * implementations of the algorithm as the kernel itself; otherwise the
84 	 * kernel's functionality and/or performance could be impacted by the
85 	 * insertion of the fips140 module.
86 	 *
87 	 * cra_driver_name makes the entry match a single implementation of an
88 	 * algorithm.  This is used for some specific non FIPS approved
89 	 * algorithm implementations that get pulled in by being located in the
90 	 * same source files as implementations of FIPS approved algorithms.
91 	 */
92 	const char *cra_name;
93 	const char *cra_driver_name;
94 
95 	/*
96 	 * approved is true if fips140_is_approved_service() should return that
97 	 * the algorithm is approved.  This requires cra_name != NULL.
98 	 */
99 	bool approved;
100 
101 	/*
102 	 * maybe_uninstantiated is true if the module provides this algorithm
103 	 * but doesn't register it directly at module initialization time.  This
104 	 * occurs for some of the HMAC variants because they are provided by a
105 	 * template which isn't immediately instantiated for every SHA variant
106 	 * (since the HMAC self-test only has to test one SHA variant).
107 	 */
108 	bool maybe_uninstantiated;
109 
110 	/*
111 	 * unregistered_inkern gets set to true at runtime if at least one
112 	 * algorithm matching this entry was unregistered from the kernel.  This
113 	 * is used to detect unregistrations with no matching registration.
114 	 */
115 	bool unregistered_inkern;
116 } fips140_algs[] = {
117 	/* Approved algorithms, all specified by cra_name */
118 	{ .cra_name = "aes", .approved = true },
119 	{ .cra_name = "cbc(aes)", .approved = true },
120 	{ .cra_name = "cmac(aes)", .approved = true },
121 	{ .cra_name = "ctr(aes)", .approved = true },
122 	{ .cra_name = "cts(cbc(aes))", .approved = true },
123 	{ .cra_name = "ecb(aes)", .approved = true },
124 	{ .cra_name = "hmac(sha1)", .approved = true,
125 	  .maybe_uninstantiated = true },
126 	{ .cra_name = "hmac(sha224)", .approved = true,
127 	  .maybe_uninstantiated = true },
128 	{ .cra_name = "hmac(sha256)", .approved = true },
129 	{ .cra_name = "hmac(sha384)", .approved = true,
130 	  .maybe_uninstantiated = true },
131 	{ .cra_name = "hmac(sha512)", .approved = true,
132 	  .maybe_uninstantiated = true },
133 	{ .cra_name = "sha1", .approved = true },
134 	{ .cra_name = "sha224", .approved = true },
135 	{ .cra_name = "sha256", .approved = true },
136 	{ .cra_name = "sha384", .approved = true },
137 	{ .cra_name = "sha512", .approved = true },
138 	{ .cra_name = "sha3-224", .approved = true },
139 	{ .cra_name = "sha3-256", .approved = true },
140 	{ .cra_name = "sha3-384", .approved = true },
141 	{ .cra_name = "sha3-512", .approved = true },
142 	{ .cra_name = "stdrng", .approved = true },
143 	{ .cra_name = "xts(aes)", .approved = true },
144 
145 	/*
146 	 * Non-approved algorithms specified by cra_name.
147 	 *
148 	 * Due to a quirk in the FIPS requirements, AES-GCM can't be FIPS
149 	 * approved.  But we treat it the same as approved algorithms in that we
150 	 * ensure that a self-test and all needed implementations are included.
151 	 *
152 	 * The Jitter RNG is needed in the module as an entropy source for the
153 	 * DRBG algorithms, but it's not considered to be approved itself.
154 	 */
155 	{ .cra_name = "gcm(aes)" },
156 	{ .cra_name = "jitterentropy_rng" },
157 
158 	/* Non-approved algorithms specified by cra_driver_name */
159 	{ .cra_driver_name = "essiv-cbc-aes-sha256-ce" },
160 	{ .cra_driver_name = "essiv-cbc-aes-sha256-neon" },
161 	{ .cra_driver_name = "cbcmac-aes-ce" },
162 	{ .cra_driver_name = "cbcmac-aes-neon" },
163 	{ .cra_driver_name = "rfc4106-gcm-aes-ce" },
164 	{ .cra_driver_name = "xcbc-aes-ce" },
165 	{ .cra_driver_name = "xcbc-aes-neon" },
166 	{ .cra_driver_name = "xctr-aes-ce" },
167 	{ .cra_driver_name = "xctr-aes-neon" },
168 };
169 
170 /*
171  * Return true if the crypto API algorithm @calg is matched by the fips140
172  * module algorithm specification @falg.
173  */
fips140_alg_matches(const struct fips140_alg * falg,const struct crypto_alg * calg)174 static bool __init fips140_alg_matches(const struct fips140_alg *falg,
175 				       const struct crypto_alg *calg)
176 {
177 	/*
178 	 * All software algorithms are synchronous.  Hardware algorithms must be
179 	 * covered by their own FIPS 140 certification.
180 	 */
181 	if (calg->cra_flags & CRYPTO_ALG_ASYNC)
182 		return false;
183 
184 	if (falg->cra_name != NULL &&
185 	    strcmp(falg->cra_name, calg->cra_name) == 0)
186 		return true;
187 
188 	if (falg->cra_driver_name != NULL &&
189 	    strcmp(falg->cra_driver_name, calg->cra_driver_name) == 0)
190 		return true;
191 
192 	return false;
193 }
194 
195 /* Find the entry in fips140_algs[], if any, that @calg is matched by. */
196 static struct fips140_alg *__init
fips140_find_matching_alg(const struct crypto_alg * calg)197 fips140_find_matching_alg(const struct crypto_alg *calg)
198 {
199 	size_t i;
200 
201 	for (i = 0; i < ARRAY_SIZE(fips140_algs); i++) {
202 		if (fips140_alg_matches(&fips140_algs[i], calg))
203 			return &fips140_algs[i];
204 	}
205 	return NULL;
206 }
207 
208 /*
209  * FIPS 140-3 service indicators.  FIPS 140-3 requires that all services
210  * "provide an indicator when the service utilises an approved cryptographic
211  * algorithm, security function or process in an approved manner".  What this
212  * means is very debatable, even with the help of the FIPS 140-3 Implementation
213  * Guidance document.  However, it was decided that a function that takes in an
214  * algorithm name and returns whether that algorithm is approved or not will
215  * meet this requirement.  Note, this relies on some properties of the module:
216  *
217  *   - The module doesn't distinguish between "services" and "algorithms"; its
218  *     services are simply its algorithms.
219  *
220  *   - The status of an approved algorithm is never non-approved, since (a) the
221  *     module doesn't support operating in a non-approved mode, such as a mode
222  *     where the self-tests are skipped; (b) there are no cases where the module
223  *     supports non-approved settings for approved algorithms, e.g.
224  *     non-approved key sizes; and (c) this function isn't available to be
225  *     called until the module_init function has completed, so it's guaranteed
226  *     that the self-tests and integrity check have already passed.
227  *
228  *   - The module does support some non-approved algorithms, so a single static
229  *     indicator ("return true;") would not be acceptable.
230  */
fips140_is_approved_service(const char * name)231 bool fips140_is_approved_service(const char *name)
232 {
233 	size_t i;
234 
235 	for (i = 0; i < ARRAY_SIZE(fips140_algs); i++) {
236 		if (fips140_algs[i].approved &&
237 		    fips140_algs[i].cra_name != NULL &&
238 		    strcmp(name, fips140_algs[i].cra_name) == 0)
239 			return true;
240 	}
241 	return false;
242 }
243 EXPORT_SYMBOL_GPL(fips140_is_approved_service);
244 
245 /*
246  * FIPS 140-3 requires that modules provide a "service" that outputs "the name
247  * or module identifier and the versioning information that can be correlated
248  * with a validation record".  This function meets that requirement.
249  *
250  * Note: the module also prints this same information to the kernel log when it
251  * is loaded.  That might meet the requirement by itself.  However, given the
252  * vagueness of what counts as a "service", we provide this function too, just
253  * in case the certification lab or CMVP is happier with an explicit function.
254  *
255  * Note: /sys/modules/fips140/scmversion also provides versioning information
256  * about the module.  However that file just shows the bare git commit ID, so it
257  * probably isn't sufficient to meet the FIPS requirement, which seems to want
258  * the "official" module name and version number used in the FIPS certificate.
259  */
fips140_module_version(void)260 const char *fips140_module_version(void)
261 {
262 	return FIPS140_MODULE_NAME " " FIPS140_MODULE_VERSION;
263 }
264 EXPORT_SYMBOL_GPL(fips140_module_version);
265 
266 static LIST_HEAD(existing_live_algos);
267 
268 /*
269  * Release a list of algorithms which have been removed from crypto_alg_list.
270  *
271  * Note that even though the list is a private list, we have to hold
272  * crypto_alg_sem while iterating through it because crypto_unregister_alg() may
273  * run concurrently (as we haven't taken a reference to the algorithms on the
274  * list), and crypto_unregister_alg() will remove the algorithm from whichever
275  * list it happens to be on, while holding crypto_alg_sem.  That's okay, since
276  * in that case crypto_unregister_alg() will handle the crypto_alg_put().
277  */
fips140_remove_final(struct list_head * list)278 static void fips140_remove_final(struct list_head *list)
279 {
280 	struct crypto_alg *alg;
281 	struct crypto_alg *n;
282 
283 	/*
284 	 * We need to take crypto_alg_sem to safely traverse the list (see
285 	 * comment above), but we have to drop it when doing each
286 	 * crypto_alg_put() as that may take crypto_alg_sem again.
287 	 */
288 	down_write(&crypto_alg_sem);
289 	list_for_each_entry_safe(alg, n, list, cra_list) {
290 		list_del_init(&alg->cra_list);
291 		up_write(&crypto_alg_sem);
292 
293 		crypto_alg_put(alg);
294 
295 		down_write(&crypto_alg_sem);
296 	}
297 	up_write(&crypto_alg_sem);
298 }
299 
unregister_existing_fips140_algos(void)300 static void __init unregister_existing_fips140_algos(void)
301 {
302 	struct crypto_alg *calg, *tmp;
303 	LIST_HEAD(remove_list);
304 	LIST_HEAD(spawns);
305 
306 	down_write(&crypto_alg_sem);
307 
308 	/*
309 	 * Find all registered algorithms that we care about, and move them to a
310 	 * private list so that they are no longer exposed via the algo lookup
311 	 * API. Subsequently, we will unregister them if they are not in active
312 	 * use. If they are, we can't fully unregister them but we can ensure
313 	 * that new users won't use them.
314 	 */
315 	list_for_each_entry_safe(calg, tmp, &crypto_alg_list, cra_list) {
316 		struct fips140_alg *falg = fips140_find_matching_alg(calg);
317 
318 		if (!falg)
319 			continue;
320 		falg->unregistered_inkern = true;
321 
322 		if (refcount_read(&calg->cra_refcnt) == 1) {
323 			/*
324 			 * This algorithm is not currently in use, but there may
325 			 * be template instances holding references to it via
326 			 * spawns. So let's tear it down like
327 			 * crypto_unregister_alg() would, but without releasing
328 			 * the lock, to prevent races with concurrent TFM
329 			 * allocations.
330 			 */
331 			calg->cra_flags |= CRYPTO_ALG_DEAD;
332 			list_move(&calg->cra_list, &remove_list);
333 			crypto_remove_spawns(calg, &spawns, NULL);
334 		} else {
335 			/*
336 			 * This algorithm is live, i.e. it has TFMs allocated,
337 			 * so we can't fully unregister it.  It's not necessary
338 			 * to dynamically redirect existing users to the FIPS
339 			 * code, given that they can't be relying on FIPS
340 			 * certified crypto in the first place.  However, we do
341 			 * need to ensure that new users will get the FIPS code.
342 			 *
343 			 * In most cases, setting calg->cra_priority to 0
344 			 * achieves this.  However, that isn't enough for
345 			 * algorithms like "hmac(sha256)" that need to be
346 			 * instantiated from a template, since existing
347 			 * algorithms always take priority over a template being
348 			 * instantiated.  Therefore, we move the algorithm to
349 			 * a private list so that algorithm lookups won't find
350 			 * it anymore.  To further distinguish it from the FIPS
351 			 * algorithms, we also append "+orig" to its name.
352 			 */
353 			pr_info("found already-live algorithm '%s' ('%s')\n",
354 				calg->cra_name, calg->cra_driver_name);
355 			calg->cra_priority = 0;
356 			strlcat(calg->cra_name, "+orig", CRYPTO_MAX_ALG_NAME);
357 			strlcat(calg->cra_driver_name, "+orig",
358 				CRYPTO_MAX_ALG_NAME);
359 			list_move(&calg->cra_list, &existing_live_algos);
360 		}
361 	}
362 	up_write(&crypto_alg_sem);
363 
364 	fips140_remove_final(&remove_list);
365 	fips140_remove_final(&spawns);
366 }
367 
368 /*
369  * The algorithms unregistered by fips140.ko are determined by fips140_algs[],
370  * but the algorithms registered by fips140.ko are determined by its initcalls.
371  * There is a chance these get out of sync.  Therefore, this function detects
372  * cases where an algorithm was unregistered without a replacement being
373  * registered.  It returns true if things look ok or false if there's a problem.
374  */
fips140_verify_no_extra_unregistrations(void)375 static bool __init fips140_verify_no_extra_unregistrations(void)
376 {
377 	bool ok = true;
378 	size_t i;
379 
380 	down_read(&crypto_alg_sem);
381 	for (i = 0; i < ARRAY_SIZE(fips140_algs); i++) {
382 		const struct fips140_alg *falg = &fips140_algs[i];
383 		const struct crypto_alg *calg;
384 		bool registered = false;
385 
386 		if (falg->maybe_uninstantiated || !falg->unregistered_inkern)
387 			continue;
388 
389 		list_for_each_entry(calg, &crypto_alg_list, cra_list) {
390 			if (fips140_alg_matches(falg, calg)) {
391 				registered = true;
392 				break;
393 			}
394 		}
395 		if (!registered) {
396 			pr_err("This module unregistered %s but did not replace it!\n",
397 			       falg->cra_name ?: falg->cra_driver_name);
398 			pr_err("Either remove it from fips140_algs[], or fix the module to include it.\n");
399 			ok = false;
400 		}
401 	}
402 	up_read(&crypto_alg_sem);
403 	return ok;
404 }
405 
unapply_text_relocations(void * section,int section_size,const Elf64_Rela * rela,int numrels)406 static void __init unapply_text_relocations(void *section, int section_size,
407 					    const Elf64_Rela *rela, int numrels)
408 {
409 	while (numrels--) {
410 		u32 *place = (u32 *)(section + rela->r_offset);
411 
412 		BUG_ON(rela->r_offset >= section_size);
413 
414 		switch (ELF64_R_TYPE(rela->r_info)) {
415 #ifdef CONFIG_ARM64
416 		case R_AARCH64_ABS32: /* for KCFI */
417 			*place = 0;
418 			break;
419 
420 		case R_AARCH64_JUMP26:
421 		case R_AARCH64_CALL26:
422 			*place &= ~GENMASK(25, 0);
423 			break;
424 
425 		case R_AARCH64_ADR_PREL_LO21:
426 		case R_AARCH64_ADR_PREL_PG_HI21:
427 		case R_AARCH64_ADR_PREL_PG_HI21_NC:
428 			*place &= ~(GENMASK(30, 29) | GENMASK(23, 5));
429 			break;
430 
431 		case R_AARCH64_ADD_ABS_LO12_NC:
432 		case R_AARCH64_LDST8_ABS_LO12_NC:
433 		case R_AARCH64_LDST16_ABS_LO12_NC:
434 		case R_AARCH64_LDST32_ABS_LO12_NC:
435 		case R_AARCH64_LDST64_ABS_LO12_NC:
436 		case R_AARCH64_LDST128_ABS_LO12_NC:
437 			*place &= ~GENMASK(21, 10);
438 			break;
439 		default:
440 			pr_err("unhandled relocation type %llu\n",
441 			       ELF64_R_TYPE(rela->r_info));
442 			BUG();
443 #else
444 #error
445 #endif
446 		}
447 		rela++;
448 	}
449 }
450 
unapply_rodata_relocations(void * section,int section_size,const Elf64_Rela * rela,int numrels)451 static void __init unapply_rodata_relocations(void *section, int section_size,
452 					      const Elf64_Rela *rela, int numrels)
453 {
454 	while (numrels--) {
455 		void *place = section + rela->r_offset;
456 
457 		BUG_ON(rela->r_offset >= section_size);
458 
459 		switch (ELF64_R_TYPE(rela->r_info)) {
460 #ifdef CONFIG_ARM64
461 		case R_AARCH64_ABS64:
462 			*(u64 *)place = 0;
463 			break;
464 		default:
465 			pr_err("unhandled relocation type %llu\n",
466 			       ELF64_R_TYPE(rela->r_info));
467 			BUG();
468 #else
469 #error
470 #endif
471 		}
472 		rela++;
473 	}
474 }
475 
476 enum {
477 	PACIASP		= 0xd503233f,
478 	AUTIASP		= 0xd50323bf,
479 	SCS_PUSH	= 0xf800865e,
480 	SCS_POP		= 0xf85f8e5e,
481 };
482 
483 /*
484  * To make the integrity check work with dynamic Shadow Call Stack (SCS),
485  * replace all instructions that push or pop from the SCS with the Pointer
486  * Authentication Code (PAC) instructions that were present originally.
487  */
unapply_scs_patch(void * section,int section_size)488 static void __init unapply_scs_patch(void *section, int section_size)
489 {
490 #if defined(CONFIG_ARM64) && defined(CONFIG_UNWIND_PATCH_PAC_INTO_SCS)
491 	u32 *insns = section;
492 	int i;
493 
494 	for (i = 0; i < section_size / sizeof(insns[0]); i++) {
495 		if (insns[i] == SCS_PUSH)
496 			insns[i] = PACIASP;
497 		else if (insns[i] == SCS_POP)
498 			insns[i] = AUTIASP;
499 	}
500 #endif
501 }
502 
503 #ifdef CONFIG_CRYPTO_FIPS140_MOD_DEBUG_INTEGRITY_CHECK
504 static struct {
505 	const void *text;
506 	int textsize;
507 	const void *rodata;
508 	int rodatasize;
509 } saved_integrity_check_info;
510 
fips140_text_read(struct file * file,char __user * to,size_t count,loff_t * ppos)511 static ssize_t fips140_text_read(struct file *file, char __user *to,
512 				 size_t count, loff_t *ppos)
513 {
514 	return simple_read_from_buffer(to, count, ppos,
515 				       saved_integrity_check_info.text,
516 				       saved_integrity_check_info.textsize);
517 }
518 
fips140_rodata_read(struct file * file,char __user * to,size_t count,loff_t * ppos)519 static ssize_t fips140_rodata_read(struct file *file, char __user *to,
520 				   size_t count, loff_t *ppos)
521 {
522 	return simple_read_from_buffer(to, count, ppos,
523 				       saved_integrity_check_info.rodata,
524 				       saved_integrity_check_info.rodatasize);
525 }
526 
527 static const struct file_operations fips140_text_fops = {
528 	.read = fips140_text_read,
529 };
530 
531 static const struct file_operations fips140_rodata_fops = {
532 	.read = fips140_rodata_read,
533 };
534 
fips140_init_integrity_debug_files(const void * text,int textsize,const void * rodata,int rodatasize)535 static void fips140_init_integrity_debug_files(const void *text, int textsize,
536 					       const void *rodata,
537 					       int rodatasize)
538 {
539 	struct dentry *dir;
540 
541 	dir = debugfs_create_dir("fips140", NULL);
542 
543 	saved_integrity_check_info.text = kmemdup(text, textsize, GFP_KERNEL);
544 	saved_integrity_check_info.textsize = textsize;
545 	if (saved_integrity_check_info.text)
546 		debugfs_create_file("text", 0400, dir, NULL,
547 				    &fips140_text_fops);
548 
549 	saved_integrity_check_info.rodata = kmemdup(rodata, rodatasize,
550 						    GFP_KERNEL);
551 	saved_integrity_check_info.rodatasize = rodatasize;
552 	if (saved_integrity_check_info.rodata)
553 		debugfs_create_file("rodata", 0400, dir, NULL,
554 				    &fips140_rodata_fops);
555 }
556 #else /* CONFIG_CRYPTO_FIPS140_MOD_DEBUG_INTEGRITY_CHECK */
fips140_init_integrity_debug_files(const void * text,int textsize,const void * rodata,int rodatasize)557 static void fips140_init_integrity_debug_files(const void *text, int textsize,
558 					       const void *rodata,
559 					       int rodatasize)
560 {
561 }
562 #endif /* !CONFIG_CRYPTO_FIPS140_MOD_DEBUG_INTEGRITY_CHECK */
563 
564 extern struct {
565 	u32	offset;
566 	u32	count;
567 } fips140_rela_text, fips140_rela_rodata;
568 
check_fips140_module_hmac(void)569 static bool __init check_fips140_module_hmac(void)
570 {
571 	struct crypto_shash *tfm = NULL;
572 	SHASH_DESC_ON_STACK(desc, dontcare);
573 	u8 digest[SHA256_DIGEST_SIZE];
574 	void *textcopy, *rodatacopy;
575 	int textsize, rodatasize;
576 	bool ok = false;
577 	int err;
578 
579 	textsize	= &__fips140_text_end - &__fips140_text_start;
580 	rodatasize	= &__fips140_rodata_end - &__fips140_rodata_start;
581 
582 	pr_info("text size  : 0x%x\n", textsize);
583 	pr_info("rodata size: 0x%x\n", rodatasize);
584 
585 	textcopy = kmalloc(textsize + rodatasize, GFP_KERNEL);
586 	if (!textcopy) {
587 		pr_err("Failed to allocate memory for copy of .text\n");
588 		goto out;
589 	}
590 
591 	rodatacopy = textcopy + textsize;
592 
593 	memcpy(textcopy, fips140_text_start, textsize);
594 	memcpy(rodatacopy, fips140_rodata_start, rodatasize);
595 
596 	// apply the relocations in reverse on the copies of .text  and .rodata
597 	unapply_text_relocations(textcopy, textsize,
598 				 offset_to_ptr(&fips140_rela_text.offset),
599 				 fips140_rela_text.count);
600 
601 	unapply_rodata_relocations(rodatacopy, rodatasize,
602 				  offset_to_ptr(&fips140_rela_rodata.offset),
603 				  fips140_rela_rodata.count);
604 
605 	unapply_scs_patch(textcopy, textsize);
606 
607 	fips140_init_integrity_debug_files(textcopy, textsize,
608 					   rodatacopy, rodatasize);
609 
610 	fips140_inject_integrity_failure(textcopy);
611 
612 	tfm = crypto_alloc_shash("hmac(sha256)", 0, 0);
613 	if (IS_ERR(tfm)) {
614 		pr_err("failed to allocate hmac tfm (%ld)\n", PTR_ERR(tfm));
615 		tfm = NULL;
616 		goto out;
617 	}
618 	desc->tfm = tfm;
619 
620 	pr_info("using '%s' for integrity check\n",
621 		crypto_shash_driver_name(tfm));
622 
623 	err = crypto_shash_setkey(tfm, fips140_integ_hmac_key,
624 				  strlen(fips140_integ_hmac_key)) ?:
625 	      crypto_shash_init(desc) ?:
626 	      crypto_shash_update(desc, textcopy, textsize) ?:
627 	      crypto_shash_finup(desc, rodatacopy, rodatasize, digest);
628 
629 	/* Zeroizing this is important; see the comment below. */
630 	shash_desc_zero(desc);
631 
632 	if (err) {
633 		pr_err("failed to calculate hmac shash (%d)\n", err);
634 		goto out;
635 	}
636 
637 	if (memcmp(digest, fips140_integ_hmac_digest, sizeof(digest))) {
638 		pr_err("provided_digest  : %*phN\n", (int)sizeof(digest),
639 		       fips140_integ_hmac_digest);
640 
641 		pr_err("calculated digest: %*phN\n", (int)sizeof(digest),
642 		       digest);
643 		goto out;
644 	}
645 	ok = true;
646 out:
647 	/*
648 	 * FIPS 140-3 requires that all "temporary value(s) generated during the
649 	 * integrity test" be zeroized (ref: FIPS 140-3 IG 9.7.B).  There is no
650 	 * technical reason to do this given that these values are public
651 	 * information, but this is the requirement so we follow it.
652 	 */
653 	crypto_free_shash(tfm);
654 	memzero_explicit(digest, sizeof(digest));
655 	kfree_sensitive(textcopy);
656 	return ok;
657 }
658 
fips140_sha256(void * p,const u8 * data,unsigned int len,u8 * out,int * hook_inuse)659 static void fips140_sha256(void *p, const u8 *data, unsigned int len, u8 *out,
660 			   int *hook_inuse)
661 {
662 	sha256(data, len, out);
663 	*hook_inuse = 1;
664 }
665 
fips140_aes_expandkey(void * p,struct crypto_aes_ctx * ctx,const u8 * in_key,unsigned int key_len,int * err)666 static void fips140_aes_expandkey(void *p, struct crypto_aes_ctx *ctx,
667 				  const u8 *in_key, unsigned int key_len,
668 				  int *err)
669 {
670 	*err = aes_expandkey(ctx, in_key, key_len);
671 }
672 
fips140_aes_encrypt(void * priv,const struct crypto_aes_ctx * ctx,u8 * out,const u8 * in,int * hook_inuse)673 static void fips140_aes_encrypt(void *priv, const struct crypto_aes_ctx *ctx,
674 				u8 *out, const u8 *in, int *hook_inuse)
675 {
676 	aes_encrypt(ctx, out, in);
677 	*hook_inuse = 1;
678 }
679 
fips140_aes_decrypt(void * priv,const struct crypto_aes_ctx * ctx,u8 * out,const u8 * in,int * hook_inuse)680 static void fips140_aes_decrypt(void *priv, const struct crypto_aes_ctx *ctx,
681 				u8 *out, const u8 *in, int *hook_inuse)
682 {
683 	aes_decrypt(ctx, out, in);
684 	*hook_inuse = 1;
685 }
686 
update_fips140_library_routines(void)687 static bool update_fips140_library_routines(void)
688 {
689 	int ret;
690 
691 	ret = register_trace_android_vh_sha256(fips140_sha256, NULL) ?:
692 	      register_trace_android_vh_aes_expandkey(fips140_aes_expandkey, NULL) ?:
693 	      register_trace_android_vh_aes_encrypt(fips140_aes_encrypt, NULL) ?:
694 	      register_trace_android_vh_aes_decrypt(fips140_aes_decrypt, NULL);
695 
696 	return ret == 0;
697 }
698 
699 /* Initialize the FIPS 140 module */
fips140_init(void)700 static int __init fips140_init(void)
701 {
702 	const initcall_entry_t *initcall;
703 
704 	pr_info("loading " FIPS140_MODULE_NAME " " FIPS140_MODULE_VERSION "\n");
705 	fips140_init_thread = current;
706 
707 	unregister_existing_fips140_algos();
708 
709 	/* iterate over all init routines present in this module and call them */
710 	for (initcall = fips140_initcalls_start + 1;
711 	     initcall < &__fips140_initcalls_end;
712 	     initcall++) {
713 		initcall_t init = offset_to_ptr(initcall);
714 		int err = init();
715 
716 		/*
717 		 * ENODEV is expected from initcalls that only register
718 		 * algorithms that depend on non-present CPU features.  Besides
719 		 * that, errors aren't expected here.
720 		 */
721 		if (err && err != -ENODEV) {
722 			pr_err("initcall %ps() failed: %d\n", init, err);
723 			goto panic;
724 		}
725 	}
726 
727 	if (!fips140_run_selftests())
728 		goto panic;
729 
730 	if (!fips140_verify_no_extra_unregistrations())
731 		goto panic;
732 
733 	/*
734 	 * It may seem backward to perform the integrity check last, but this
735 	 * is intentional: the check itself uses hmac(sha256) which is one of
736 	 * the algorithms that are replaced with versions from this module, and
737 	 * the integrity check must use the replacement version.  Also, to be
738 	 * ready for FIPS 140-3, the integrity check algorithm must have already
739 	 * been self-tested.
740 	 */
741 
742 	if (!check_fips140_module_hmac()) {
743 		if (!IS_ENABLED(CONFIG_CRYPTO_FIPS140_MOD_DEBUG_INTEGRITY_CHECK)) {
744 			pr_crit("integrity check failed -- giving up!\n");
745 			goto panic;
746 		}
747 		pr_crit("ignoring integrity check failure due to debug mode\n");
748 	} else {
749 		pr_info("integrity check passed\n");
750 	}
751 
752 	complete_all(&fips140_tests_done);
753 
754 	if (!update_fips140_library_routines())
755 		goto panic;
756 
757 	if (!fips140_eval_testing_init())
758 		goto panic;
759 
760 	pr_info("module successfully loaded\n");
761 	return 0;
762 
763 panic:
764 	panic("FIPS 140 module load failure");
765 }
766 
767 module_init(fips140_init);
768 
769 MODULE_IMPORT_NS(CRYPTO_INTERNAL);
770 MODULE_LICENSE("GPL v2");
771 
772 /*
773  * Below are copies of some selected "crypto-related" helper functions that are
774  * used by fips140.ko but are not already built into it, due to them being
775  * defined in a file that cannot easily be built into fips140.ko (e.g.,
776  * crypto/algapi.c) instead of one that can (e.g., most files in lib/).
777  *
778  * There is no hard rule about what needs to be included here, as this is for
779  * FIPS certifiability, not any technical reason.  FIPS modules are supposed to
780  * implement the "crypto" themselves, but to do so they are allowed to call
781  * non-cryptographic helper functions from outside the module.  Something like
782  * memcpy() is "clearly" non-cryptographic.  However, there is is ambiguity
783  * about functions like crypto_inc() which aren't cryptographic by themselves,
784  * but are more closely associated with cryptography than e.g. memcpy().  To err
785  * on the side of caution, we define copies of some selected functions below so
786  * that calls to them from within fips140.ko will remain in fips140.ko.
787  */
788 
crypto_inc_byte(u8 * a,unsigned int size)789 static inline void crypto_inc_byte(u8 *a, unsigned int size)
790 {
791 	u8 *b = (a + size);
792 	u8 c;
793 
794 	for (; size; size--) {
795 		c = *--b + 1;
796 		*b = c;
797 		if (c)
798 			break;
799 	}
800 }
801 
crypto_inc(u8 * a,unsigned int size)802 void crypto_inc(u8 *a, unsigned int size)
803 {
804 	__be32 *b = (__be32 *)(a + size);
805 	u32 c;
806 
807 	if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
808 	    IS_ALIGNED((unsigned long)b, __alignof__(*b)))
809 		for (; size >= 4; size -= 4) {
810 			c = be32_to_cpu(*--b) + 1;
811 			*b = cpu_to_be32(c);
812 			if (likely(c))
813 				return;
814 		}
815 
816 	crypto_inc_byte(a, size);
817 }
818