Debian Codegraph @

attest/pcp_windows.go

raw
1 // Copyright 2019 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 //go:build windows
16 // +build windows
17
18 package attest
19
20 import (
21 "bytes"
22 "crypto/x509"
23 "encoding/binary"
24 "fmt"
25 "io"
26 "syscall"
27 "unsafe"
28
29 "github.com/google/go-tpm/tpmutil"
30 tpmtbs "github.com/google/go-tpm/tpmutil/tbs"
31 "golang.org/x/sys/windows"
32 )
33
34 const (
35 pcpProviderName = "Microsoft Platform Crypto Provider"
36 cryptENotFound = 0x80092004 // From winerror.h.
37
38 // The below is documented in this Microsoft whitepaper:
39 // https://github.com/Microsoft/TSS.MSR/blob/master/PCPTool.v11/Using%20the%20Windows%208%20Platform%20Crypto%20Provider%20and%20Associated%20TPM%20Functionality.pdf
40 ncryptOverwriteKeyFlag = 0x80
41 // Key usage value for AKs.
42 nCryptPropertyPCPKeyUsagePolicyIdentity = 0x8
43 )
44
45 // DLL references.
46 var (
47 nCrypt = windows.MustLoadDLL("ncrypt.dll")
48 nCryptOpenStorageProvider = nCrypt.MustFindProc("NCryptOpenStorageProvider")
49 nCryptFreeObject = nCrypt.MustFindProc("NCryptFreeObject")
50 nCryptGetProperty = nCrypt.MustFindProc("NCryptGetProperty")
51 nCryptSetProperty = nCrypt.MustFindProc("NCryptSetProperty")
52 nCryptOpenKey = nCrypt.MustFindProc("NCryptOpenKey")
53 nCryptCreatePersistedKey = nCrypt.MustFindProc("NCryptCreatePersistedKey")
54 nCryptFinalizeKey = nCrypt.MustFindProc("NCryptFinalizeKey")
55 nCryptDeleteKey = nCrypt.MustFindProc("NCryptDeleteKey")
56
57 crypt32 = windows.MustLoadDLL("crypt32.dll")
58 crypt32CertEnumCertificatesInStore = crypt32.MustFindProc("CertEnumCertificatesInStore")
59 crypt32CertCloseStore = crypt32.MustFindProc("CertCloseStore")
60
61 tbs *windows.DLL
62 tbsGetDeviceInfo *windows.Proc
63 )
64
65 func maybeWinErr(errNo uintptr) error {
66 if errData, known := tpmErrNums[uint32(errNo)]; known {
67 return fmt.Errorf("tpm or subsystem failure: %s: %s", errData.name, errData.description)
68 }
69 return nil
70 }
71
72 func utf16ToString(buf []byte) (string, error) {
73 b := make([]uint16, len(buf)/2)
74 // LPCSTR (Windows' representation of utf16) is always little endian.
75 if err := binary.Read(bytes.NewReader(buf), binary.LittleEndian, &b); err != nil {
76 return "", err
77 }
78 return windows.UTF16ToString(b), nil
79 }
80
81 // closeNCryptoObject is a helper to call NCryptFreeObject on a given handle.
82 func closeNCryptObject(hnd uintptr) error {
83 r, _, msg := nCryptFreeObject.Call(hnd)
84 if r != 0 {
85 if tpmErr := maybeWinErr(r); tpmErr != nil {
86 return tpmErr
87 }
88 return fmt.Errorf("NCryptFreeObject returned %X: %v", r, msg)
89 }
90 return nil
91 }
92
93 // getNCryptBufferProperty is a helper to read a byte slice from a NCrypt handle property
94 // using NCryptGetProperty.
95 func getNCryptBufferProperty(hnd uintptr, field string) ([]byte, error) {
96 var size uint32
97 wideField, err := windows.UTF16FromString(field)
98 if err != nil {
99 return nil, err
100 }
101
102 r, _, msg := nCryptGetProperty.Call(hnd, uintptr(unsafe.Pointer(&wideField[0])), 0, 0, uintptr(unsafe.Pointer(&size)), 0)
103 if r != 0 {
104 if tpmErr := maybeWinErr(r); tpmErr != nil {
105 msg = tpmErr
106 }
107 return nil, fmt.Errorf("NCryptGetProperty returned %d,%X (%v) for key %q on size read", size, r, msg, field)
108 }
109 buff := make([]byte, size)
110 r, _, msg = nCryptGetProperty.Call(hnd, uintptr(unsafe.Pointer(&wideField[0])), uintptr(unsafe.Pointer(&buff[0])), uintptr(size), uintptr(unsafe.Pointer(&size)), 0)
111 if r != 0 {
112 if tpmErr := maybeWinErr(r); tpmErr != nil {
113 msg = tpmErr
114 }
115 return nil, fmt.Errorf("NCryptGetProperty returned %X (%v) for key %q on data read", r, msg, field)
116 }
117 return buff, nil
118 }
119
120 // winPCP represents a reference to the Platform Crypto Provider.
121 type winPCP struct {
122 hProv uintptr
123 }
124
125 // tbsDeviceInfo represents TPM device information from the TBS
126 // API. This structure is identical to _TBS_DEVICE_INFO in tbs.h.
127 type tbsDeviceInfo struct {
128 TBSVersion uint32
129 TPMVersion uint32
130 TPMInterfaceType uint32
131 TPMImplementationRevision uint32
132 }
133
134 // windowsTPMInfo describes the versions of the TPM and OS interface code.
135 type windowsTPMInfo struct {
136 Manufacturer string
137 PCPVersion string
138 TBSInfo tbsDeviceInfo
139 }
140
141 // TPMInfo returns version information about the TPM & OS interface code.
142 func (h *winPCP) TPMInfo() (*windowsTPMInfo, error) {
143 var err error
144 out := &windowsTPMInfo{}
145
146 buf, err := getNCryptBufferProperty(h.hProv, "PCP_PLATFORM_TYPE")
147 if err != nil {
148 return nil, fmt.Errorf("Failed to read PCP_PLATFORM_TYPE: %v", err)
149 }
150 out.Manufacturer, err = utf16ToString(buf)
151 if err != nil {
152 return nil, err
153 }
154
155 buf, err = getNCryptBufferProperty(h.hProv, "PCP_PROVIDER_VERSION")
156 if err != nil {
157 return nil, fmt.Errorf("Failed to read PCP_PROVIDER_VERSION: %v", err)
158 }
159 out.PCPVersion, err = utf16ToString(buf)
160 if err != nil {
161 return nil, err
162 }
163
164 r, _, msg := tbsGetDeviceInfo.Call(unsafe.Sizeof(out.TBSInfo), uintptr(unsafe.Pointer(&out.TBSInfo)))
165 if r != 0 {
166 return nil, fmt.Errorf("Failed to call Tbsi_GetDeviceInfo: %v", msg)
167 }
168
169 return out, nil
170 }
171
172 // TPMCommandInterface returns an interface where TPM commands can issued directly.
173 func (h *winPCP) TPMCommandInterface() (io.ReadWriteCloser, error) {
174 var provTBS tpmtbs.Context
175 var sz uint32
176 platformHndField, err := windows.UTF16FromString("PCP_PLATFORMHANDLE")
177 if err != nil {
178 return nil, err
179 }
180
181 r, _, err := nCryptGetProperty.Call(h.hProv, uintptr(unsafe.Pointer(&platformHndField[0])), uintptr(unsafe.Pointer(&provTBS)), unsafe.Sizeof(provTBS), uintptr(unsafe.Pointer(&sz)), 0)
182 if r != 0 {
183 if tpmErr := maybeWinErr(r); tpmErr != nil {
184 err = tpmErr
185 }
186 return nil, fmt.Errorf("NCryptGetProperty for platform handle returned %X (%v)", r, err)
187 }
188
189 return tpmutil.FromContext(provTBS), nil
190 }
191
192 // TPMKeyHandle returns a transient handle to the given key on the TPM.
193 func (h *winPCP) TPMKeyHandle(hnd uintptr) (tpmutil.Handle, error) {
194 var keyHndTBS tpmutil.Handle
195 var sz uint32
196 platformHndField, err := windows.UTF16FromString("PCP_PLATFORMHANDLE")
197 if err != nil {
198 return 0, err
199 }
200
201 if r, _, err := nCryptGetProperty.Call(hnd, uintptr(unsafe.Pointer(&platformHndField[0])), uintptr(unsafe.Pointer(&keyHndTBS)), unsafe.Sizeof(keyHndTBS), uintptr(unsafe.Pointer(&sz)), 0); r != 0 {
202 if tpmErr := maybeWinErr(r); tpmErr != nil {
203 err = tpmErr
204 }
205 return 0, fmt.Errorf("NCryptGetProperty for hKey platform handle returned %X (%v)", r, err)
206 }
207
208 return keyHndTBS, nil
209 }
210
211 // Close releases all resources managed by the Handle.
212 func (h *winPCP) Close() error {
213 return closeNCryptObject(h.hProv)
214 }
215
216 // DeleteKey permanently removes the key with the given handle from the system,
217 // and frees its handle.
218 func (h *winPCP) DeleteKey(kh uintptr) error {
219 r, _, msg := nCryptDeleteKey.Call(kh, 0)
220 if r != 0 {
221 return fmt.Errorf("nCryptDeleteKey returned %X: %v", r, msg)
222 }
223 return nil
224 }
225
226 // EKCerts returns the Endorsement Certificates.
227 // Failure to fetch an ECC certificate is not considered
228 // an error as they do not exist on all platforms.
229 func (h *winPCP) EKCerts() ([]*x509.Certificate, error) {
230 c, err := getPCPCerts(h.hProv, "PCP_RSA_EKNVCERT")
231 if err != nil {
232 return nil, err
233 }
234 eccCerts, err := getPCPCerts(h.hProv, "PCP_ECC_EKNVCERT")
235 if err == nil { // ECC certs are not present on all platforms
236 c = append(c, eccCerts...)
237 }
238
239 // Reading the certificate from the system store has failed.
240 // Lets try reading the raw bytes directly from NVRAM instead.
241 if len(c) == 0 {
242 certs, err := getPCPCerts(h.hProv, "PCP_EKNVCERT")
243 if err != nil {
244 return nil, fmt.Errorf("Failed to read PCP_EKNVCERT: %v", err)
245 }
246 c = append(c, certs...)
247 }
248
249 var out []*x509.Certificate
250 for _, der := range c {
251 cert, err := ParseEKCertificate(der)
252 if err != nil {
253 return nil, err
254 }
255 out = append(out, cert)
256 }
257
258 return out, nil
259 }
260
261 // getPCPCerts is a helper to iterate over a certificates in a cert store,
262 // whose handle was obtained by reading a specific property on a PCP handle.
263 func getPCPCerts(hProv uintptr, propertyName string) ([][]byte, error) {
264 var size, cryptCertHnd uintptr
265 utf16PropName, err := windows.UTF16FromString(propertyName)
266 if err != nil {
267 return nil, err
268 }
269
270 r, _, msg := nCryptGetProperty.Call(hProv, uintptr(unsafe.Pointer(&utf16PropName[0])), uintptr(unsafe.Pointer(&cryptCertHnd)), 8, uintptr(unsafe.Pointer(&size)), 0)
271 if r != 0 {
272 return nil, fmt.Errorf("NCryptGetProperty returned %X, %v", r, msg)
273 }
274 defer crypt32CertCloseStore.Call(uintptr(unsafe.Pointer(cryptCertHnd)), 0)
275
276 var out [][]byte
277 var certContext uintptr
278 for {
279 certContext, _, msg = crypt32CertEnumCertificatesInStore.Call(uintptr(unsafe.Pointer(cryptCertHnd)), certContext)
280 if certContext == 0 && msg != nil {
281 if errno, ok := msg.(syscall.Errno); ok {
282 // cryptENotFound is returned when there are no more certificates to iterate through.
283 if errno == cryptENotFound {
284 break
285 }
286 }
287 return nil, msg
288 }
289 cert := (*syscall.CertContext)(unsafe.Pointer(certContext))
290 // Copy the buffer. This was taken straight from the Go source: src/crypto/x509/root_windows.go#L70
291 buf := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
292 buf2 := make([]byte, cert.Length)
293 copy(buf2, buf)
294 out = append(out, buf2)
295 }
296 return out, nil
297 }
298
299 // NewAK creates a persistent attestation key of the specified name.
300 func (h *winPCP) NewAK(name string, alg Algorithm) (uintptr, error) {
301 var kh uintptr
302 utf16Name, err := windows.UTF16FromString(name)
303 if err != nil {
304 return 0, err
305 }
306 utf16Alg, err := windows.UTF16FromString(string(alg))
307 if err != nil {
308 return 0, err
309 }
310
311 // Create a persistent RSA key of the specified name.
312 r, _, msg := nCryptCreatePersistedKey.Call(h.hProv, uintptr(unsafe.Pointer(&kh)), uintptr(unsafe.Pointer(&utf16Alg[0])), uintptr(unsafe.Pointer(&utf16Name[0])), 0, 0)
313 if r != 0 {
314 if tpmErr := maybeWinErr(r); tpmErr != nil {
315 msg = tpmErr
316 }
317 return 0, fmt.Errorf("NCryptCreatePersistedKey returned %X: %v", r, msg)
318 }
319 // Specify generated key length to be 2048 bits.
320 utf16Length, err := windows.UTF16FromString("Length")
321 if err != nil {
322 return 0, err
323 }
324 var length uint32 = uint32(alg.Size())
325 r, _, msg = nCryptSetProperty.Call(kh, uintptr(unsafe.Pointer(&utf16Length[0])), uintptr(unsafe.Pointer(&length)), unsafe.Sizeof(length), 0)
326 if r != 0 {
327 if tpmErr := maybeWinErr(r); tpmErr != nil {
328 msg = tpmErr
329 }
330 return 0, fmt.Errorf("NCryptSetProperty (Length) returned %X: %v", r, msg)
331 }
332 // Specify the generated key can only be used for identity attestation.
333 utf16KeyPolicy, err := windows.UTF16FromString("PCP_KEY_USAGE_POLICY")
334 if err != nil {
335 return 0, err
336 }
337 var policy uint32 = nCryptPropertyPCPKeyUsagePolicyIdentity
338 r, _, msg = nCryptSetProperty.Call(kh, uintptr(unsafe.Pointer(&utf16KeyPolicy[0])), uintptr(unsafe.Pointer(&policy)), unsafe.Sizeof(policy), 0)
339 if r != 0 {
340 if tpmErr := maybeWinErr(r); tpmErr != nil {
341 msg = tpmErr
342 }
343 return 0, fmt.Errorf("NCryptSetProperty (PCP KeyUsage Policy) returned %X: %v", r, msg)
344 }
345
346 // Finalize (create) the key.
347 r, _, msg = nCryptFinalizeKey.Call(kh, 0)
348 if r != 0 {
349 if tpmErr := maybeWinErr(r); tpmErr != nil {
350 msg = tpmErr
351 }
352 return 0, fmt.Errorf("NCryptFinalizeKey returned %X: %v", r, msg)
353 }
354
355 return kh, nil
356 }
357
358 // EKPub returns a BCRYPT_RSA_BLOB structure representing the EK.
359 func (h *winPCP) EKPub() ([]byte, error) {
360 return getNCryptBufferProperty(h.hProv, "PCP_EKPUB")
361 }
362
363 type akProps struct {
364 RawPublic []byte
365 RawCreationData []byte
366 RawAttest []byte
367 RawSignature []byte
368 }
369
370 // AKProperties returns the binding properties of the given attestation
371 // key. Note that it is only valid to call this function with the same
372 // winPCP handle within which the AK was created.
373 func (h *winPCP) AKProperties(kh uintptr) (*akProps, error) {
374 idBlob, err := getNCryptBufferProperty(kh, "PCP_TPM12_IDBINDING")
375 if err != nil {
376 return nil, err
377 }
378 r := bytes.NewReader(idBlob)
379 // Because the TPM 1.2 blob leads with a version tag,
380 // we can switch decoding logic based on it.
381 if bytes.Equal(idBlob[0:4], []byte{1, 1, 0, 0}) {
382 return decodeAKProps12(r)
383 }
384 return decodeAKProps20(r)
385 }
386
387 // decodeAKProps12 separates the single TPM 1.2 blob from the PCP property
388 // into its constituents, returning information about the public key
389 // of the AK.
390 func decodeAKProps12(r *bytes.Reader) (*akProps, error) {
391 var out akProps
392 // Skip over fixed-size fields in TPM_IDENTITY_CONTENTS which
393 // we don't need to read.
394 // Specifically: ver, ordinal, & labelPrivCADigest.
395 r.Seek(4+4+20, io.SeekCurrent)
396 pubKeyStartIdx := int(r.Size()) - r.Len()
397
398 // Skip over fixed-size key parameters in TPM_PUBKEY, so
399 // we can read the length of the exponent &
400 // determine where the pubkey structure ends.
401 // Specifically: algID, encScheme, sigScheme, paramSize, keyLength,
402 // and numPrimes.
403 r.Seek(4+2+2+4+4+4, io.SeekCurrent)
404
405 // Read the size of the exponent section.
406 var exponentSize uint32
407 if err := binary.Read(r, binary.BigEndian, &exponentSize); err != nil {
408 return nil, fmt.Errorf("failed to decode exponentSize: %v", err)
409 }
410 // Consume the bytes representing the exponent.
411 exp := make([]byte, int(exponentSize))
412 if err := binary.Read(r, binary.BigEndian, &exp); err != nil {
413 return nil, fmt.Errorf("failed to decode exp: %v", err)
414 }
415 // Read the size of the key data.
416 var keyDataSize uint32
417 if err := binary.Read(r, binary.BigEndian, &keyDataSize); err != nil {
418 return nil, fmt.Errorf("failed to decode keyDataSize: %v", err)
419 }
420 // Seek to the end of the key data.
421 r.Seek(int64(keyDataSize), io.SeekCurrent)
422
423 // Read the trailing signature.
424 out.RawSignature = make([]byte, r.Len())
425 if err := binary.Read(r, binary.BigEndian, &out.RawSignature); err != nil {
426 return nil, fmt.Errorf("failed to decode signature: %v", err)
427 }
428
429 // Seek back to the location of the public key, and consume it.
430 r.Seek(int64(pubKeyStartIdx), io.SeekStart)
431 out.RawPublic = make([]byte, 24+int(exponentSize)+4+int(keyDataSize))
432 if err := binary.Read(r, binary.BigEndian, &out.RawPublic); err != nil {
433 return nil, fmt.Errorf("failed to decode public: %v", err)
434 }
435
436 return &out, nil
437 }
438
439 // decodeAKProps20 separates the single TPM 2.0 blob from the PCP property
440 // into its constituents. For TPM 2.0 devices, these are bytes representing
441 // the following structures: TPM2B_PUBLIC, TPM2B_CREATION_DATA, TPM2B_ATTEST,
442 // and TPMT_SIGNATURE.
443 func decodeAKProps20(r *bytes.Reader) (*akProps, error) {
444 var out akProps
445
446 var publicSize uint16
447 if err := binary.Read(r, binary.BigEndian, &publicSize); err != nil {
448 return nil, fmt.Errorf("failed to decode TPM2B_PUBLIC.size: %v", err)
449 }
450 out.RawPublic = make([]byte, publicSize)
451 if err := binary.Read(r, binary.BigEndian, &out.RawPublic); err != nil {
452 return nil, fmt.Errorf("failed to decode TPM2B_PUBLIC.data: %v", err)
453 }
454
455 var creationDataSize uint16
456 if err := binary.Read(r, binary.BigEndian, &creationDataSize); err != nil {
457 return nil, fmt.Errorf("failed to decode TPM2B_CREATION_DATA.size: %v", err)
458 }
459 out.RawCreationData = make([]byte, creationDataSize)
460 if err := binary.Read(r, binary.BigEndian, &out.RawCreationData); err != nil {
461 return nil, fmt.Errorf("failed to decode TPM2B_CREATION_DATA.data: %v", err)
462 }
463
464 var attestSize uint16
465 if err := binary.Read(r, binary.BigEndian, &attestSize); err != nil {
466 return nil, fmt.Errorf("failed to decode TPM2B_ATTEST.size: %v", err)
467 }
468 out.RawAttest = make([]byte, attestSize)
469 if err := binary.Read(r, binary.BigEndian, &out.RawAttest); err != nil {
470 return nil, fmt.Errorf("failed to decode TPM2B_ATTEST.data: %v", err)
471 }
472
473 // The encoded TPMT_SIGNATURE structure represents the remaining bytes in
474 // the ID binding blob.
475 out.RawSignature = make([]byte, r.Len())
476 if err := binary.Read(r, binary.BigEndian, &out.RawSignature); err != nil {
477 return nil, fmt.Errorf("failed to decode TPMT_SIGNATURE.data: %v", err)
478 }
479 return &out, nil
480 }
481
482 // LoadKeyByName returns a handle to the persistent PCP key with the specified
483 // name.
484 func (h *winPCP) LoadKeyByName(name string) (uintptr, error) {
485 utf16Name, err := windows.UTF16FromString(name)
486 if err != nil {
487 return 0, err
488 }
489
490 var hKey uintptr
491 r, _, msg := nCryptOpenKey.Call(h.hProv, uintptr(unsafe.Pointer(&hKey)), uintptr(unsafe.Pointer(&utf16Name[0])), 0, 0)
492 if r != 0 {
493 if tpmErr := maybeWinErr(r); tpmErr != nil {
494 msg = tpmErr
495 }
496 return 0, fmt.Errorf("NCryptOpenKey returned %X (%v) for key %q", r, msg, name)
497 }
498 return hKey, nil
499 }
500
501 // ActivateCredential performs TPM2_ActivateCredential or TPM_ActivateIdentity.
502 func (h *winPCP) ActivateCredential(hKey uintptr, activationBlob []byte) ([]byte, error) {
503 utf16ActivationStr, err := windows.UTF16FromString("PCP_TPM12_IDACTIVATION")
504 if err != nil {
505 return nil, err
506 }
507
508 r, _, msg := nCryptSetProperty.Call(hKey, uintptr(unsafe.Pointer(&utf16ActivationStr[0])), uintptr(unsafe.Pointer(&activationBlob[0])), uintptr(len(activationBlob)), 0)
509 if r != 0 {
510 if tpmErr := maybeWinErr(r); tpmErr != nil {
511 msg = tpmErr
512 }
513 return nil, fmt.Errorf("NCryptSetProperty returned %X (%v) for key activation", r, msg)
514 }
515
516 return getNCryptBufferProperty(hKey, "PCP_TPM12_IDACTIVATION")
517 }
518
519 // openPCP initializes a reference to the Microsoft PCP provider.
520 // The Caller is expected to call Close() when they are done.
521 func openPCP() (*winPCP, error) {
522 var err error
523 var h winPCP
524 pname, err := windows.UTF16FromString(pcpProviderName)
525 if err != nil {
526 return nil, err
527 }
528
529 r, _, err := nCryptOpenStorageProvider.Call(uintptr(unsafe.Pointer(&h.hProv)), uintptr(unsafe.Pointer(&pname[0])), 0)
530 if r != 0 { // r is non-zero on error, err is always populated in this case.
531 if tpmErr := maybeWinErr(r); tpmErr != nil {
532 return nil, tpmErr
533 }
534 return nil, err
535 }
536 return &h, nil
537 }