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