blob: 79733990c8f74acea2b791f4076185964f20c8c6 [file] [log] [blame]
Lorenz Brunae0d90d2019-09-05 17:53:56 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package tpm
18
19import (
Lorenz Brunaa6b7342019-12-12 02:55:02 +010020 "bytes"
21 "crypto"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020022 "crypto/rand"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010023 "crypto/rsa"
24 "crypto/x509"
Tim Windelschmidt3215ee82024-04-23 15:12:39 +020025 "errors"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020026 "fmt"
27 "io"
28 "os"
29 "path/filepath"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020030 "strconv"
Serge Bazanskic7359672020-10-30 16:38:57 +010031 "strings"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020032 "sync"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010033 "time"
34
Lorenz Brund13c1c62022-03-30 19:58:58 +020035 tpm2tools "github.com/google/go-tpm-tools/client"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020036 "github.com/google/go-tpm/tpm2"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010037 "github.com/google/go-tpm/tpmutil"
Lorenz Brun662182f2022-03-10 14:06:48 +010038 "golang.org/x/crypto/nacl/secretbox"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020039 "golang.org/x/sys/unix"
Lorenz Brun65702192023-08-31 16:27:38 +020040 "google.golang.org/protobuf/proto"
41
42 tpmpb "source.monogon.dev/metropolis/pkg/tpm/proto"
Serge Bazanski77cb6c52020-12-19 00:09:22 +010043
Serge Bazanski31370b02021-01-07 16:31:14 +010044 "source.monogon.dev/metropolis/pkg/logtree"
45 "source.monogon.dev/metropolis/pkg/sysfs"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020046)
47
48var (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020049 // SecureBootPCRs are all PCRs that measure the current Secure Boot
50 // configuration. This is what we want if we rely on secure boot to verify
51 // boot integrity. The firmware hashes the secure boot policy and custom
52 // keys into the PCR.
Leopold Schabel68c58752019-11-14 21:00:59 +010053 //
54 // This requires an extra step that provisions the custom keys.
55 //
56 // Some background: https://mjg59.dreamwidth.org/48897.html?thread=1847297
Serge Bazanski216fe7b2021-05-21 18:36:16 +020057 // (the initramfs issue mentioned in the article has been solved by
58 // integrating it into the kernel binary, and we don't have a shim
59 // bootloader)
Leopold Schabel68c58752019-11-14 21:00:59 +010060 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020061 // PCR7 alone is not sufficient - it needs to be combined with firmware
62 // measurements.
Lorenz Brunae0d90d2019-09-05 17:53:56 +020063 SecureBootPCRs = []int{7}
64
Serge Bazanski216fe7b2021-05-21 18:36:16 +020065 // FirmwarePCRs are alle PCRs that contain the firmware measurements. See:
66 // https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf
Leopold Schabel68c58752019-11-14 21:00:59 +010067 FirmwarePCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010068 0, // platform firmware
69 2, // option ROM code
70 3, // option ROM configuration and data
Leopold Schabel68c58752019-11-14 21:00:59 +010071 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +020072
Serge Bazanski216fe7b2021-05-21 18:36:16 +020073 // FullSystemPCRs are all PCRs that contain any measurements up to the
74 // currently running EFI payload.
Leopold Schabel68c58752019-11-14 21:00:59 +010075 FullSystemPCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010076 0, // platform firmware
77 1, // host platform configuration
78 2, // option ROM code
79 3, // option ROM configuration and data
80 4, // EFI payload
Leopold Schabel68c58752019-11-14 21:00:59 +010081 }
82
Serge Bazanski216fe7b2021-05-21 18:36:16 +020083 // Using FullSystemPCRs is the most secure, but also the most brittle
84 // option since updating the EFI binary, updating the platform firmware,
85 // changing platform settings or updating the binary would invalidate the
86 // sealed data. It's annoying (but possible) to predict values for PCR4,
87 // and even more annoying for the firmware PCR (comparison to known values
88 // on similar hardware is the only thing that comes to mind).
Leopold Schabel68c58752019-11-14 21:00:59 +010089 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020090 // See also: https://github.com/mxre/sealkey (generates PCR4 from EFI
91 // image, BSD license)
Leopold Schabel68c58752019-11-14 21:00:59 +010092 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020093 // Using only SecureBootPCRs is the easiest and still reasonably secure, if
94 // we assume that the platform knows how to take care of itself (i.e. Intel
95 // Boot Guard), and that secure boot is implemented properly. It is,
96 // however, a much larger amount of code we need to trust.
Leopold Schabel68c58752019-11-14 21:00:59 +010097 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020098 // We do not care about PCR 5 (GPT partition table) since modifying it is
99 // harmless. All of the boot options and cmdline are hardcoded in the
100 // kernel image, and we use no bootloader, so there's no PCR for bootloader
101 // configuration or kernel cmdline.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200102)
103
104var (
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100105 numSRTMPCRs = 16
106 srtmPCRs = tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}}
107 // TCG Trusted Platform Module Library Level 00 Revision 0.99 Table 6
108 tpmGeneratedValue = uint32(0xff544347)
109)
110
111var (
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200112 // ErrNotExists is returned when no TPMs are available in the system
113 ErrNotExists = errors.New("no TPMs found")
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200114 // ErrNotInitialized is returned when this package was not initialized
115 // successfully
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200116 ErrNotInitialized = errors.New("no TPM was initialized")
117)
118
119// Singleton since the TPM is too
120var tpm *TPM
121
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200122// We're serializing all TPM operations since it has a limited number of
123// handles and recovering if it runs out is difficult to implement correctly.
124// Might also be marginally more secure.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200125var lock sync.Mutex
126
127// TPM represents a high-level interface to a connected TPM 2.0
128type TPM struct {
Serge Bazanskic7359672020-10-30 16:38:57 +0100129 logger logtree.LeveledLogger
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200130 device io.ReadWriteCloser
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100131
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200132 // We keep the AK loaded since it's used fairly often and deriving it is
133 // expensive
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100134 akHandleCache tpmutil.Handle
135 akPublicKey crypto.PublicKey
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200136}
137
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200138// Initialize finds and opens the TPM (if any). If there is no TPM available it
139// returns ErrNotExists
Serge Bazanskic7359672020-10-30 16:38:57 +0100140func Initialize(logger logtree.LeveledLogger) error {
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200141 lock.Lock()
142 defer lock.Unlock()
143 tpmDir, err := os.Open("/sys/class/tpm")
144 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200145 return fmt.Errorf("failed to open sysfs TPM class: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200146 }
147 defer tpmDir.Close()
148
149 tpms, err := tpmDir.Readdirnames(2)
150 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200151 return fmt.Errorf("failed to read TPM device class: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200152 }
153
154 if len(tpms) == 0 {
155 return ErrNotExists
156 }
157 if len(tpms) > 1 {
Lorenz Bruna50e8452020-09-09 17:09:27 +0200158 // If this is changed GetMeasurementLog() needs to be updated too
Serge Bazanskic7359672020-10-30 16:38:57 +0100159 logger.Warningf("Found more than one TPM, using the first one")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200160 }
161 tpmName := tpms[0]
162 ueventData, err := sysfs.ReadUevents(filepath.Join("/sys/class/tpm", tpmName, "uevent"))
163 majorDev, err := strconv.Atoi(ueventData["MAJOR"])
164 if err != nil {
165 return fmt.Errorf("failed to convert uevent: %w", err)
166 }
167 minorDev, err := strconv.Atoi(ueventData["MINOR"])
168 if err != nil {
169 return fmt.Errorf("failed to convert uevent: %w", err)
170 }
171 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 +0200172 return fmt.Errorf("failed to create TPM device node: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200173 }
174 device, err := tpm2.OpenTPM("/dev/tpm")
175 if err != nil {
Tim Windelschmidtc20e3722024-04-23 15:04:45 +0200176 return fmt.Errorf("failed to open TPM: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200177 }
178 tpm = &TPM{
179 device: device,
180 logger: logger,
181 }
182 return nil
183}
184
Lorenz Brun8b786892022-01-13 14:21:16 +0100185// IsInitialized returns true if Initialize was called an at least one
186// TPM 2.0 was found and initialized. Otherwise it returns false.
187func IsInitialized() bool {
188 lock.Lock()
189 defer lock.Unlock()
Tim Windelschmidt683b62b2024-04-18 23:40:33 +0200190 return tpm != nil
Lorenz Brun8b786892022-01-13 14:21:16 +0100191}
192
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200193// GenerateSafeKey uses two sources of randomness (Kernel & TPM) to generate
194// the key
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200195func GenerateSafeKey(size uint16) ([]byte, error) {
196 lock.Lock()
197 defer lock.Unlock()
198 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200199 return nil, ErrNotInitialized
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200200 }
201 encryptionKeyHost := make([]byte, size)
202 if _, err := io.ReadFull(rand.Reader, encryptionKeyHost); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200203 return nil, fmt.Errorf("failed to generate host portion of new key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200204 }
205 var encryptionKeyTPM []byte
206 for i := 48; i > 0; i-- {
207 tpmKeyPart, err := tpm2.GetRandom(tpm.device, size-uint16(len(encryptionKeyTPM)))
208 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200209 return nil, fmt.Errorf("failed to generate TPM portion of new key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200210 }
211 encryptionKeyTPM = append(encryptionKeyTPM, tpmKeyPart...)
212 if len(encryptionKeyTPM) >= int(size) {
213 break
214 }
215 }
216
217 if len(encryptionKeyTPM) != int(size) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200218 return nil, fmt.Errorf("got incorrect amount of TPM randomess: %v, requested %v", len(encryptionKeyTPM), size)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200219 }
220
221 encryptionKey := make([]byte, size)
222 for i := uint16(0); i < size; i++ {
223 encryptionKey[i] = encryptionKeyHost[i] ^ encryptionKeyTPM[i]
224 }
225 return encryptionKey, nil
226}
227
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200228// Seal seals sensitive data and only allows access if the current platform
229// configuration in matches the one the data was sealed on.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200230func Seal(data []byte, pcrs []int) ([]byte, error) {
Lorenz Brun662182f2022-03-10 14:06:48 +0100231 // Generate a key and use secretbox to encrypt and authenticate the actual
232 // payload as go-tpm2 uses a raw seal operation limiting payload size to
233 // 128 bytes which is insufficient.
234 boxKey, err := GenerateSafeKey(32)
235 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200236 return nil, fmt.Errorf("failed to generate boxKey: %w", err)
Lorenz Brun662182f2022-03-10 14:06:48 +0100237 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200238 lock.Lock()
239 defer lock.Unlock()
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200240 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
241 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200242 return nil, fmt.Errorf("failed to load TPM SRK: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200243 }
244 defer srk.Close()
Lorenz Brun662182f2022-03-10 14:06:48 +0100245 var boxKeyArr [32]byte
246 copy(boxKeyArr[:], boxKey)
247 // Nonce is not used as we're generating a new boxKey for every operation,
248 // therefore we can just leave it all-zero.
249 var unusedNonce [24]byte
250 encryptedData := secretbox.Seal(nil, data, &unusedNonce, &boxKeyArr)
Lorenz Brund13c1c62022-03-30 19:58:58 +0200251 sealedKey, err := srk.Seal(boxKey, tpm2tools.SealOpts{Current: tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: pcrs}})
Lorenz Brun662182f2022-03-10 14:06:48 +0100252 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200253 return nil, fmt.Errorf("failed to seal boxKey: %w", err)
Lorenz Brun662182f2022-03-10 14:06:48 +0100254 }
255 sealedBytes := tpmpb.ExtendedSealedBytes{
256 SealedKey: sealedKey,
257 EncryptedPayload: encryptedData,
258 }
259 rawSealedBytes, err := proto.Marshal(&sealedBytes)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200260 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200261 return nil, fmt.Errorf("failed to marshal sealed data: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200262 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100263 return rawSealedBytes, nil
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200264}
265
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200266// Unseal unseals sensitive data if the current platform configuration allows
267// and sealing constraints allow it.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200268func Unseal(data []byte) ([]byte, error) {
269 lock.Lock()
270 defer lock.Unlock()
271 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200272 return nil, ErrNotInitialized
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200273 }
274 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
275 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200276 return nil, fmt.Errorf("failed to load TPM SRK: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200277 }
278 defer srk.Close()
279
Lorenz Brun662182f2022-03-10 14:06:48 +0100280 var sealedBytes tpmpb.ExtendedSealedBytes
281 if err := proto.Unmarshal(data, &sealedBytes); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200282 return nil, fmt.Errorf("failed to unmarshal sealed data: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200283 }
Lorenz Bruned6bcac2022-05-04 17:39:41 +0200284 if sealedBytes.SealedKey == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200285 return nil, fmt.Errorf("sealed data structure is invalid: no sealed key")
Lorenz Bruned6bcac2022-05-04 17:39:41 +0200286 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200287 // Logging this for auditing purposes
Tim Windelschmidtbda384c2024-04-11 01:41:57 +0200288 var pcrList []string
Lorenz Brun662182f2022-03-10 14:06:48 +0100289 for _, pcr := range sealedBytes.SealedKey.Pcrs {
Lorenz Brun800e7c92023-07-12 22:37:39 +0200290 pcrList = append(pcrList, strconv.FormatUint(uint64(pcr), 10))
Serge Bazanskic7359672020-10-30 16:38:57 +0100291 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100292 tpm.logger.Infof("Attempting to unseal key protected with PCRs %s", strings.Join(pcrList, ","))
Lorenz Brund13c1c62022-03-30 19:58:58 +0200293 unsealedKey, err := srk.Unseal(sealedBytes.SealedKey, tpm2tools.UnsealOpts{})
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200294 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200295 return nil, fmt.Errorf("failed to unseal key: %w", err)
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200296 }
Lorenz Brun662182f2022-03-10 14:06:48 +0100297 var key [32]byte
298 if len(unsealedKey) != len(key) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200299 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 +0100300 }
301 copy(key[:], unsealedKey)
302 var unusedNonce [24]byte
303 payload, ok := secretbox.Open(nil, sealedBytes.EncryptedPayload, &unusedNonce, &key)
304 if !ok {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200305 return nil, errors.New("payload box cannot be opened")
Lorenz Brun662182f2022-03-10 14:06:48 +0100306 }
307 return payload, nil
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200308}
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100309
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200310// Standard AK template for RSA2048 non-duplicatable restricted signing for
311// attestation
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100312var akTemplate = tpm2.Public{
313 Type: tpm2.AlgRSA,
314 NameAlg: tpm2.AlgSHA256,
315 Attributes: tpm2.FlagSignerDefault,
316 RSAParameters: &tpm2.RSAParams{
317 Sign: &tpm2.SigScheme{
318 Alg: tpm2.AlgRSASSA,
319 Hash: tpm2.AlgSHA256,
320 },
321 KeyBits: 2048,
322 },
323}
324
325func loadAK() error {
326 var err error
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200327 // Rationale: The AK is an EK-equivalent key and used only for attestation.
328 // Using a non-primary key here would require us to store the wrapped
329 // version somewhere, which is inconvenient. This being a primary key in
330 // the Endorsement hierarchy means that it can always be recreated and can
331 // never be "destroyed". Under our security model this is of no concern
332 // since we identify a node by its IK (Identity Key) which we can destroy.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100333 tpm.akHandleCache, tpm.akPublicKey, err = tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
334 tpm2.PCRSelection{}, "", "", akTemplate)
335 return err
336}
337
338// Process documented in TCG EK Credential Profile 2.2.1
339func loadEK() (tpmutil.Handle, crypto.PublicKey, error) {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200340 // The EK is a primary key which is supposed to be certified by the
341 // manufacturer of the TPM. Its public attributes are standardized in TCG
342 // EK Credential Profile 2.0 Table 1. These need to match exactly or we
343 // aren't getting the key the manufacturere signed. tpm2tools contains such
344 // a template already, so we're using that instead of redoing it ourselves.
345 // This ignores the more complicated ways EKs can be specified, the
346 // additional stuff you can do is just absolutely crazy (see 2.2.1.2
347 // onward)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100348 return tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
349 tpm2.PCRSelection{}, "", "", tpm2tools.DefaultEKTemplateRSA())
350}
351
352// GetAKPublic gets the TPM2T_PUBLIC of the AK key
353func GetAKPublic() ([]byte, error) {
354 lock.Lock()
355 defer lock.Unlock()
356 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200357 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100358 }
359 if tpm.akHandleCache == tpmutil.Handle(0) {
360 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200361 return nil, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100362 }
363 }
364 public, _, _, err := tpm2.ReadPublic(tpm.device, tpm.akHandleCache)
365 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200366 return nil, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100367 }
368 return public.Encode()
369}
370
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200371// TCG TPM v2.0 Provisioning Guidance v1.0 7.8 Table 2 and TCG EK Credential
372// Profile v2.1 2.2.1.4 de-facto Standard for Windows These are both
373// non-normative and reference Windows 10 documentation that's no longer
374// available :( But in practice this is what people are using, so if it's
375// normative or not doesn't really matter
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100376const ekCertHandle = 0x01c00002
377
378// GetEKPublic gets the public key and (if available) Certificate of the EK
379func GetEKPublic() ([]byte, []byte, error) {
380 lock.Lock()
381 defer lock.Unlock()
382 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200383 return nil, []byte{}, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100384 }
385 ekHandle, publicRaw, err := loadEK()
386 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200387 return nil, []byte{}, fmt.Errorf("failed to load EK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100388 }
389 defer tpm2.FlushContext(tpm.device, ekHandle)
390 // Don't question the use of HandleOwner, that's the Standardâ„¢
391 ekCertRaw, err := tpm2.NVReadEx(tpm.device, ekCertHandle, tpm2.HandleOwner, "", 0)
392 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200393 return nil, []byte{}, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100394 }
395
396 publicKey, err := x509.MarshalPKIXPublicKey(publicRaw)
397 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200398 return nil, []byte{}, err
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100399 }
400
401 return publicKey, ekCertRaw, nil
402}
403
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200404// MakeAKChallenge generates a challenge for TPM residency and attributes of
405// the AK
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100406func MakeAKChallenge(ekPubKey, akPub []byte, nonce []byte) ([]byte, []byte, error) {
407 ekPubKeyData, err := x509.ParsePKIXPublicKey(ekPubKey)
408 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200409 return nil, []byte{}, fmt.Errorf("failed to decode EK pubkey: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100410 }
411 akPubData, err := tpm2.DecodePublic(akPub)
412 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200413 return nil, []byte{}, fmt.Errorf("failed to decode AK public part: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100414 }
415 // Make sure we're attesting the right attributes (in particular Restricted)
416 if !akPubData.MatchesTemplate(akTemplate) {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200417 return nil, []byte{}, errors.New("the key being challenged is not a valid AK")
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100418 }
419 akName, err := akPubData.Name()
420 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200421 return nil, []byte{}, fmt.Errorf("failed to derive AK name: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100422 }
423 return generateRSA(akName.Digest, ekPubKeyData.(*rsa.PublicKey), 16, nonce, rand.Reader)
424}
425
426// SolveAKChallenge solves a challenge for TPM residency of the AK
427func SolveAKChallenge(credBlob, secretChallenge []byte) ([]byte, error) {
428 lock.Lock()
429 defer lock.Unlock()
430 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200431 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100432 }
433 if tpm.akHandleCache == tpmutil.Handle(0) {
434 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200435 return nil, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100436 }
437 }
438
439 ekHandle, _, err := loadEK()
440 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200441 return nil, fmt.Errorf("failed to load EK: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100442 }
443 defer tpm2.FlushContext(tpm.device, ekHandle)
444
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200445 // This is necessary since the EK requires an endorsement handle policy in
446 // its session. For us this is stupid because we keep all hierarchies open
447 // anyways since a) we cannot safely store secrets on the OS side
448 // pre-global unlock and b) it makes no sense in this security model since
449 // an uncompromised host OS will not let an untrusted entity attest as
450 // itself and a compromised OS can either not pass PCR policy checks or the
451 // game's already over (you successfully runtime-exploited a production
452 // Metropolis node).
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100453 endorsementSession, _, err := tpm2.StartAuthSession(
454 tpm.device,
455 tpm2.HandleNull,
456 tpm2.HandleNull,
457 make([]byte, 16),
458 nil,
459 tpm2.SessionPolicy,
460 tpm2.AlgNull,
461 tpm2.AlgSHA256)
462 if err != nil {
463 panic(err)
464 }
465 defer tpm2.FlushContext(tpm.device, endorsementSession)
466
Lorenz Brund13c1c62022-03-30 19:58:58 +0200467 _, _, 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 +0100468 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200469 return nil, fmt.Errorf("failed to make a policy secret session: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100470 }
471
472 for {
473 solution, err := tpm2.ActivateCredentialUsingAuth(tpm.device, []tpm2.AuthCommand{
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200474 // Use standard no-password authenatication
475 {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession},
476 // Use a full policy session for the EK
477 {Session: endorsementSession, Attributes: tpm2.AttrContinueSession},
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100478 }, tpm.akHandleCache, ekHandle, credBlob, secretChallenge)
Tim Windelschmidtaf821c82024-04-23 15:03:52 +0200479 var warn tpm2.Warning
480 if errors.As(err, &warn) && warn.Code == tpm2.RCRetry {
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100481 time.Sleep(100 * time.Millisecond)
482 continue
483 }
484 return solution, err
485 }
486}
487
488// FlushTransientHandles flushes all sessions and non-persistent handles
489func FlushTransientHandles() error {
490 lock.Lock()
491 defer lock.Unlock()
492 if tpm == nil {
493 return ErrNotInitialized
494 }
495 flushHandleTypes := []tpm2.HandleType{tpm2.HandleTypeTransient, tpm2.HandleTypeLoadedSession, tpm2.HandleTypeSavedSession}
496 for _, handleType := range flushHandleTypes {
497 handles, err := tpm2tools.Handles(tpm.device, handleType)
498 if err != nil {
499 return err
500 }
501 for _, handle := range handles {
502 if err := tpm2.FlushContext(tpm.device, handle); err != nil {
503 return err
504 }
505 }
506 }
507 return nil
508}
509
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200510// AttestPlatform performs a PCR quote using the AK and returns the quote and
511// its signature
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100512func AttestPlatform(nonce []byte) ([]byte, []byte, error) {
513 lock.Lock()
514 defer lock.Unlock()
515 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200516 return nil, []byte{}, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100517 }
518 if tpm.akHandleCache == tpmutil.Handle(0) {
519 if err := loadAK(); err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200520 return nil, []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100521 }
522 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200523 // We only care about SHA256 since SHA1 is weak. This is supported on at
524 // least GCE and Intel / AMD fTPM, which is good enough for now. Alg is
525 // null because that would just hash the nonce, which is dumb.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100526 quote, signature, err := tpm2.Quote(tpm.device, tpm.akHandleCache, "", "", nonce, srtmPCRs,
527 tpm2.AlgNull)
528 if err != nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200529 return nil, []byte{}, fmt.Errorf("failed to quote PCRs: %w", err)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100530 }
531 return quote, signature.RSA.Signature, err
532}
533
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200534// VerifyAttestPlatform verifies a given attestation. You can rely on all data
535// coming back as being from the TPM on which the AK is bound to.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100536func VerifyAttestPlatform(nonce, akPub, quote, signature []byte) (*tpm2.AttestationData, error) {
537 hash := crypto.SHA256.New()
538 hash.Write(quote)
539
540 akPubData, err := tpm2.DecodePublic(akPub)
541 if err != nil {
542 return nil, fmt.Errorf("invalid AK: %w", err)
543 }
544 akPublicKey, err := akPubData.Key()
545 if err != nil {
546 return nil, fmt.Errorf("invalid AK: %w", err)
547 }
548 akRSAKey, ok := akPublicKey.(*rsa.PublicKey)
549 if !ok {
550 return nil, errors.New("invalid AK: invalid key type")
551 }
552
553 if err := rsa.VerifyPKCS1v15(akRSAKey, crypto.SHA256, hash.Sum(nil), signature); err != nil {
554 return nil, err
555 }
556
557 quoteData, err := tpm2.DecodeAttestationData(quote)
558 if err != nil {
559 return nil, err
560 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200561 // quoteData.Magic works together with the TPM's Restricted key attribute.
562 // If this attribute is set (which it needs to be for the AK to be
563 // considered valid) the TPM will not sign external data having this prefix
564 // with such a key. Only data that originates inside the TPM like quotes
565 // and key certifications can have this prefix and sill be signed by a
566 // restricted key. This check is thus vital, otherwise somebody can just
567 // feed the TPM an arbitrary attestation to sign with its AK and this
568 // function will happily accept the forged attestation.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100569 if quoteData.Magic != tpmGeneratedValue {
570 return nil, errors.New("invalid TPM quote: data marker for internal data not set - forged attestation")
571 }
572 if quoteData.Type != tpm2.TagAttestQuote {
573 return nil, errors.New("invalid TPM qoute: not a TPM quote")
574 }
575 if !bytes.Equal(quoteData.ExtraData, nonce) {
576 return nil, errors.New("invalid TPM quote: wrong nonce")
577 }
578
579 return quoteData, nil
580}
581
582// GetPCRs returns all SRTM PCRs in-order
583func GetPCRs() ([][]byte, error) {
584 lock.Lock()
585 defer lock.Unlock()
586 if tpm == nil {
Tim Windelschmidt3074ec62024-04-23 15:08:05 +0200587 return nil, ErrNotInitialized
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100588 }
589 pcrs := make([][]byte, numSRTMPCRs)
590
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200591 // The TPM can (and most do) return partial results. Let's just retry as
592 // many times as we have PCRs since each read should return at least one
593 // PCR.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100594readLoop:
595 for i := 0; i < numSRTMPCRs; i++ {
596 sel := tpm2.PCRSelection{Hash: tpm2.AlgSHA256}
597 for pcrN := 0; pcrN < numSRTMPCRs; pcrN++ {
598 if len(pcrs[pcrN]) == 0 {
599 sel.PCRs = append(sel.PCRs, pcrN)
600 }
601 }
602
603 readPCRs, err := tpm2.ReadPCRs(tpm.device, sel)
604 if err != nil {
605 return nil, fmt.Errorf("failed to read PCRs: %w", err)
606 }
607
608 for pcrN, pcr := range readPCRs {
609 pcrs[pcrN] = pcr
610 }
611 for _, pcr := range pcrs {
612 // If at least one PCR is still not read, continue
613 if len(pcr) == 0 {
614 continue readLoop
615 }
616 }
617 break
618 }
619
620 return pcrs, nil
621}
Lorenz Bruna50e8452020-09-09 17:09:27 +0200622
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200623// GetMeasurmentLog returns the binary log of all data hashed into PCRs. The
624// result can be parsed by eventlog. As this library currently doesn't support
625// extending PCRs it just returns the log as supplied by the EFI interface.
Lorenz Bruna50e8452020-09-09 17:09:27 +0200626func GetMeasurementLog() ([]byte, error) {
Lorenz Brun764a2de2021-11-22 16:26:36 +0100627 return os.ReadFile("/sys/kernel/security/tpm0/binary_bios_measurements")
Lorenz Bruna50e8452020-09-09 17:09:27 +0200628}