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