blob: f15517d108eb1fbd83da9aeee4482d2f37dd0d9e [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
Lorenz Brunae0d90d2019-09-05 17:53:56 +02002// SPDX-License-Identifier: Apache-2.0
Lorenz Brunae0d90d2019-09-05 17:53:56 +02003
4package tpm
5
6import (
Lorenz Brunaa6b7342019-12-12 02:55:02 +01007 "bytes"
8 "crypto"
Lorenz Brunae0d90d2019-09-05 17:53:56 +02009 "crypto/rand"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010010 "crypto/rsa"
11 "crypto/x509"
Tim Windelschmidt3215ee82024-04-23 15:12:39 +020012 "errors"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020013 "fmt"
14 "io"
15 "os"
16 "path/filepath"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020017 "strconv"
Serge Bazanskic7359672020-10-30 16:38:57 +010018 "strings"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020019 "sync"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010020 "time"
21
Lorenz Brund13c1c62022-03-30 19:58:58 +020022 tpm2tools "github.com/google/go-tpm-tools/client"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020023 "github.com/google/go-tpm/tpm2"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010024 "github.com/google/go-tpm/tpmutil"
Lorenz Brun662182f2022-03-10 14:06:48 +010025 "golang.org/x/crypto/nacl/secretbox"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020026 "golang.org/x/sys/unix"
Lorenz Brun65702192023-08-31 16:27:38 +020027 "google.golang.org/protobuf/proto"
28
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020029 tpmpb "source.monogon.dev/osbase/tpm/proto"
Serge Bazanski77cb6c52020-12-19 00:09:22 +010030
Serge Bazanski3c5d0632024-09-12 10:49:12 +000031 "source.monogon.dev/go/logging"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020032 "source.monogon.dev/osbase/sysfs"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020033)
34
35var (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020036 // SecureBootPCRs are all PCRs that measure the current Secure Boot
37 // configuration. This is what we want if we rely on secure boot to verify
38 // boot integrity. The firmware hashes the secure boot policy and custom
39 // keys into the PCR.
Leopold Schabel68c58752019-11-14 21:00:59 +010040 //
41 // This requires an extra step that provisions the custom keys.
42 //
43 // Some background: https://mjg59.dreamwidth.org/48897.html?thread=1847297
Serge Bazanski216fe7b2021-05-21 18:36:16 +020044 // (the initramfs issue mentioned in the article has been solved by
45 // integrating it into the kernel binary, and we don't have a shim
46 // bootloader)
Leopold Schabel68c58752019-11-14 21:00:59 +010047 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020048 // PCR7 alone is not sufficient - it needs to be combined with firmware
49 // measurements.
Lorenz Brunae0d90d2019-09-05 17:53:56 +020050 SecureBootPCRs = []int{7}
51
Serge Bazanski216fe7b2021-05-21 18:36:16 +020052 // FirmwarePCRs are alle PCRs that contain the firmware measurements. See:
53 // https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf
Leopold Schabel68c58752019-11-14 21:00:59 +010054 FirmwarePCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010055 0, // platform firmware
56 2, // option ROM code
57 3, // option ROM configuration and data
Leopold Schabel68c58752019-11-14 21:00:59 +010058 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +020059
Serge Bazanski216fe7b2021-05-21 18:36:16 +020060 // FullSystemPCRs are all PCRs that contain any measurements up to the
61 // currently running EFI payload.
Leopold Schabel68c58752019-11-14 21:00:59 +010062 FullSystemPCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010063 0, // platform firmware
64 1, // host platform configuration
65 2, // option ROM code
66 3, // option ROM configuration and data
67 4, // EFI payload
Leopold Schabel68c58752019-11-14 21:00:59 +010068 }
69
Serge Bazanski216fe7b2021-05-21 18:36:16 +020070 // Using FullSystemPCRs is the most secure, but also the most brittle
71 // option since updating the EFI binary, updating the platform firmware,
72 // changing platform settings or updating the binary would invalidate the
73 // sealed data. It's annoying (but possible) to predict values for PCR4,
74 // and even more annoying for the firmware PCR (comparison to known values
75 // on similar hardware is the only thing that comes to mind).
Leopold Schabel68c58752019-11-14 21:00:59 +010076 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020077 // See also: https://github.com/mxre/sealkey (generates PCR4 from EFI
78 // image, BSD license)
Leopold Schabel68c58752019-11-14 21:00:59 +010079 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020080 // Using only SecureBootPCRs is the easiest and still reasonably secure, if
81 // we assume that the platform knows how to take care of itself (i.e. Intel
82 // Boot Guard), and that secure boot is implemented properly. It is,
83 // however, a much larger amount of code we need to trust.
Leopold Schabel68c58752019-11-14 21:00:59 +010084 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020085 // We do not care about PCR 5 (GPT partition table) since modifying it is
86 // harmless. All of the boot options and cmdline are hardcoded in the
87 // kernel image, and we use no bootloader, so there's no PCR for bootloader
88 // configuration or kernel cmdline.
Lorenz Brunae0d90d2019-09-05 17:53:56 +020089)
90
91var (
Lorenz Brunaa6b7342019-12-12 02:55:02 +010092 numSRTMPCRs = 16
93 srtmPCRs = tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}}
94 // TCG Trusted Platform Module Library Level 00 Revision 0.99 Table 6
95 tpmGeneratedValue = uint32(0xff544347)
96)
97
98var (
Lorenz Brunae0d90d2019-09-05 17:53:56 +020099 // ErrNotExists is returned when no TPMs are available in the system
100 ErrNotExists = errors.New("no TPMs found")
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200101 // ErrNotInitialized is returned when this package was not initialized
102 // successfully
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200103 ErrNotInitialized = errors.New("no TPM was initialized")
104)
105
106// Singleton since the TPM is too
107var tpm *TPM
108
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200109// We're serializing all TPM operations since it has a limited number of
110// handles and recovering if it runs out is difficult to implement correctly.
111// Might also be marginally more secure.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200112var lock sync.Mutex
113
114// TPM represents a high-level interface to a connected TPM 2.0
115type TPM struct {
Serge Bazanski3c5d0632024-09-12 10:49:12 +0000116 logger logging.Leveled
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200117 device io.ReadWriteCloser
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100118
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200119 // We keep the AK loaded since it's used fairly often and deriving it is
120 // expensive
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100121 akHandleCache tpmutil.Handle
122 akPublicKey crypto.PublicKey
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200123}
124
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200125// Initialize finds and opens the TPM (if any). If there is no TPM available it
126// returns ErrNotExists
Serge Bazanski3c5d0632024-09-12 10:49:12 +0000127func Initialize(logger logging.Leveled) error {
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200128 lock.Lock()
129 defer lock.Unlock()
130 tpmDir, err := os.Open("/sys/class/tpm")
131 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200132 return fmt.Errorf("failed to open sysfs TPM class: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200133 }
134 defer tpmDir.Close()
135
136 tpms, err := tpmDir.Readdirnames(2)
137 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200138 return fmt.Errorf("failed to read TPM device class: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200139 }
140
141 if len(tpms) == 0 {
142 return ErrNotExists
143 }
144 if len(tpms) > 1 {
Lorenz Bruna50e8452020-09-09 17:09:27 +0200145 // If this is changed GetMeasurementLog() needs to be updated too
Serge Bazanskic7359672020-10-30 16:38:57 +0100146 logger.Warningf("Found more than one TPM, using the first one")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200147 }
148 tpmName := tpms[0]
149 ueventData, err := sysfs.ReadUevents(filepath.Join("/sys/class/tpm", tpmName, "uevent"))
Tim Windelschmidt096654a2024-04-18 23:10:19 +0200150 if err != nil {
151 return fmt.Errorf("failed to read uevents: %w", err)
152 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200153 majorDev, err := strconv.Atoi(ueventData["MAJOR"])
154 if err != nil {
155 return fmt.Errorf("failed to convert uevent: %w", err)
156 }
157 minorDev, err := strconv.Atoi(ueventData["MINOR"])
158 if err != nil {
159 return fmt.Errorf("failed to convert uevent: %w", err)
160 }
161 if err := unix.Mknod("/dev/tpm", 0600|unix.S_IFCHR, int(unix.Mkdev(uint32(majorDev), uint32(minorDev)))); err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200162 return fmt.Errorf("failed to create TPM device node: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200163 }
164 device, err := tpm2.OpenTPM("/dev/tpm")
165 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200166 return fmt.Errorf("failed to open TPM: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200167 }
168 tpm = &TPM{
169 device: device,
170 logger: logger,
171 }
172 return nil
173}
174
Lorenz Brun8b786892022-01-13 14:21:16 +0100175// IsInitialized returns true if Initialize was called an at least one
176// TPM 2.0 was found and initialized. Otherwise it returns false.
177func IsInitialized() bool {
178 lock.Lock()
179 defer lock.Unlock()
Tim Windelschmidt683b62b2024-04-18 23:40:33 +0200180 return tpm != nil
Lorenz Brun8b786892022-01-13 14:21:16 +0100181}
182
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200183// GenerateSafeKey uses two sources of randomness (Kernel & TPM) to generate
184// the key
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200185func GenerateSafeKey(size uint16) ([]byte, error) {
186 lock.Lock()
187 defer lock.Unlock()
188 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200189 return nil, ErrNotInitialized
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200190 }
191 encryptionKeyHost := make([]byte, size)
192 if _, err := io.ReadFull(rand.Reader, encryptionKeyHost); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200193 return nil, fmt.Errorf("failed to generate host portion of new key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200194 }
195 var encryptionKeyTPM []byte
196 for i := 48; i > 0; i-- {
197 tpmKeyPart, err := tpm2.GetRandom(tpm.device, size-uint16(len(encryptionKeyTPM)))
198 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200199 return nil, fmt.Errorf("failed to generate TPM portion of new key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200200 }
201 encryptionKeyTPM = append(encryptionKeyTPM, tpmKeyPart...)
202 if len(encryptionKeyTPM) >= int(size) {
203 break
204 }
205 }
206
207 if len(encryptionKeyTPM) != int(size) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200208 return nil, fmt.Errorf("got incorrect amount of TPM randomess: %v, requested %v", len(encryptionKeyTPM), size)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200209 }
210
211 encryptionKey := make([]byte, size)
212 for i := uint16(0); i < size; i++ {
213 encryptionKey[i] = encryptionKeyHost[i] ^ encryptionKeyTPM[i]
214 }
215 return encryptionKey, nil
216}
217
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200218// Seal seals sensitive data and only allows access if the current platform
219// configuration in matches the one the data was sealed on.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200220func Seal(data []byte, pcrs []int) ([]byte, error) {
Lorenz Brun662182f2022-03-10 14:06:48 +0100221 // Generate a key and use secretbox to encrypt and authenticate the actual
222 // payload as go-tpm2 uses a raw seal operation limiting payload size to
223 // 128 bytes which is insufficient.
224 boxKey, err := GenerateSafeKey(32)
225 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200226 return nil, fmt.Errorf("failed to generate boxKey: %w", err)
Lorenz Brun662182f2022-03-10 14:06:48 +0100227 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200228 lock.Lock()
229 defer lock.Unlock()
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200230 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
231 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200232 return nil, fmt.Errorf("failed to load TPM SRK: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200233 }
234 defer srk.Close()
Lorenz Brun662182f2022-03-10 14:06:48 +0100235 var boxKeyArr [32]byte
236 copy(boxKeyArr[:], boxKey)
237 // Nonce is not used as we're generating a new boxKey for every operation,
238 // therefore we can just leave it all-zero.
239 var unusedNonce [24]byte
240 encryptedData := secretbox.Seal(nil, data, &unusedNonce, &boxKeyArr)
Lorenz Brund13c1c62022-03-30 19:58:58 +0200241 sealedKey, err := srk.Seal(boxKey, tpm2tools.SealOpts{Current: tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: pcrs}})
Lorenz Brun662182f2022-03-10 14:06:48 +0100242 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200243 return nil, fmt.Errorf("failed to seal boxKey: %w", err)
Lorenz Brun662182f2022-03-10 14:06:48 +0100244 }
245 sealedBytes := tpmpb.ExtendedSealedBytes{
246 SealedKey: sealedKey,
247 EncryptedPayload: encryptedData,
248 }
249 rawSealedBytes, err := proto.Marshal(&sealedBytes)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200250 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200251 return nil, fmt.Errorf("failed to marshal sealed data: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200252 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100253 return rawSealedBytes, nil
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200254}
255
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200256// Unseal unseals sensitive data if the current platform configuration allows
257// and sealing constraints allow it.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200258func Unseal(data []byte) ([]byte, error) {
259 lock.Lock()
260 defer lock.Unlock()
261 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200262 return nil, ErrNotInitialized
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200263 }
264 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
265 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200266 return nil, fmt.Errorf("failed to load TPM SRK: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200267 }
268 defer srk.Close()
269
Lorenz Brun662182f2022-03-10 14:06:48 +0100270 var sealedBytes tpmpb.ExtendedSealedBytes
271 if err := proto.Unmarshal(data, &sealedBytes); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200272 return nil, fmt.Errorf("failed to unmarshal sealed data: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200273 }
Lorenz Bruned6bcac2022-05-04 17:39:41 +0200274 if sealedBytes.SealedKey == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200275 return nil, fmt.Errorf("sealed data structure is invalid: no sealed key")
Lorenz Bruned6bcac2022-05-04 17:39:41 +0200276 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200277 // Logging this for auditing purposes
Tim Windelschmidtbda384c2024-04-11 01:41:57 +0200278 var pcrList []string
Lorenz Brun662182f2022-03-10 14:06:48 +0100279 for _, pcr := range sealedBytes.SealedKey.Pcrs {
Lorenz Brun800e7c92023-07-12 22:37:39 +0200280 pcrList = append(pcrList, strconv.FormatUint(uint64(pcr), 10))
Serge Bazanskic7359672020-10-30 16:38:57 +0100281 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100282 tpm.logger.Infof("Attempting to unseal key protected with PCRs %s", strings.Join(pcrList, ","))
Lorenz Brund13c1c62022-03-30 19:58:58 +0200283 unsealedKey, err := srk.Unseal(sealedBytes.SealedKey, tpm2tools.UnsealOpts{})
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200284 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200285 return nil, fmt.Errorf("failed to unseal key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200286 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100287 var key [32]byte
288 if len(unsealedKey) != len(key) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200289 return nil, fmt.Errorf("unsealed key has wrong length: expected %v bytes, got %v", len(key), len(unsealedKey))
Lorenz Brun662182f2022-03-10 14:06:48 +0100290 }
291 copy(key[:], unsealedKey)
292 var unusedNonce [24]byte
293 payload, ok := secretbox.Open(nil, sealedBytes.EncryptedPayload, &unusedNonce, &key)
294 if !ok {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200295 return nil, errors.New("payload box cannot be opened")
Lorenz Brun662182f2022-03-10 14:06:48 +0100296 }
297 return payload, nil
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200298}
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100299
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200300// Standard AK template for RSA2048 non-duplicatable restricted signing for
301// attestation
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100302var akTemplate = tpm2.Public{
303 Type: tpm2.AlgRSA,
304 NameAlg: tpm2.AlgSHA256,
305 Attributes: tpm2.FlagSignerDefault,
306 RSAParameters: &tpm2.RSAParams{
307 Sign: &tpm2.SigScheme{
308 Alg: tpm2.AlgRSASSA,
309 Hash: tpm2.AlgSHA256,
310 },
311 KeyBits: 2048,
312 },
313}
314
315func loadAK() error {
316 var err error
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200317 // Rationale: The AK is an EK-equivalent key and used only for attestation.
318 // Using a non-primary key here would require us to store the wrapped
319 // version somewhere, which is inconvenient. This being a primary key in
320 // the Endorsement hierarchy means that it can always be recreated and can
321 // never be "destroyed". Under our security model this is of no concern
322 // since we identify a node by its IK (Identity Key) which we can destroy.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100323 tpm.akHandleCache, tpm.akPublicKey, err = tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
324 tpm2.PCRSelection{}, "", "", akTemplate)
325 return err
326}
327
328// Process documented in TCG EK Credential Profile 2.2.1
329func loadEK() (tpmutil.Handle, crypto.PublicKey, error) {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200330 // The EK is a primary key which is supposed to be certified by the
331 // manufacturer of the TPM. Its public attributes are standardized in TCG
332 // EK Credential Profile 2.0 Table 1. These need to match exactly or we
333 // aren't getting the key the manufacturere signed. tpm2tools contains such
334 // a template already, so we're using that instead of redoing it ourselves.
335 // This ignores the more complicated ways EKs can be specified, the
336 // additional stuff you can do is just absolutely crazy (see 2.2.1.2
337 // onward)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100338 return tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
339 tpm2.PCRSelection{}, "", "", tpm2tools.DefaultEKTemplateRSA())
340}
341
342// GetAKPublic gets the TPM2T_PUBLIC of the AK key
343func GetAKPublic() ([]byte, error) {
344 lock.Lock()
345 defer lock.Unlock()
346 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200347 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100348 }
349 if tpm.akHandleCache == tpmutil.Handle(0) {
350 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200351 return nil, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100352 }
353 }
354 public, _, _, err := tpm2.ReadPublic(tpm.device, tpm.akHandleCache)
355 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200356 return nil, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100357 }
358 return public.Encode()
359}
360
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200361// TCG TPM v2.0 Provisioning Guidance v1.0 7.8 Table 2 and TCG EK Credential
362// Profile v2.1 2.2.1.4 de-facto Standard for Windows These are both
363// non-normative and reference Windows 10 documentation that's no longer
364// available :( But in practice this is what people are using, so if it's
365// normative or not doesn't really matter
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100366const ekCertHandle = 0x01c00002
367
368// GetEKPublic gets the public key and (if available) Certificate of the EK
369func GetEKPublic() ([]byte, []byte, error) {
370 lock.Lock()
371 defer lock.Unlock()
372 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200373 return nil, []byte{}, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100374 }
375 ekHandle, publicRaw, err := loadEK()
376 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200377 return nil, []byte{}, fmt.Errorf("failed to load EK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100378 }
379 defer tpm2.FlushContext(tpm.device, ekHandle)
380 // Don't question the use of HandleOwner, that's the Standardâ„¢
381 ekCertRaw, err := tpm2.NVReadEx(tpm.device, ekCertHandle, tpm2.HandleOwner, "", 0)
382 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200383 return nil, []byte{}, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100384 }
385
386 publicKey, err := x509.MarshalPKIXPublicKey(publicRaw)
387 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200388 return nil, []byte{}, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100389 }
390
391 return publicKey, ekCertRaw, nil
392}
393
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200394// MakeAKChallenge generates a challenge for TPM residency and attributes of
395// the AK
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100396func MakeAKChallenge(ekPubKey, akPub []byte, nonce []byte) ([]byte, []byte, error) {
397 ekPubKeyData, err := x509.ParsePKIXPublicKey(ekPubKey)
398 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200399 return nil, []byte{}, fmt.Errorf("failed to decode EK pubkey: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100400 }
401 akPubData, err := tpm2.DecodePublic(akPub)
402 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200403 return nil, []byte{}, fmt.Errorf("failed to decode AK public part: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100404 }
405 // Make sure we're attesting the right attributes (in particular Restricted)
406 if !akPubData.MatchesTemplate(akTemplate) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200407 return nil, []byte{}, errors.New("the key being challenged is not a valid AK")
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100408 }
409 akName, err := akPubData.Name()
410 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200411 return nil, []byte{}, fmt.Errorf("failed to derive AK name: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100412 }
413 return generateRSA(akName.Digest, ekPubKeyData.(*rsa.PublicKey), 16, nonce, rand.Reader)
414}
415
416// SolveAKChallenge solves a challenge for TPM residency of the AK
417func SolveAKChallenge(credBlob, secretChallenge []byte) ([]byte, error) {
418 lock.Lock()
419 defer lock.Unlock()
420 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200421 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100422 }
423 if tpm.akHandleCache == tpmutil.Handle(0) {
424 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200425 return nil, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100426 }
427 }
428
429 ekHandle, _, err := loadEK()
430 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200431 return nil, fmt.Errorf("failed to load EK: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100432 }
433 defer tpm2.FlushContext(tpm.device, ekHandle)
434
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200435 // This is necessary since the EK requires an endorsement handle policy in
436 // its session. For us this is stupid because we keep all hierarchies open
437 // anyways since a) we cannot safely store secrets on the OS side
438 // pre-global unlock and b) it makes no sense in this security model since
439 // an uncompromised host OS will not let an untrusted entity attest as
440 // itself and a compromised OS can either not pass PCR policy checks or the
441 // game's already over (you successfully runtime-exploited a production
442 // Metropolis node).
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100443 endorsementSession, _, err := tpm2.StartAuthSession(
444 tpm.device,
445 tpm2.HandleNull,
446 tpm2.HandleNull,
447 make([]byte, 16),
448 nil,
449 tpm2.SessionPolicy,
450 tpm2.AlgNull,
451 tpm2.AlgSHA256)
452 if err != nil {
453 panic(err)
454 }
455 defer tpm2.FlushContext(tpm.device, endorsementSession)
456
Lorenz Brund13c1c62022-03-30 19:58:58 +0200457 _, _, err = tpm2.PolicySecret(tpm.device, tpm2.HandleEndorsement, tpm2.AuthCommand{Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}, endorsementSession, nil, nil, nil, 0)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100458 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200459 return nil, fmt.Errorf("failed to make a policy secret session: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100460 }
461
462 for {
463 solution, err := tpm2.ActivateCredentialUsingAuth(tpm.device, []tpm2.AuthCommand{
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200464 // Use standard no-password authenatication
465 {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession},
466 // Use a full policy session for the EK
467 {Session: endorsementSession, Attributes: tpm2.AttrContinueSession},
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100468 }, tpm.akHandleCache, ekHandle, credBlob, secretChallenge)
Tim Windelschmidtaf821c82024-04-23 15:03:52 +0200469 var warn tpm2.Warning
470 if errors.As(err, &warn) && warn.Code == tpm2.RCRetry {
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100471 time.Sleep(100 * time.Millisecond)
472 continue
473 }
474 return solution, err
475 }
476}
477
478// FlushTransientHandles flushes all sessions and non-persistent handles
479func FlushTransientHandles() error {
480 lock.Lock()
481 defer lock.Unlock()
482 if tpm == nil {
483 return ErrNotInitialized
484 }
485 flushHandleTypes := []tpm2.HandleType{tpm2.HandleTypeTransient, tpm2.HandleTypeLoadedSession, tpm2.HandleTypeSavedSession}
486 for _, handleType := range flushHandleTypes {
487 handles, err := tpm2tools.Handles(tpm.device, handleType)
488 if err != nil {
489 return err
490 }
491 for _, handle := range handles {
492 if err := tpm2.FlushContext(tpm.device, handle); err != nil {
493 return err
494 }
495 }
496 }
497 return nil
498}
499
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200500// AttestPlatform performs a PCR quote using the AK and returns the quote and
501// its signature
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100502func AttestPlatform(nonce []byte) ([]byte, []byte, error) {
503 lock.Lock()
504 defer lock.Unlock()
505 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200506 return nil, []byte{}, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100507 }
508 if tpm.akHandleCache == tpmutil.Handle(0) {
509 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200510 return nil, []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100511 }
512 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200513 // We only care about SHA256 since SHA1 is weak. This is supported on at
514 // least GCE and Intel / AMD fTPM, which is good enough for now. Alg is
515 // null because that would just hash the nonce, which is dumb.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100516 quote, signature, err := tpm2.Quote(tpm.device, tpm.akHandleCache, "", "", nonce, srtmPCRs,
517 tpm2.AlgNull)
518 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200519 return nil, []byte{}, fmt.Errorf("failed to quote PCRs: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100520 }
521 return quote, signature.RSA.Signature, err
522}
523
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200524// VerifyAttestPlatform verifies a given attestation. You can rely on all data
525// coming back as being from the TPM on which the AK is bound to.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100526func VerifyAttestPlatform(nonce, akPub, quote, signature []byte) (*tpm2.AttestationData, error) {
527 hash := crypto.SHA256.New()
528 hash.Write(quote)
529
530 akPubData, err := tpm2.DecodePublic(akPub)
531 if err != nil {
532 return nil, fmt.Errorf("invalid AK: %w", err)
533 }
534 akPublicKey, err := akPubData.Key()
535 if err != nil {
536 return nil, fmt.Errorf("invalid AK: %w", err)
537 }
538 akRSAKey, ok := akPublicKey.(*rsa.PublicKey)
539 if !ok {
540 return nil, errors.New("invalid AK: invalid key type")
541 }
542
543 if err := rsa.VerifyPKCS1v15(akRSAKey, crypto.SHA256, hash.Sum(nil), signature); err != nil {
544 return nil, err
545 }
546
547 quoteData, err := tpm2.DecodeAttestationData(quote)
548 if err != nil {
549 return nil, err
550 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200551 // quoteData.Magic works together with the TPM's Restricted key attribute.
552 // If this attribute is set (which it needs to be for the AK to be
553 // considered valid) the TPM will not sign external data having this prefix
554 // with such a key. Only data that originates inside the TPM like quotes
555 // and key certifications can have this prefix and sill be signed by a
556 // restricted key. This check is thus vital, otherwise somebody can just
557 // feed the TPM an arbitrary attestation to sign with its AK and this
558 // function will happily accept the forged attestation.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100559 if quoteData.Magic != tpmGeneratedValue {
560 return nil, errors.New("invalid TPM quote: data marker for internal data not set - forged attestation")
561 }
562 if quoteData.Type != tpm2.TagAttestQuote {
563 return nil, errors.New("invalid TPM qoute: not a TPM quote")
564 }
565 if !bytes.Equal(quoteData.ExtraData, nonce) {
566 return nil, errors.New("invalid TPM quote: wrong nonce")
567 }
568
569 return quoteData, nil
570}
571
572// GetPCRs returns all SRTM PCRs in-order
573func GetPCRs() ([][]byte, error) {
574 lock.Lock()
575 defer lock.Unlock()
576 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200577 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100578 }
579 pcrs := make([][]byte, numSRTMPCRs)
580
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200581 // The TPM can (and most do) return partial results. Let's just retry as
582 // many times as we have PCRs since each read should return at least one
583 // PCR.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100584readLoop:
585 for i := 0; i < numSRTMPCRs; i++ {
586 sel := tpm2.PCRSelection{Hash: tpm2.AlgSHA256}
587 for pcrN := 0; pcrN < numSRTMPCRs; pcrN++ {
588 if len(pcrs[pcrN]) == 0 {
589 sel.PCRs = append(sel.PCRs, pcrN)
590 }
591 }
592
593 readPCRs, err := tpm2.ReadPCRs(tpm.device, sel)
594 if err != nil {
595 return nil, fmt.Errorf("failed to read PCRs: %w", err)
596 }
597
598 for pcrN, pcr := range readPCRs {
599 pcrs[pcrN] = pcr
600 }
601 for _, pcr := range pcrs {
602 // If at least one PCR is still not read, continue
603 if len(pcr) == 0 {
604 continue readLoop
605 }
606 }
607 break
608 }
609
610 return pcrs, nil
611}
Lorenz Bruna50e8452020-09-09 17:09:27 +0200612
Tim Windelschmidt8732d432024-04-18 23:20:05 +0200613// GetMeasurementLog returns the binary log of all data hashed into PCRs. The
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200614// result can be parsed by eventlog. As this library currently doesn't support
615// extending PCRs it just returns the log as supplied by the EFI interface.
Lorenz Bruna50e8452020-09-09 17:09:27 +0200616func GetMeasurementLog() ([]byte, error) {
Lorenz Brun764a2de2021-11-22 16:26:36 +0100617 return os.ReadFile("/sys/kernel/security/tpm0/binary_bios_measurements")
Lorenz Bruna50e8452020-09-09 17:09:27 +0200618}