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