xref: /freebsd/lib/libsecureboot/vepcr.c (revision 123af6ec70016f5556da5972d4d63c7d175c06d3)
1 /*-
2  * Copyright (c) 2018, Juniper Networks, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
14  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
15  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
16  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
17  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
19  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 #include <sys/cdefs.h>
26 __FBSDID("$FreeBSD$");
27 
28 #include "libsecureboot-priv.h"
29 
30 /*
31  * To support measured boot without putting a ton
32  * of extra code in the loader, we just maintain
33  * a hash of all the hashes we (attempt to) verify.
34  * The loader can export this for kernel or rc script
35  * to feed to a TPM pcr register - hence the name ve_pcr.
36  *
37  * NOTE: in the current standard the TPM pcr register size is for SHA1,
38  * the fact that we provide a SHA256 hash should not matter
39  * as long as we are consistent - it can be truncated or hashed
40  * before feeding to TPM.
41  */
42 
43 static const br_hash_class *pcr_md = NULL;
44 static br_hash_compat_context pcr_ctx;
45 static size_t pcr_hlen = 0;
46 
47 /**
48  * @brief initialize pcr context
49  *
50  * Real TPM registers only hold a SHA1 hash
51  * but we use SHA256
52  */
53 void
54 ve_pcr_init(void)
55 {
56 	pcr_hlen = br_sha256_SIZE;
57 	pcr_md = &br_sha256_vtable;
58 	pcr_md->init(&pcr_ctx.vtable);
59 }
60 
61 /**
62  * @brief update pcr context
63  */
64 void
65 ve_pcr_update(unsigned char *data, size_t dlen)
66 {
67 	if (pcr_md)
68 		pcr_md->update(&pcr_ctx.vtable, data, dlen);
69 }
70 
71 /**
72  * @brief get pcr result
73  */
74 ssize_t
75 ve_pcr_get(unsigned char *buf, size_t sz)
76 {
77 	if (!pcr_md)
78 		return (-1);
79 	if (sz < pcr_hlen)
80 		return (-1);
81 	pcr_md->out(&pcr_ctx.vtable, buf);
82 	return (pcr_hlen);
83 }
84 
85