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