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