blob: de9b0d86f6c2f4e60b313a0156750b4ac479feea [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"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020025 "fmt"
26 "io"
27 "os"
28 "path/filepath"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020029 "strconv"
Serge Bazanskic7359672020-10-30 16:38:57 +010030 "strings"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020031 "sync"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010032 "time"
33
Lorenz Brunae0d90d2019-09-05 17:53:56 +020034 "github.com/gogo/protobuf/proto"
35 tpmpb "github.com/google/go-tpm-tools/proto"
36 "github.com/google/go-tpm-tools/tpm2tools"
37 "github.com/google/go-tpm/tpm2"
Lorenz Brunaa6b7342019-12-12 02:55:02 +010038 "github.com/google/go-tpm/tpmutil"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020039 "github.com/pkg/errors"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020040 "golang.org/x/sys/unix"
Serge Bazanski77cb6c52020-12-19 00:09:22 +010041
Serge Bazanski31370b02021-01-07 16:31:14 +010042 "source.monogon.dev/metropolis/pkg/logtree"
43 "source.monogon.dev/metropolis/pkg/sysfs"
Lorenz Brunae0d90d2019-09-05 17:53:56 +020044)
45
46var (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020047 // SecureBootPCRs are all PCRs that measure the current Secure Boot
48 // configuration. This is what we want if we rely on secure boot to verify
49 // boot integrity. The firmware hashes the secure boot policy and custom
50 // keys into the PCR.
Leopold Schabel68c58752019-11-14 21:00:59 +010051 //
52 // This requires an extra step that provisions the custom keys.
53 //
54 // Some background: https://mjg59.dreamwidth.org/48897.html?thread=1847297
Serge Bazanski216fe7b2021-05-21 18:36:16 +020055 // (the initramfs issue mentioned in the article has been solved by
56 // integrating it into the kernel binary, and we don't have a shim
57 // bootloader)
Leopold Schabel68c58752019-11-14 21:00:59 +010058 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020059 // PCR7 alone is not sufficient - it needs to be combined with firmware
60 // measurements.
Lorenz Brunae0d90d2019-09-05 17:53:56 +020061 SecureBootPCRs = []int{7}
62
Serge Bazanski216fe7b2021-05-21 18:36:16 +020063 // FirmwarePCRs are alle PCRs that contain the firmware measurements. See:
64 // https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf
Leopold Schabel68c58752019-11-14 21:00:59 +010065 FirmwarePCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010066 0, // platform firmware
67 2, // option ROM code
68 3, // option ROM configuration and data
Leopold Schabel68c58752019-11-14 21:00:59 +010069 }
Lorenz Brunae0d90d2019-09-05 17:53:56 +020070
Serge Bazanski216fe7b2021-05-21 18:36:16 +020071 // FullSystemPCRs are all PCRs that contain any measurements up to the
72 // currently running EFI payload.
Leopold Schabel68c58752019-11-14 21:00:59 +010073 FullSystemPCRs = []int{
Lorenz Brunaa6b7342019-12-12 02:55:02 +010074 0, // platform firmware
75 1, // host platform configuration
76 2, // option ROM code
77 3, // option ROM configuration and data
78 4, // EFI payload
Leopold Schabel68c58752019-11-14 21:00:59 +010079 }
80
Serge Bazanski216fe7b2021-05-21 18:36:16 +020081 // Using FullSystemPCRs is the most secure, but also the most brittle
82 // option since updating the EFI binary, updating the platform firmware,
83 // changing platform settings or updating the binary would invalidate the
84 // sealed data. It's annoying (but possible) to predict values for PCR4,
85 // and even more annoying for the firmware PCR (comparison to known values
86 // on similar hardware is the only thing that comes to mind).
Leopold Schabel68c58752019-11-14 21:00:59 +010087 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020088 // See also: https://github.com/mxre/sealkey (generates PCR4 from EFI
89 // image, BSD license)
Leopold Schabel68c58752019-11-14 21:00:59 +010090 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020091 // Using only SecureBootPCRs is the easiest and still reasonably secure, if
92 // we assume that the platform knows how to take care of itself (i.e. Intel
93 // Boot Guard), and that secure boot is implemented properly. It is,
94 // however, a much larger amount of code we need to trust.
Leopold Schabel68c58752019-11-14 21:00:59 +010095 //
Serge Bazanski216fe7b2021-05-21 18:36:16 +020096 // We do not care about PCR 5 (GPT partition table) since modifying it is
97 // harmless. All of the boot options and cmdline are hardcoded in the
98 // kernel image, and we use no bootloader, so there's no PCR for bootloader
99 // configuration or kernel cmdline.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200100)
101
102var (
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100103 numSRTMPCRs = 16
104 srtmPCRs = tpm2.PCRSelection{Hash: tpm2.AlgSHA256, PCRs: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}}
105 // TCG Trusted Platform Module Library Level 00 Revision 0.99 Table 6
106 tpmGeneratedValue = uint32(0xff544347)
107)
108
109var (
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200110 // ErrNotExists is returned when no TPMs are available in the system
111 ErrNotExists = errors.New("no TPMs found")
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200112 // ErrNotInitialized is returned when this package was not initialized
113 // successfully
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200114 ErrNotInitialized = errors.New("no TPM was initialized")
115)
116
117// Singleton since the TPM is too
118var tpm *TPM
119
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200120// We're serializing all TPM operations since it has a limited number of
121// handles and recovering if it runs out is difficult to implement correctly.
122// Might also be marginally more secure.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200123var lock sync.Mutex
124
125// TPM represents a high-level interface to a connected TPM 2.0
126type TPM struct {
Serge Bazanskic7359672020-10-30 16:38:57 +0100127 logger logtree.LeveledLogger
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200128 device io.ReadWriteCloser
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100129
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200130 // We keep the AK loaded since it's used fairly often and deriving it is
131 // expensive
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100132 akHandleCache tpmutil.Handle
133 akPublicKey crypto.PublicKey
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200134}
135
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200136// Initialize finds and opens the TPM (if any). If there is no TPM available it
137// returns ErrNotExists
Serge Bazanskic7359672020-10-30 16:38:57 +0100138func Initialize(logger logtree.LeveledLogger) error {
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200139 lock.Lock()
140 defer lock.Unlock()
141 tpmDir, err := os.Open("/sys/class/tpm")
142 if err != nil {
143 return errors.Wrap(err, "failed to open sysfs TPM class")
144 }
145 defer tpmDir.Close()
146
147 tpms, err := tpmDir.Readdirnames(2)
148 if err != nil {
149 return errors.Wrap(err, "failed to read TPM device class")
150 }
151
152 if len(tpms) == 0 {
153 return ErrNotExists
154 }
155 if len(tpms) > 1 {
Lorenz Bruna50e8452020-09-09 17:09:27 +0200156 // If this is changed GetMeasurementLog() needs to be updated too
Serge Bazanskic7359672020-10-30 16:38:57 +0100157 logger.Warningf("Found more than one TPM, using the first one")
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200158 }
159 tpmName := tpms[0]
160 ueventData, err := sysfs.ReadUevents(filepath.Join("/sys/class/tpm", tpmName, "uevent"))
161 majorDev, err := strconv.Atoi(ueventData["MAJOR"])
162 if err != nil {
163 return fmt.Errorf("failed to convert uevent: %w", err)
164 }
165 minorDev, err := strconv.Atoi(ueventData["MINOR"])
166 if err != nil {
167 return fmt.Errorf("failed to convert uevent: %w", err)
168 }
169 if err := unix.Mknod("/dev/tpm", 0600|unix.S_IFCHR, int(unix.Mkdev(uint32(majorDev), uint32(minorDev)))); err != nil {
170 return errors.Wrap(err, "failed to create TPM device node")
171 }
172 device, err := tpm2.OpenTPM("/dev/tpm")
173 if err != nil {
174 return errors.Wrap(err, "failed to open TPM")
175 }
176 tpm = &TPM{
177 device: device,
178 logger: logger,
179 }
180 return nil
181}
182
Lorenz Brun8b786892022-01-13 14:21:16 +0100183// IsInitialized returns true if Initialize was called an at least one
184// TPM 2.0 was found and initialized. Otherwise it returns false.
185func IsInitialized() bool {
186 lock.Lock()
187 defer lock.Unlock()
188 return !(tpm == nil)
189}
190
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200191// GenerateSafeKey uses two sources of randomness (Kernel & TPM) to generate
192// the key
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200193func GenerateSafeKey(size uint16) ([]byte, error) {
194 lock.Lock()
195 defer lock.Unlock()
196 if tpm == nil {
197 return []byte{}, ErrNotInitialized
198 }
199 encryptionKeyHost := make([]byte, size)
200 if _, err := io.ReadFull(rand.Reader, encryptionKeyHost); err != nil {
201 return []byte{}, errors.Wrap(err, "failed to generate host portion of new key")
202 }
203 var encryptionKeyTPM []byte
204 for i := 48; i > 0; i-- {
205 tpmKeyPart, err := tpm2.GetRandom(tpm.device, size-uint16(len(encryptionKeyTPM)))
206 if err != nil {
207 return []byte{}, errors.Wrap(err, "failed to generate TPM portion of new key")
208 }
209 encryptionKeyTPM = append(encryptionKeyTPM, tpmKeyPart...)
210 if len(encryptionKeyTPM) >= int(size) {
211 break
212 }
213 }
214
215 if len(encryptionKeyTPM) != int(size) {
216 return []byte{}, fmt.Errorf("got incorrect amount of TPM randomess: %v, requested %v", len(encryptionKeyTPM), size)
217 }
218
219 encryptionKey := make([]byte, size)
220 for i := uint16(0); i < size; i++ {
221 encryptionKey[i] = encryptionKeyHost[i] ^ encryptionKeyTPM[i]
222 }
223 return encryptionKey, nil
224}
225
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200226// Seal seals sensitive data and only allows access if the current platform
227// configuration in matches the one the data was sealed on.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200228func Seal(data []byte, pcrs []int) ([]byte, error) {
229 lock.Lock()
230 defer lock.Unlock()
231 if tpm == nil {
232 return []byte{}, ErrNotInitialized
233 }
234 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
235 if err != nil {
236 return []byte{}, errors.Wrap(err, "failed to load TPM SRK")
237 }
238 defer srk.Close()
239 sealedKey, err := srk.Seal(pcrs, data)
240 sealedKeyRaw, err := proto.Marshal(sealedKey)
241 if err != nil {
242 return []byte{}, errors.Wrapf(err, "failed to marshal sealed data")
243 }
244 return sealedKeyRaw, nil
245}
246
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200247// Unseal unseals sensitive data if the current platform configuration allows
248// and sealing constraints allow it.
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200249func Unseal(data []byte) ([]byte, error) {
250 lock.Lock()
251 defer lock.Unlock()
252 if tpm == nil {
253 return []byte{}, ErrNotInitialized
254 }
255 srk, err := tpm2tools.StorageRootKeyRSA(tpm.device)
256 if err != nil {
257 return []byte{}, errors.Wrap(err, "failed to load TPM SRK")
258 }
259 defer srk.Close()
260
261 var sealedKey tpmpb.SealedBytes
262 if err := proto.Unmarshal(data, &sealedKey); err != nil {
263 return []byte{}, errors.Wrap(err, "failed to decode sealed data")
264 }
265 // Logging this for auditing purposes
Serge Bazanskic7359672020-10-30 16:38:57 +0100266 pcrList := []string{}
267 for _, pcr := range sealedKey.Pcrs {
268 pcrList = append(pcrList, string(pcr))
269 }
270 tpm.logger.Infof("Attempting to unseal data protected with PCRs %s", strings.Join(pcrList, ","))
Lorenz Brunae0d90d2019-09-05 17:53:56 +0200271 unsealedData, err := srk.Unseal(&sealedKey)
272 if err != nil {
273 return []byte{}, errors.Wrap(err, "failed to unseal data")
274 }
275 return unsealedData, nil
276}
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100277
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200278// Standard AK template for RSA2048 non-duplicatable restricted signing for
279// attestation
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100280var akTemplate = tpm2.Public{
281 Type: tpm2.AlgRSA,
282 NameAlg: tpm2.AlgSHA256,
283 Attributes: tpm2.FlagSignerDefault,
284 RSAParameters: &tpm2.RSAParams{
285 Sign: &tpm2.SigScheme{
286 Alg: tpm2.AlgRSASSA,
287 Hash: tpm2.AlgSHA256,
288 },
289 KeyBits: 2048,
290 },
291}
292
293func loadAK() error {
294 var err error
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200295 // Rationale: The AK is an EK-equivalent key and used only for attestation.
296 // Using a non-primary key here would require us to store the wrapped
297 // version somewhere, which is inconvenient. This being a primary key in
298 // the Endorsement hierarchy means that it can always be recreated and can
299 // never be "destroyed". Under our security model this is of no concern
300 // since we identify a node by its IK (Identity Key) which we can destroy.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100301 tpm.akHandleCache, tpm.akPublicKey, err = tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
302 tpm2.PCRSelection{}, "", "", akTemplate)
303 return err
304}
305
306// Process documented in TCG EK Credential Profile 2.2.1
307func loadEK() (tpmutil.Handle, crypto.PublicKey, error) {
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200308 // The EK is a primary key which is supposed to be certified by the
309 // manufacturer of the TPM. Its public attributes are standardized in TCG
310 // EK Credential Profile 2.0 Table 1. These need to match exactly or we
311 // aren't getting the key the manufacturere signed. tpm2tools contains such
312 // a template already, so we're using that instead of redoing it ourselves.
313 // This ignores the more complicated ways EKs can be specified, the
314 // additional stuff you can do is just absolutely crazy (see 2.2.1.2
315 // onward)
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100316 return tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
317 tpm2.PCRSelection{}, "", "", tpm2tools.DefaultEKTemplateRSA())
318}
319
320// GetAKPublic gets the TPM2T_PUBLIC of the AK key
321func GetAKPublic() ([]byte, error) {
322 lock.Lock()
323 defer lock.Unlock()
324 if tpm == nil {
325 return []byte{}, ErrNotInitialized
326 }
327 if tpm.akHandleCache == tpmutil.Handle(0) {
328 if err := loadAK(); err != nil {
329 return []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
330 }
331 }
332 public, _, _, err := tpm2.ReadPublic(tpm.device, tpm.akHandleCache)
333 if err != nil {
334 return []byte{}, err
335 }
336 return public.Encode()
337}
338
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200339// TCG TPM v2.0 Provisioning Guidance v1.0 7.8 Table 2 and TCG EK Credential
340// Profile v2.1 2.2.1.4 de-facto Standard for Windows These are both
341// non-normative and reference Windows 10 documentation that's no longer
342// available :( But in practice this is what people are using, so if it's
343// normative or not doesn't really matter
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100344const ekCertHandle = 0x01c00002
345
346// GetEKPublic gets the public key and (if available) Certificate of the EK
347func GetEKPublic() ([]byte, []byte, error) {
348 lock.Lock()
349 defer lock.Unlock()
350 if tpm == nil {
351 return []byte{}, []byte{}, ErrNotInitialized
352 }
353 ekHandle, publicRaw, err := loadEK()
354 if err != nil {
355 return []byte{}, []byte{}, fmt.Errorf("failed to load EK primary key: %w", err)
356 }
357 defer tpm2.FlushContext(tpm.device, ekHandle)
358 // Don't question the use of HandleOwner, that's the Standardâ„¢
359 ekCertRaw, err := tpm2.NVReadEx(tpm.device, ekCertHandle, tpm2.HandleOwner, "", 0)
360 if err != nil {
361 return []byte{}, []byte{}, err
362 }
363
364 publicKey, err := x509.MarshalPKIXPublicKey(publicRaw)
365 if err != nil {
366 return []byte{}, []byte{}, err
367 }
368
369 return publicKey, ekCertRaw, nil
370}
371
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200372// MakeAKChallenge generates a challenge for TPM residency and attributes of
373// the AK
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100374func MakeAKChallenge(ekPubKey, akPub []byte, nonce []byte) ([]byte, []byte, error) {
375 ekPubKeyData, err := x509.ParsePKIXPublicKey(ekPubKey)
376 if err != nil {
377 return []byte{}, []byte{}, fmt.Errorf("failed to decode EK pubkey: %w", err)
378 }
379 akPubData, err := tpm2.DecodePublic(akPub)
380 if err != nil {
381 return []byte{}, []byte{}, fmt.Errorf("failed to decode AK public part: %w", err)
382 }
383 // Make sure we're attesting the right attributes (in particular Restricted)
384 if !akPubData.MatchesTemplate(akTemplate) {
385 return []byte{}, []byte{}, errors.New("the key being challenged is not a valid AK")
386 }
387 akName, err := akPubData.Name()
388 if err != nil {
389 return []byte{}, []byte{}, fmt.Errorf("failed to derive AK name: %w", err)
390 }
391 return generateRSA(akName.Digest, ekPubKeyData.(*rsa.PublicKey), 16, nonce, rand.Reader)
392}
393
394// SolveAKChallenge solves a challenge for TPM residency of the AK
395func SolveAKChallenge(credBlob, secretChallenge []byte) ([]byte, error) {
396 lock.Lock()
397 defer lock.Unlock()
398 if tpm == nil {
399 return []byte{}, ErrNotInitialized
400 }
401 if tpm.akHandleCache == tpmutil.Handle(0) {
402 if err := loadAK(); err != nil {
403 return []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
404 }
405 }
406
407 ekHandle, _, err := loadEK()
408 if err != nil {
409 return []byte{}, fmt.Errorf("failed to load EK: %w", err)
410 }
411 defer tpm2.FlushContext(tpm.device, ekHandle)
412
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200413 // This is necessary since the EK requires an endorsement handle policy in
414 // its session. For us this is stupid because we keep all hierarchies open
415 // anyways since a) we cannot safely store secrets on the OS side
416 // pre-global unlock and b) it makes no sense in this security model since
417 // an uncompromised host OS will not let an untrusted entity attest as
418 // itself and a compromised OS can either not pass PCR policy checks or the
419 // game's already over (you successfully runtime-exploited a production
420 // Metropolis node).
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100421 endorsementSession, _, err := tpm2.StartAuthSession(
422 tpm.device,
423 tpm2.HandleNull,
424 tpm2.HandleNull,
425 make([]byte, 16),
426 nil,
427 tpm2.SessionPolicy,
428 tpm2.AlgNull,
429 tpm2.AlgSHA256)
430 if err != nil {
431 panic(err)
432 }
433 defer tpm2.FlushContext(tpm.device, endorsementSession)
434
435 _, err = tpm2.PolicySecret(tpm.device, tpm2.HandleEndorsement, tpm2.AuthCommand{Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}, endorsementSession, nil, nil, nil, 0)
436 if err != nil {
437 return []byte{}, fmt.Errorf("failed to make a policy secret session: %w", err)
438 }
439
440 for {
441 solution, err := tpm2.ActivateCredentialUsingAuth(tpm.device, []tpm2.AuthCommand{
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200442 // Use standard no-password authenatication
443 {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession},
444 // Use a full policy session for the EK
445 {Session: endorsementSession, Attributes: tpm2.AttrContinueSession},
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100446 }, tpm.akHandleCache, ekHandle, credBlob, secretChallenge)
447 if warn, ok := err.(tpm2.Warning); ok && warn.Code == tpm2.RCRetry {
448 time.Sleep(100 * time.Millisecond)
449 continue
450 }
451 return solution, err
452 }
453}
454
455// FlushTransientHandles flushes all sessions and non-persistent handles
456func FlushTransientHandles() error {
457 lock.Lock()
458 defer lock.Unlock()
459 if tpm == nil {
460 return ErrNotInitialized
461 }
462 flushHandleTypes := []tpm2.HandleType{tpm2.HandleTypeTransient, tpm2.HandleTypeLoadedSession, tpm2.HandleTypeSavedSession}
463 for _, handleType := range flushHandleTypes {
464 handles, err := tpm2tools.Handles(tpm.device, handleType)
465 if err != nil {
466 return err
467 }
468 for _, handle := range handles {
469 if err := tpm2.FlushContext(tpm.device, handle); err != nil {
470 return err
471 }
472 }
473 }
474 return nil
475}
476
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200477// AttestPlatform performs a PCR quote using the AK and returns the quote and
478// its signature
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100479func AttestPlatform(nonce []byte) ([]byte, []byte, error) {
480 lock.Lock()
481 defer lock.Unlock()
482 if tpm == nil {
483 return []byte{}, []byte{}, ErrNotInitialized
484 }
485 if tpm.akHandleCache == tpmutil.Handle(0) {
486 if err := loadAK(); err != nil {
487 return []byte{}, []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
488 }
489 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200490 // We only care about SHA256 since SHA1 is weak. This is supported on at
491 // least GCE and Intel / AMD fTPM, which is good enough for now. Alg is
492 // null because that would just hash the nonce, which is dumb.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100493 quote, signature, err := tpm2.Quote(tpm.device, tpm.akHandleCache, "", "", nonce, srtmPCRs,
494 tpm2.AlgNull)
495 if err != nil {
496 return []byte{}, []byte{}, fmt.Errorf("failed to quote PCRs: %w", err)
497 }
498 return quote, signature.RSA.Signature, err
499}
500
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200501// VerifyAttestPlatform verifies a given attestation. You can rely on all data
502// coming back as being from the TPM on which the AK is bound to.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100503func VerifyAttestPlatform(nonce, akPub, quote, signature []byte) (*tpm2.AttestationData, error) {
504 hash := crypto.SHA256.New()
505 hash.Write(quote)
506
507 akPubData, err := tpm2.DecodePublic(akPub)
508 if err != nil {
509 return nil, fmt.Errorf("invalid AK: %w", err)
510 }
511 akPublicKey, err := akPubData.Key()
512 if err != nil {
513 return nil, fmt.Errorf("invalid AK: %w", err)
514 }
515 akRSAKey, ok := akPublicKey.(*rsa.PublicKey)
516 if !ok {
517 return nil, errors.New("invalid AK: invalid key type")
518 }
519
520 if err := rsa.VerifyPKCS1v15(akRSAKey, crypto.SHA256, hash.Sum(nil), signature); err != nil {
521 return nil, err
522 }
523
524 quoteData, err := tpm2.DecodeAttestationData(quote)
525 if err != nil {
526 return nil, err
527 }
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200528 // quoteData.Magic works together with the TPM's Restricted key attribute.
529 // If this attribute is set (which it needs to be for the AK to be
530 // considered valid) the TPM will not sign external data having this prefix
531 // with such a key. Only data that originates inside the TPM like quotes
532 // and key certifications can have this prefix and sill be signed by a
533 // restricted key. This check is thus vital, otherwise somebody can just
534 // feed the TPM an arbitrary attestation to sign with its AK and this
535 // function will happily accept the forged attestation.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100536 if quoteData.Magic != tpmGeneratedValue {
537 return nil, errors.New("invalid TPM quote: data marker for internal data not set - forged attestation")
538 }
539 if quoteData.Type != tpm2.TagAttestQuote {
540 return nil, errors.New("invalid TPM qoute: not a TPM quote")
541 }
542 if !bytes.Equal(quoteData.ExtraData, nonce) {
543 return nil, errors.New("invalid TPM quote: wrong nonce")
544 }
545
546 return quoteData, nil
547}
548
549// GetPCRs returns all SRTM PCRs in-order
550func GetPCRs() ([][]byte, error) {
551 lock.Lock()
552 defer lock.Unlock()
553 if tpm == nil {
554 return [][]byte{}, ErrNotInitialized
555 }
556 pcrs := make([][]byte, numSRTMPCRs)
557
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200558 // The TPM can (and most do) return partial results. Let's just retry as
559 // many times as we have PCRs since each read should return at least one
560 // PCR.
Lorenz Brunaa6b7342019-12-12 02:55:02 +0100561readLoop:
562 for i := 0; i < numSRTMPCRs; i++ {
563 sel := tpm2.PCRSelection{Hash: tpm2.AlgSHA256}
564 for pcrN := 0; pcrN < numSRTMPCRs; pcrN++ {
565 if len(pcrs[pcrN]) == 0 {
566 sel.PCRs = append(sel.PCRs, pcrN)
567 }
568 }
569
570 readPCRs, err := tpm2.ReadPCRs(tpm.device, sel)
571 if err != nil {
572 return nil, fmt.Errorf("failed to read PCRs: %w", err)
573 }
574
575 for pcrN, pcr := range readPCRs {
576 pcrs[pcrN] = pcr
577 }
578 for _, pcr := range pcrs {
579 // If at least one PCR is still not read, continue
580 if len(pcr) == 0 {
581 continue readLoop
582 }
583 }
584 break
585 }
586
587 return pcrs, nil
588}
Lorenz Bruna50e8452020-09-09 17:09:27 +0200589
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200590// GetMeasurmentLog returns the binary log of all data hashed into PCRs. The
591// result can be parsed by eventlog. As this library currently doesn't support
592// extending PCRs it just returns the log as supplied by the EFI interface.
Lorenz Bruna50e8452020-09-09 17:09:27 +0200593func GetMeasurementLog() ([]byte, error) {
Lorenz Brun764a2de2021-11-22 16:26:36 +0100594 return os.ReadFile("/sys/kernel/security/tpm0/binary_bios_measurements")
Lorenz Bruna50e8452020-09-09 17:09:27 +0200595}