*: reflow comments to 80 characters
This reformats the entire Metropolis codebase to have comments no longer
than 80 characters, implementing CR/66.
This has been done half manually, as we don't have a good integration
between commentwrap/Bazel, but that can be implemented if we decide to
go for this tool/limit.
Change-Id: If1fff0b093ef806f5dc00551c11506e8290379d0
diff --git a/metropolis/pkg/tpm/tpm.go b/metropolis/pkg/tpm/tpm.go
index e650ff9..ab02dd3 100644
--- a/metropolis/pkg/tpm/tpm.go
+++ b/metropolis/pkg/tpm/tpm.go
@@ -45,28 +45,32 @@
)
var (
- // SecureBootPCRs are all PCRs that measure the current Secure Boot configuration.
- // This is what we want if we rely on secure boot to verify boot integrity. The firmware
- // hashes the secure boot policy and custom keys into the PCR.
+ // SecureBootPCRs are all PCRs that measure the current Secure Boot
+ // configuration. This is what we want if we rely on secure boot to verify
+ // boot integrity. The firmware hashes the secure boot policy and custom
+ // keys into the PCR.
//
// This requires an extra step that provisions the custom keys.
//
// Some background: https://mjg59.dreamwidth.org/48897.html?thread=1847297
- // (the initramfs issue mentioned in the article has been solved by integrating
- // it into the kernel binary, and we don't have a shim bootloader)
+ // (the initramfs issue mentioned in the article has been solved by
+ // integrating it into the kernel binary, and we don't have a shim
+ // bootloader)
//
- // PCR7 alone is not sufficient - it needs to be combined with firmware measurements.
+ // PCR7 alone is not sufficient - it needs to be combined with firmware
+ // measurements.
SecureBootPCRs = []int{7}
- // FirmwarePCRs are alle PCRs that contain the firmware measurements
- // See https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf
+ // FirmwarePCRs are alle PCRs that contain the firmware measurements. See:
+ // https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf
FirmwarePCRs = []int{
0, // platform firmware
2, // option ROM code
3, // option ROM configuration and data
}
- // FullSystemPCRs are all PCRs that contain any measurements up to the currently running EFI payload.
+ // FullSystemPCRs are all PCRs that contain any measurements up to the
+ // currently running EFI payload.
FullSystemPCRs = []int{
0, // platform firmware
1, // host platform configuration
@@ -75,21 +79,25 @@
4, // EFI payload
}
- // Using FullSystemPCRs is the most secure, but also the most brittle option since updating the EFI
- // binary, updating the platform firmware, changing platform settings or updating the binary
- // would invalidate the sealed data. It's annoying (but possible) to predict values for PCR4,
- // and even more annoying for the firmware PCR (comparison to known values on similar hardware
- // is the only thing that comes to mind).
+ // Using FullSystemPCRs is the most secure, but also the most brittle
+ // option since updating the EFI binary, updating the platform firmware,
+ // changing platform settings or updating the binary would invalidate the
+ // sealed data. It's annoying (but possible) to predict values for PCR4,
+ // and even more annoying for the firmware PCR (comparison to known values
+ // on similar hardware is the only thing that comes to mind).
//
- // See also: https://github.com/mxre/sealkey (generates PCR4 from EFI image, BSD license)
+ // See also: https://github.com/mxre/sealkey (generates PCR4 from EFI
+ // image, BSD license)
//
- // Using only SecureBootPCRs is the easiest and still reasonably secure, if we assume that the
- // platform knows how to take care of itself (i.e. Intel Boot Guard), and that secure boot
- // is implemented properly. It is, however, a much larger amount of code we need to trust.
+ // Using only SecureBootPCRs is the easiest and still reasonably secure, if
+ // we assume that the platform knows how to take care of itself (i.e. Intel
+ // Boot Guard), and that secure boot is implemented properly. It is,
+ // however, a much larger amount of code we need to trust.
//
- // We do not care about PCR 5 (GPT partition table) since modifying it is harmless. All of
- // the boot options and cmdline are hardcoded in the kernel image, and we use no bootloader,
- // so there's no PCR for bootloader configuration or kernel cmdline.
+ // We do not care about PCR 5 (GPT partition table) since modifying it is
+ // harmless. All of the boot options and cmdline are hardcoded in the
+ // kernel image, and we use no bootloader, so there's no PCR for bootloader
+ // configuration or kernel cmdline.
)
var (
@@ -102,15 +110,17 @@
var (
// ErrNotExists is returned when no TPMs are available in the system
ErrNotExists = errors.New("no TPMs found")
- // ErrNotInitialized is returned when this package was not initialized successfully
+ // ErrNotInitialized is returned when this package was not initialized
+ // successfully
ErrNotInitialized = errors.New("no TPM was initialized")
)
// Singleton since the TPM is too
var tpm *TPM
-// We're serializing all TPM operations since it has a limited number of handles and recovering
-// if it runs out is difficult to implement correctly. Might also be marginally more secure.
+// We're serializing all TPM operations since it has a limited number of
+// handles and recovering if it runs out is difficult to implement correctly.
+// Might also be marginally more secure.
var lock sync.Mutex
// TPM represents a high-level interface to a connected TPM 2.0
@@ -118,13 +128,14 @@
logger logtree.LeveledLogger
device io.ReadWriteCloser
- // We keep the AK loaded since it's used fairly often and deriving it is expensive
+ // We keep the AK loaded since it's used fairly often and deriving it is
+ // expensive
akHandleCache tpmutil.Handle
akPublicKey crypto.PublicKey
}
-// Initialize finds and opens the TPM (if any). If there is no TPM available it returns
-// ErrNotExists
+// Initialize finds and opens the TPM (if any). If there is no TPM available it
+// returns ErrNotExists
func Initialize(logger logtree.LeveledLogger) error {
lock.Lock()
defer lock.Unlock()
@@ -170,7 +181,8 @@
return nil
}
-// GenerateSafeKey uses two sources of randomness (Kernel & TPM) to generate the key
+// GenerateSafeKey uses two sources of randomness (Kernel & TPM) to generate
+// the key
func GenerateSafeKey(size uint16) ([]byte, error) {
lock.Lock()
defer lock.Unlock()
@@ -204,8 +216,8 @@
return encryptionKey, nil
}
-// Seal seals sensitive data and only allows access if the current platform configuration in
-// matches the one the data was sealed on.
+// Seal seals sensitive data and only allows access if the current platform
+// configuration in matches the one the data was sealed on.
func Seal(data []byte, pcrs []int) ([]byte, error) {
lock.Lock()
defer lock.Unlock()
@@ -225,8 +237,8 @@
return sealedKeyRaw, nil
}
-// Unseal unseals sensitive data if the current platform configuration allows and sealing constraints
-// allow it.
+// Unseal unseals sensitive data if the current platform configuration allows
+// and sealing constraints allow it.
func Unseal(data []byte) ([]byte, error) {
lock.Lock()
defer lock.Unlock()
@@ -256,7 +268,8 @@
return unsealedData, nil
}
-// Standard AK template for RSA2048 non-duplicatable restricted signing for attestation
+// Standard AK template for RSA2048 non-duplicatable restricted signing for
+// attestation
var akTemplate = tpm2.Public{
Type: tpm2.AlgRSA,
NameAlg: tpm2.AlgSHA256,
@@ -272,11 +285,12 @@
func loadAK() error {
var err error
- // Rationale: The AK is an EK-equivalent key and used only for attestation. Using a non-primary
- // key here would require us to store the wrapped version somewhere, which is inconvenient.
- // This being a primary key in the Endorsement hierarchy means that it can always be recreated
- // and can never be "destroyed". Under our security model this is of no concern since we identify
- // a node by its IK (Identity Key) which we can destroy.
+ // Rationale: The AK is an EK-equivalent key and used only for attestation.
+ // Using a non-primary key here would require us to store the wrapped
+ // version somewhere, which is inconvenient. This being a primary key in
+ // the Endorsement hierarchy means that it can always be recreated and can
+ // never be "destroyed". Under our security model this is of no concern
+ // since we identify a node by its IK (Identity Key) which we can destroy.
tpm.akHandleCache, tpm.akPublicKey, err = tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
tpm2.PCRSelection{}, "", "", akTemplate)
return err
@@ -284,12 +298,14 @@
// Process documented in TCG EK Credential Profile 2.2.1
func loadEK() (tpmutil.Handle, crypto.PublicKey, error) {
- // The EK is a primary key which is supposed to be certified by the manufacturer of the TPM.
- // Its public attributes are standardized in TCG EK Credential Profile 2.0 Table 1. These need
- // to match exactly or we aren't getting the key the manufacturere signed. tpm2tools contains
- // such a template already, so we're using that instead of redoing it ourselves.
- // This ignores the more complicated ways EKs can be specified, the additional stuff you can do
- // is just absolutely crazy (see 2.2.1.2 onward)
+ // The EK is a primary key which is supposed to be certified by the
+ // manufacturer of the TPM. Its public attributes are standardized in TCG
+ // EK Credential Profile 2.0 Table 1. These need to match exactly or we
+ // aren't getting the key the manufacturere signed. tpm2tools contains such
+ // a template already, so we're using that instead of redoing it ourselves.
+ // This ignores the more complicated ways EKs can be specified, the
+ // additional stuff you can do is just absolutely crazy (see 2.2.1.2
+ // onward)
return tpm2.CreatePrimary(tpm.device, tpm2.HandleEndorsement,
tpm2.PCRSelection{}, "", "", tpm2tools.DefaultEKTemplateRSA())
}
@@ -313,10 +329,11 @@
return public.Encode()
}
-// TCG TPM v2.0 Provisioning Guidance v1.0 7.8 Table 2 and
-// TCG EK Credential Profile v2.1 2.2.1.4 de-facto Standard for Windows
-// These are both non-normative and reference Windows 10 documentation that's no longer available :(
-// But in practice this is what people are using, so if it's normative or not doesn't really matter
+// TCG TPM v2.0 Provisioning Guidance v1.0 7.8 Table 2 and TCG EK Credential
+// Profile v2.1 2.2.1.4 de-facto Standard for Windows These are both
+// non-normative and reference Windows 10 documentation that's no longer
+// available :( But in practice this is what people are using, so if it's
+// normative or not doesn't really matter
const ekCertHandle = 0x01c00002
// GetEKPublic gets the public key and (if available) Certificate of the EK
@@ -345,7 +362,8 @@
return publicKey, ekCertRaw, nil
}
-// MakeAKChallenge generates a challenge for TPM residency and attributes of the AK
+// MakeAKChallenge generates a challenge for TPM residency and attributes of
+// the AK
func MakeAKChallenge(ekPubKey, akPub []byte, nonce []byte) ([]byte, []byte, error) {
ekPubKeyData, err := x509.ParsePKIXPublicKey(ekPubKey)
if err != nil {
@@ -385,12 +403,14 @@
}
defer tpm2.FlushContext(tpm.device, ekHandle)
- // This is necessary since the EK requires an endorsement handle policy in its session
- // For us this is stupid because we keep all hierarchies open anyways since a) we cannot safely
- // store secrets on the OS side pre-global unlock and b) it makes no sense in this security model
- // since an uncompromised host OS will not let an untrusted entity attest as itself and a
- // compromised OS can either not pass PCR policy checks or the game's already over (you
- // successfully runtime-exploited a production Metropolis node)
+ // This is necessary since the EK requires an endorsement handle policy in
+ // its session. For us this is stupid because we keep all hierarchies open
+ // anyways since a) we cannot safely store secrets on the OS side
+ // pre-global unlock and b) it makes no sense in this security model since
+ // an uncompromised host OS will not let an untrusted entity attest as
+ // itself and a compromised OS can either not pass PCR policy checks or the
+ // game's already over (you successfully runtime-exploited a production
+ // Metropolis node).
endorsementSession, _, err := tpm2.StartAuthSession(
tpm.device,
tpm2.HandleNull,
@@ -412,8 +432,10 @@
for {
solution, err := tpm2.ActivateCredentialUsingAuth(tpm.device, []tpm2.AuthCommand{
- {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession}, // Use standard no-password authentication
- {Session: endorsementSession, Attributes: tpm2.AttrContinueSession}, // Use a full policy session for the EK
+ // Use standard no-password authenatication
+ {Session: tpm2.HandlePasswordSession, Attributes: tpm2.AttrContinueSession},
+ // Use a full policy session for the EK
+ {Session: endorsementSession, Attributes: tpm2.AttrContinueSession},
}, tpm.akHandleCache, ekHandle, credBlob, secretChallenge)
if warn, ok := err.(tpm2.Warning); ok && warn.Code == tpm2.RCRetry {
time.Sleep(100 * time.Millisecond)
@@ -445,7 +467,8 @@
return nil
}
-// AttestPlatform performs a PCR quote using the AK and returns the quote and its signature
+// AttestPlatform performs a PCR quote using the AK and returns the quote and
+// its signature
func AttestPlatform(nonce []byte) ([]byte, []byte, error) {
lock.Lock()
defer lock.Unlock()
@@ -457,9 +480,9 @@
return []byte{}, []byte{}, fmt.Errorf("failed to load AK primary key: %w", err)
}
}
- // We only care about SHA256 since SHA1 is weak. This is supported on at least GCE and
- // Intel / AMD fTPM, which is good enough for now. Alg is null because that would just hash the
- // nonce, which is dumb.
+ // We only care about SHA256 since SHA1 is weak. This is supported on at
+ // least GCE and Intel / AMD fTPM, which is good enough for now. Alg is
+ // null because that would just hash the nonce, which is dumb.
quote, signature, err := tpm2.Quote(tpm.device, tpm.akHandleCache, "", "", nonce, srtmPCRs,
tpm2.AlgNull)
if err != nil {
@@ -468,8 +491,8 @@
return quote, signature.RSA.Signature, err
}
-// VerifyAttestPlatform verifies a given attestation. You can rely on all data coming back as being
-// from the TPM on which the AK is bound to.
+// VerifyAttestPlatform verifies a given attestation. You can rely on all data
+// coming back as being from the TPM on which the AK is bound to.
func VerifyAttestPlatform(nonce, akPub, quote, signature []byte) (*tpm2.AttestationData, error) {
hash := crypto.SHA256.New()
hash.Write(quote)
@@ -495,12 +518,14 @@
if err != nil {
return nil, err
}
- // quoteData.Magic works together with the TPM's Restricted key attribute. If this attribute is set
- // (which it needs to be for the AK to be considered valid) the TPM will not sign external data
- // having this prefix with such a key. Only data that originates inside the TPM like quotes and
- // key certifications can have this prefix and sill be signed by a restricted key. This check
- // is thus vital, otherwise somebody can just feed the TPM an arbitrary attestation to sign with
- // its AK and this function will happily accept the forged attestation.
+ // quoteData.Magic works together with the TPM's Restricted key attribute.
+ // If this attribute is set (which it needs to be for the AK to be
+ // considered valid) the TPM will not sign external data having this prefix
+ // with such a key. Only data that originates inside the TPM like quotes
+ // and key certifications can have this prefix and sill be signed by a
+ // restricted key. This check is thus vital, otherwise somebody can just
+ // feed the TPM an arbitrary attestation to sign with its AK and this
+ // function will happily accept the forged attestation.
if quoteData.Magic != tpmGeneratedValue {
return nil, errors.New("invalid TPM quote: data marker for internal data not set - forged attestation")
}
@@ -523,8 +548,9 @@
}
pcrs := make([][]byte, numSRTMPCRs)
- // The TPM can (and most do) return partial results. Let's just retry as many times as we have
- // PCRs since each read should return at least one PCR.
+ // The TPM can (and most do) return partial results. Let's just retry as
+ // many times as we have PCRs since each read should return at least one
+ // PCR.
readLoop:
for i := 0; i < numSRTMPCRs; i++ {
sel := tpm2.PCRSelection{Hash: tpm2.AlgSHA256}
@@ -554,8 +580,9 @@
return pcrs, nil
}
-// GetMeasurmentLog returns the binary log of all data hashed into PCRs. The result can be parsed by eventlog.
-// As this library currently doesn't support extending PCRs it just returns the log as supplied by the EFI interface.
+// GetMeasurmentLog returns the binary log of all data hashed into PCRs. The
+// result can be parsed by eventlog. As this library currently doesn't support
+// extending PCRs it just returns the log as supplied by the EFI interface.
func GetMeasurementLog() ([]byte, error) {
return ioutil.ReadFile("/sys/kernel/security/tpm0/binary_bios_measurements")
}