Debian Codegraph @

examples/tpm2-seal-unseal/main.go

raw
1 //go:build !windows
2
3 // Copyright (c) 2018, Google LLC All rights reserved.
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 // Command tpm2-seal-unseal illustrates utilizing the TPM2 API to seal and unseal data.
18 package main
19
20 import (
21 "flag"
22 "fmt"
23 "io"
24 "os"
25
26 "github.com/google/go-tpm/legacy/tpm2"
27 "github.com/google/go-tpm/tpmutil"
28 )
29
30 var (
31 // Default EK template defined in:
32 // https://trustedcomputinggroup.org/wp-content/uploads/Credential_Profile_EK_V2.0_R14_published.pdf
33 // Shared SRK template based off of EK template and specified in:
34 // https://trustedcomputinggroup.org/wp-content/uploads/TCG-TPM-v2.0-Provisioning-Guidance-Published-v1r1.pdf
35 srkTemplate = tpm2.Public{
36 Type: tpm2.AlgRSA,
37 NameAlg: tpm2.AlgSHA256,
38 Attributes: tpm2.FlagFixedTPM | tpm2.FlagFixedParent | tpm2.FlagSensitiveDataOrigin | tpm2.FlagUserWithAuth | tpm2.FlagRestricted | tpm2.FlagDecrypt | tpm2.FlagNoDA,
39 AuthPolicy: nil,
40 RSAParameters: &tpm2.RSAParams{
41 Symmetric: &tpm2.SymScheme{
42 Alg: tpm2.AlgAES,
43 KeyBits: 128,
44 Mode: tpm2.AlgCFB,
45 },
46 KeyBits: 2048,
47 ModulusRaw: make([]byte, 256),
48 },
49 }
50 tpmPath = flag.String("tpm-path", "/dev/tpm0", "Path to the TPM device (character device or a Unix socket).")
51 pcr = flag.Int("pcr", -1, "PCR to seal data to. Must be within [0, 23].")
52 )
53
54 func main() {
55 flag.Parse()
56
57 if *pcr < 0 || *pcr > 23 {
58 fmt.Fprintf(os.Stderr, "Invalid flag 'pcr': value %d is out of range", *pcr)
59 os.Exit(1)
60 }
61
62 err := run(*pcr, *tpmPath)
63 if err != nil {
64 fmt.Fprintf(os.Stderr, "Error: %v\n", err)
65 os.Exit(1)
66 }
67 }
68
69 func run(pcr int, tpmPath string) (retErr error) {
70 // Open the TPM
71 rwc, err := tpm2.OpenTPM(tpmPath)
72 if err != nil {
73 return fmt.Errorf("can't open TPM %q: %v", tpmPath, err)
74 }
75 defer func() {
76 if err := rwc.Close(); err != nil {
77 retErr = fmt.Errorf("%v\ncan't close TPM %q: %v", retErr, tpmPath, err)
78 }
79 }()
80
81 // Create the parent key against which to seal the data
82 srkPassword := ""
83 srkHandle, _, err := tpm2.CreatePrimary(rwc, tpm2.HandleOwner, tpm2.PCRSelection{}, "", srkPassword, srkTemplate)
84 if err != nil {
85 return fmt.Errorf("can't create primary key: %v", err)
86 }
87 defer func() {
88 if err := tpm2.FlushContext(rwc, srkHandle); err != nil {
89 retErr = fmt.Errorf("%v\nunable to flush SRK handle %q: %v", retErr, srkHandle, err)
90 }
91 }()
92 fmt.Printf("Created parent key with handle: 0x%x\n", srkHandle)
93
94 // Note the value of the pcr against which we will seal the data
95 pcrVal, err := tpm2.ReadPCR(rwc, pcr, tpm2.AlgSHA256)
96 if err != nil {
97 return fmt.Errorf("unable to read PCR: %v", err)
98 }
99 fmt.Printf("PCR %v value: 0x%x\n", pcr, pcrVal)
100
101 // Get the authorization policy that will protect the data to be sealed
102 objectPassword := "objectPassword"
103 sessHandle, policy, err := policyPCRPasswordSession(rwc, pcr, objectPassword)
104 if err != nil {
105 return fmt.Errorf("unable to get policy: %v", err)
106 }
107 if err := tpm2.FlushContext(rwc, sessHandle); err != nil {
108 return fmt.Errorf("unable to flush session: %v", err)
109 }
110 fmt.Printf("Created authorization policy: 0x%x\n", policy)
111
112 // Seal the data to the parent key and the policy
113 dataToSeal := []byte("secret")
114 fmt.Printf("Data to be sealed: 0x%x\n", dataToSeal)
115 privateArea, publicArea, err := tpm2.Seal(rwc, srkHandle, srkPassword, objectPassword, policy, dataToSeal)
116 if err != nil {
117 return fmt.Errorf("unable to seal data: %v", err)
118 }
119 fmt.Printf("Sealed data: 0x%x\n", privateArea)
120
121 // Load the sealed data into the TPM.
122 objectHandle, _, err := tpm2.Load(rwc, srkHandle, srkPassword, publicArea, privateArea)
123 if err != nil {
124 return fmt.Errorf("unable to load data: %v", err)
125 }
126 defer func() {
127 if err := tpm2.FlushContext(rwc, objectHandle); err != nil {
128 retErr = fmt.Errorf("%v\nunable to flush object handle %q: %v", retErr, objectHandle, err)
129 }
130 }()
131 fmt.Printf("Loaded sealed data with handle: 0x%x\n", objectHandle)
132
133 // Unseal the data
134 unsealedData, err := unseal(rwc, pcr, objectPassword, objectHandle)
135 if err != nil {
136 return fmt.Errorf("unable to unseal data: %v", err)
137 }
138 fmt.Printf("Unsealed data: 0x%x\n", unsealedData)
139
140 // Try to unseal the data with the wrong password
141 _, err = unseal(rwc, pcr, "wrong-password", objectHandle)
142 fmt.Printf("Trying to unseal with wrong password resulted in: %v\n", err)
143
144 // Extend the PCR
145 if err := tpm2.PCREvent(rwc, tpmutil.Handle(pcr), []byte{1}); err != nil {
146 return fmt.Errorf("unable to extend PCR: %v", err)
147 }
148 fmt.Printf("Extended PCR %d\n", pcr)
149
150 // Note the new value of the pcr
151 pcrVal, err = tpm2.ReadPCR(rwc, pcr, tpm2.AlgSHA256)
152 if err != nil {
153 return fmt.Errorf("unable to read PCR: %v", err)
154 }
155 fmt.Printf("PCR %d value: 0x%x\n", pcr, pcrVal)
156
157 // Try to unseal the data with the PCR in the wrong state
158 _, err = unseal(rwc, pcr, objectPassword, objectHandle)
159 fmt.Printf("Trying to unseal with wrong PCR state resulted in: %v\n", err)
160
161 return
162 }
163
164 // Returns the unsealed data
165 func unseal(rwc io.ReadWriteCloser, pcr int, objectPassword string, objectHandle tpmutil.Handle) (data []byte, retErr error) {
166 // Create the authorization session
167 sessHandle, _, err := policyPCRPasswordSession(rwc, pcr, objectPassword)
168 if err != nil {
169 return nil, fmt.Errorf("unable to get auth session: %v", err)
170 }
171 defer func() {
172 if err := tpm2.FlushContext(rwc, sessHandle); err != nil {
173 retErr = fmt.Errorf("%v\nunable to flush session: %v", retErr, err)
174 }
175 }()
176
177 // Unseal the data
178 unsealedData, err := tpm2.UnsealWithSession(rwc, sessHandle, objectHandle, objectPassword)
179 if err != nil {
180 return nil, fmt.Errorf("unable to unseal data: %v", err)
181 }
182 return unsealedData, nil
183 }
184
185 // Returns session handle and policy digest.
186 func policyPCRPasswordSession(rwc io.ReadWriteCloser, pcr int, password string) (sessHandle tpmutil.Handle, policy []byte, retErr error) {
187 // FYI, this is not a very secure session.
188 sessHandle, _, err := tpm2.StartAuthSession(
189 rwc,
190 tpm2.HandleNull, /*tpmKey*/
191 tpm2.HandleNull, /*bindKey*/
192 make([]byte, 16), /*nonceCaller*/
193 nil, /*secret*/
194 tpm2.SessionPolicy,
195 tpm2.AlgNull,
196 tpm2.AlgSHA256)
197 if err != nil {
198 return tpm2.HandleNull, nil, fmt.Errorf("unable to start session: %v", err)
199 }
200 defer func() {
201 if sessHandle != tpm2.HandleNull && err != nil {
202 if err := tpm2.FlushContext(rwc, sessHandle); err != nil {
203 retErr = fmt.Errorf("%v\nunable to flush session: %v", retErr, err)
204 }
205 }
206 }()
207
208 pcrSelection := tpm2.PCRSelection{
209 Hash: tpm2.AlgSHA256,
210 PCRs: []int{pcr},
211 }
212
213 // An empty expected digest means that digest verification is skipped.
214 if err := tpm2.PolicyPCR(rwc, sessHandle, nil /*expectedDigest*/, pcrSelection); err != nil {
215 return sessHandle, nil, fmt.Errorf("unable to bind PCRs to auth policy: %v", err)
216 }
217
218 if err := tpm2.PolicyPassword(rwc, sessHandle); err != nil {
219 return sessHandle, nil, fmt.Errorf("unable to require password for auth policy: %v", err)
220 }
221
222 policy, err = tpm2.PolicyGetDigest(rwc, sessHandle)
223 if err != nil {
224 return sessHandle, nil, fmt.Errorf("unable to get policy digest: %v", err)
225 }
226 return sessHandle, policy, nil
227 }