Debian Codegraph @

attest/certification.go

raw
1 // Copyright 2021 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 package attest
16
17 import (
18 "bytes"
19 "crypto"
20 "crypto/ecdsa"
21 "crypto/rand"
22 "crypto/rsa"
23 "errors"
24 "fmt"
25 "io"
26
27 "github.com/google/go-tpm/legacy/tpm2"
28 "github.com/google/go-tpm/legacy/tpm2/credactivation"
29 "github.com/google/go-tpm/tpmutil"
30 )
31
32 // secureCurves represents a set of secure elliptic curves. For now,
33 // the selection is based on the key size only.
34 var secureCurves = map[tpm2.EllipticCurve]bool{
35 tpm2.CurveNISTP256: true,
36 tpm2.CurveNISTP384: true,
37 tpm2.CurveNISTP521: true,
38 tpm2.CurveBNP256: true,
39 tpm2.CurveBNP638: true,
40 }
41
42 // CertificationParameters encapsulates the inputs for certifying an application key.
43 type CertificationParameters struct {
44 // Public represents the key's canonical encoding (a TPMT_PUBLIC structure).
45 // It includes the public key and signing parameters.
46 Public []byte
47 // CreateData represents the properties of a TPM 2.0 key. It is encoded
48 // as a TPMS_CREATION_DATA structure.
49 CreateData []byte
50 // CreateAttestation represents an assertion as to the details of the key.
51 // It is encoded as a TPMS_ATTEST structure.
52 CreateAttestation []byte
53 // CreateSignature represents a signature of the CreateAttestation structure.
54 // It is encoded as a TPMT_SIGNATURE structure.
55 CreateSignature []byte
56 }
57
58 // VerifyOpts specifies options for the key certification's verification.
59 type VerifyOpts struct {
60 // Public is the public key used to verify key ceritification.
61 Public crypto.PublicKey
62 // Hash is the hash function used for signature verification. It can be
63 // extracted from the properties of the certifying key.
64 Hash crypto.Hash
65 }
66
67 // ActivateOpts specifies options for the key certification's challenge generation.
68 type ActivateOpts struct {
69 // EK, the endorsement key, describes an asymmetric key whose
70 // private key is permanently bound to the TPM.
71 //
72 // Activation will verify that the provided EK is held on the same
73 // TPM as the key we're certifying. However, it is the caller's responsibility to
74 // ensure the EK they provide corresponds to the the device which
75 // they are trying to associate the certified key with.
76 EK crypto.PublicKey
77 // VerifierKeyNameDigest is the name digest of the public key we're using to
78 // verify the certification of the tpm-generated key being activated.
79 // The verifier key (usually the AK) that owns this digest should be the same
80 // key used in VerifyOpts.Public.
81 // Use tpm2.Public.Name() to produce the digest for a provided key.
82 VerifierKeyNameDigest *tpm2.HashValue
83 }
84
85 // CertifyOpts specifies options for the key's certification.
86 type CertifyOpts struct {
87 // QualifyingData is the user provided qualifying data.
88 QualifyingData []byte
89 }
90
91 // NewActivateOpts creates options for use in generating an activation challenge for a certified key.
92 // The computed hash is the name digest of the public key used to verify the certification of our key.
93 func NewActivateOpts(verifierPubKey tpm2.Public, ek crypto.PublicKey) (*ActivateOpts, error) {
94 pubName, err := verifierPubKey.Name()
95 if err != nil {
96 return nil, fmt.Errorf("unable to resolve a tpm2.Public Name struct from the given public key struct: %v", err)
97 }
98
99 return &ActivateOpts{
100 EK: ek,
101 VerifierKeyNameDigest: pubName.Digest,
102 }, nil
103 }
104
105 // Verify verifies the TPM2-produced certification parameters checking whether:
106 // - the key length is secure
107 // - the attestation parameters matched the attested key
108 // - the key was TPM-generated and resides within TPM
109 // - the key can sign/decrypt outside-TPM objects
110 // - the signature is successfully verified against the passed public key
111 // For now, it accepts only RSA verification keys.
112 func (p *CertificationParameters) Verify(opts VerifyOpts) error {
113 pub, err := tpm2.DecodePublic(p.Public)
114 if err != nil {
115 return fmt.Errorf("DecodePublic() failed: %v", err)
116 }
117 att, err := tpm2.DecodeAttestationData(p.CreateAttestation)
118 if err != nil {
119 return fmt.Errorf("DecodeAttestationData() failed: %v", err)
120 }
121 if att.Type != tpm2.TagAttestCertify {
122 return fmt.Errorf("attestation does not apply to certification data, got tag %x", att.Type)
123 }
124
125 switch pub.Type {
126 case tpm2.AlgRSA:
127 if pub.RSAParameters.KeyBits < minRSABits {
128 return fmt.Errorf("attested key too small: must be at least %d bits but was %d bits", minRSABits, pub.RSAParameters.KeyBits)
129 }
130 case tpm2.AlgECC:
131 if !secureCurves[pub.ECCParameters.CurveID] {
132 return fmt.Errorf("attested key uses insecure curve")
133 }
134 default:
135 return fmt.Errorf("public key of alg 0x%x not supported", pub.Type)
136 }
137
138 // Make sure the key has sane parameters (e.g., attestation can be faked if an AK
139 // can be used for arbitrary signatures).
140 // We verify the following:
141 // - Key is TPM backed.
142 // - Key is TPM generated.
143 // - Key is not restricted (means it can do arbitrary signing/decrypt ops).
144 // - Key cannot be duplicated.
145 // - Key was generated by a call to TPM_Create*.
146 if att.Magic != generatedMagic {
147 return errors.New("creation attestation was not produced by a TPM")
148 }
149 if (pub.Attributes & tpm2.FlagFixedTPM) == 0 {
150 return errors.New("provided key is exportable")
151 }
152 if (pub.Attributes & tpm2.FlagRestricted) != 0 {
153 return errors.New("provided key is restricted")
154 }
155 if (pub.Attributes & tpm2.FlagFixedParent) == 0 {
156 return errors.New("provided key can be duplicated to a different parent")
157 }
158 if (pub.Attributes & tpm2.FlagSensitiveDataOrigin) == 0 {
159 return errors.New("provided key is not created by TPM")
160 }
161
162 // Verify the attested creation name matches what is computed from
163 // the public key.
164 match, err := att.AttestedCertifyInfo.Name.MatchesPublic(pub)
165 if err != nil {
166 return err
167 }
168 if !match {
169 return errors.New("certification refers to a different key")
170 }
171
172 // Check the signature over the attestation data verifies correctly.
173 if !opts.Hash.Available() {
174 return fmt.Errorf("hash function is unavailable")
175 }
176 hsh := opts.Hash.New()
177 hsh.Write(p.CreateAttestation)
178
179 if len(p.CreateSignature) < 8 {
180 return fmt.Errorf("signature invalid: length of %d is shorter than 8", len(p.CreateSignature))
181 }
182
183 sig, err := tpm2.DecodeSignature(bytes.NewBuffer(p.CreateSignature))
184 if err != nil {
185 return fmt.Errorf("DecodeSignature() failed: %v", err)
186 }
187
188 switch pk := opts.Public.(type) {
189 case *rsa.PublicKey:
190 if sig.RSA == nil {
191 return fmt.Errorf("rsa public key provided for non-rsa signature")
192 }
193 if err := rsa.VerifyPKCS1v15(pk, opts.Hash, hsh.Sum(nil), sig.RSA.Signature); err != nil {
194 return fmt.Errorf("could not verify attestation: %v", err)
195 }
196 case *ecdsa.PublicKey:
197 if sig.ECC == nil {
198 return fmt.Errorf("ecdsa public key provided for non-ecdsa signature")
199 }
200 if ok := ecdsa.Verify(pk, hsh.Sum(nil), sig.ECC.R, sig.ECC.S); !ok {
201 return fmt.Errorf("could not verify ECC attestation")
202 }
203 default:
204 return fmt.Errorf("unsupported public key type: %T", pk)
205 }
206
207 return nil
208 }
209
210 // Generate returns a credential activation challenge, which can be provided
211 // to the TPM to verify the AK parameters given are authentic & the AK
212 // is present on the same TPM as the EK.
213 //
214 // The caller is expected to verify the secret returned from the TPM as
215 // as result of calling ActivateCredential() matches the secret returned here.
216 // The caller should use subtle.ConstantTimeCompare to avoid potential
217 // timing attack vectors.
218 func (p *CertificationParameters) Generate(rnd io.Reader, verifyOpts VerifyOpts, activateOpts ActivateOpts) (secret []byte, ec *EncryptedCredential, err error) {
219 if err := p.Verify(verifyOpts); err != nil {
220 return nil, nil, err
221 }
222
223 if activateOpts.EK == nil {
224 return nil, nil, errors.New("no EK provided")
225 }
226
227 secret = make([]byte, activationSecretLen)
228 if rnd == nil {
229 rnd = rand.Reader
230 }
231 if _, err = io.ReadFull(rnd, secret); err != nil {
232 return nil, nil, fmt.Errorf("error generating activation secret: %v", err)
233 }
234
235 att, err := tpm2.DecodeAttestationData(p.CreateAttestation)
236 if err != nil {
237 return nil, nil, fmt.Errorf("DecodeAttestationData() failed: %v", err)
238 }
239
240 if att.Type != tpm2.TagAttestCertify {
241 return nil, nil, fmt.Errorf("attestation does not apply to certify data, got %x", att.Type)
242 }
243
244 cred, encSecret, err := credactivation.Generate(activateOpts.VerifierKeyNameDigest, activateOpts.EK, symBlockSize, secret)
245 if err != nil {
246 return nil, nil, fmt.Errorf("credactivation.Generate() failed: %v", err)
247 }
248
249 return secret, &EncryptedCredential{
250 Credential: cred,
251 Secret: encSecret,
252 }, nil
253 }
254
255 // certify uses AK's handle, the passed user qualifying data, and the passed
256 // signature scheme to certify the key with the `hnd` handle.
257 func certify(tpm io.ReadWriteCloser, hnd, akHnd tpmutil.Handle, qualifyingData []byte, scheme tpm2.SigScheme) (*CertificationParameters, error) {
258 pub, _, _, err := tpm2.ReadPublic(tpm, hnd)
259 if err != nil {
260 return nil, fmt.Errorf("tpm2.ReadPublic() failed: %v", err)
261 }
262 public, err := pub.Encode()
263 if err != nil {
264 return nil, fmt.Errorf("could not encode public key: %v", err)
265 }
266 att, sig, err := tpm2.CertifyEx(tpm, "", "", hnd, akHnd, qualifyingData, scheme)
267 if err != nil {
268 return nil, fmt.Errorf("tpm2.Certify() failed: %v", err)
269 }
270 return &CertificationParameters{
271 Public: public,
272 CreateAttestation: att,
273 CreateSignature: sig,
274 }, nil
275 }