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