Debian Codegraph @

server/certstore/certstore_windows.go

raw
1 // Copyright 2022-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 //
14 // Adapted, updated, and enhanced from CertToStore, https://github.com/google/certtostore/releases/tag/v1.0.2
15 // Apache License, Version 2.0, Copyright 2017 Google Inc.
16
17 package certstore
18
19 import (
20 "bytes"
21 "crypto"
22 "crypto/ecdsa"
23 "crypto/elliptic"
24 "crypto/rsa"
25 "crypto/tls"
26 "crypto/x509"
27 "encoding/binary"
28 "fmt"
29 "io"
30 "math/big"
31 "reflect"
32 "sync"
33 "syscall"
34 "unicode/utf16"
35 "unsafe"
36
37 "golang.org/x/crypto/cryptobyte"
38 "golang.org/x/crypto/cryptobyte/asn1"
39 "golang.org/x/sys/windows"
40 )
41
42 const (
43 // wincrypt.h constants
44 winAcquireCached = windows.CRYPT_ACQUIRE_CACHE_FLAG
45 winAcquireSilent = windows.CRYPT_ACQUIRE_SILENT_FLAG
46 winAcquireOnlyNCryptKey = windows.CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG
47 winEncodingX509ASN = windows.X509_ASN_ENCODING
48 winEncodingPKCS7 = windows.PKCS_7_ASN_ENCODING
49 winCertStoreProvSystem = windows.CERT_STORE_PROV_SYSTEM
50 winCertStoreCurrentUser = windows.CERT_SYSTEM_STORE_CURRENT_USER
51 winCertStoreLocalMachine = windows.CERT_SYSTEM_STORE_LOCAL_MACHINE
52 winCertStoreReadOnly = windows.CERT_STORE_READONLY_FLAG
53 winInfoIssuerFlag = windows.CERT_INFO_ISSUER_FLAG
54 winInfoSubjectFlag = windows.CERT_INFO_SUBJECT_FLAG
55 winCompareNameStrW = windows.CERT_COMPARE_NAME_STR_W
56 winCompareShift = windows.CERT_COMPARE_SHIFT
57
58 // Reference https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfindcertificateinstore
59 winFindIssuerStr = windows.CERT_FIND_ISSUER_STR_W
60 winFindSubjectStr = windows.CERT_FIND_SUBJECT_STR_W
61 winFindHashStr = windows.CERT_FIND_HASH_STR
62
63 winNcryptKeySpec = windows.CERT_NCRYPT_KEY_SPEC
64
65 winBCryptPadPKCS1 uintptr = 0x2
66 winBCryptPadPSS uintptr = 0x8 // Modern TLS 1.2+
67 winBCryptPadPSSSalt uint32 = 32 // default 20, 32 optimal for typical SHA256 hash
68
69 winRSA1Magic = 0x31415352 // "RSA1" BCRYPT_RSAPUBLIC_MAGIC
70
71 winECS1Magic = 0x31534345 // "ECS1" BCRYPT_ECDSA_PUBLIC_P256_MAGIC
72 winECS3Magic = 0x33534345 // "ECS3" BCRYPT_ECDSA_PUBLIC_P384_MAGIC
73 winECS5Magic = 0x35534345 // "ECS5" BCRYPT_ECDSA_PUBLIC_P521_MAGIC
74
75 winECK1Magic = 0x314B4345 // "ECK1" BCRYPT_ECDH_PUBLIC_P256_MAGIC
76 winECK3Magic = 0x334B4345 // "ECK3" BCRYPT_ECDH_PUBLIC_P384_MAGIC
77 winECK5Magic = 0x354B4345 // "ECK5" BCRYPT_ECDH_PUBLIC_P521_MAGIC
78
79 winCryptENotFound = windows.CRYPT_E_NOT_FOUND
80
81 providerMSSoftware = "Microsoft Software Key Storage Provider"
82 )
83
84 var (
85 winBCryptRSAPublicBlob = winWide("RSAPUBLICBLOB")
86 winBCryptECCPublicBlob = winWide("ECCPUBLICBLOB")
87
88 winNCryptAlgorithmGroupProperty = winWide("Algorithm Group") // NCRYPT_ALGORITHM_GROUP_PROPERTY
89 winNCryptUniqueNameProperty = winWide("Unique Name") // NCRYPT_UNIQUE_NAME_PROPERTY
90 winNCryptECCCurveNameProperty = winWide("ECCCurveName") // NCRYPT_ECC_CURVE_NAME_PROPERTY
91
92 winCurveIDs = map[uint32]elliptic.Curve{
93 winECS1Magic: elliptic.P256(), // BCRYPT_ECDSA_PUBLIC_P256_MAGIC
94 winECS3Magic: elliptic.P384(), // BCRYPT_ECDSA_PUBLIC_P384_MAGIC
95 winECS5Magic: elliptic.P521(), // BCRYPT_ECDSA_PUBLIC_P521_MAGIC
96 winECK1Magic: elliptic.P256(), // BCRYPT_ECDH_PUBLIC_P256_MAGIC
97 winECK3Magic: elliptic.P384(), // BCRYPT_ECDH_PUBLIC_P384_MAGIC
98 winECK5Magic: elliptic.P521(), // BCRYPT_ECDH_PUBLIC_P521_MAGIC
99 }
100
101 winCurveNames = map[string]elliptic.Curve{
102 "nistP256": elliptic.P256(), // BCRYPT_ECC_CURVE_NISTP256
103 "nistP384": elliptic.P384(), // BCRYPT_ECC_CURVE_NISTP384
104 "nistP521": elliptic.P521(), // BCRYPT_ECC_CURVE_NISTP521
105 }
106
107 winAlgIDs = map[crypto.Hash]*uint16{
108 crypto.SHA1: winWide("SHA1"), // BCRYPT_SHA1_ALGORITHM
109 crypto.SHA256: winWide("SHA256"), // BCRYPT_SHA256_ALGORITHM
110 crypto.SHA384: winWide("SHA384"), // BCRYPT_SHA384_ALGORITHM
111 crypto.SHA512: winWide("SHA512"), // BCRYPT_SHA512_ALGORITHM
112 }
113
114 // MY is well-known system store on Windows that holds personal certificates. Read
115 // More about the CA locations here:
116 // https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/certificate-of-clientcertificate-element?redirectedfrom=MSDN
117 // https://superuser.com/questions/217719/what-are-the-windows-system-certificate-stores
118 // https://docs.microsoft.com/en-us/windows/win32/seccrypto/certificate-stores
119 // https://learn.microsoft.com/en-us/windows/win32/seccrypto/system-store-locations
120 // https://stackoverflow.com/questions/63286085/which-x509-storename-refers-to-the-certificates-stored-beneath-trusted-root-cert#:~:text=4-,StoreName.,is%20%22Intermediate%20Certification%20Authorities%22.
121 winMyStore = winWide("MY")
122 winIntermediateCAStore = winWide("CA")
123 winRootStore = winWide("Root")
124 winAuthRootStore = winWide("AuthRoot")
125
126 // These DLLs must be available on all Windows hosts
127 winCrypt32 = windows.NewLazySystemDLL("crypt32.dll")
128 winNCrypt = windows.NewLazySystemDLL("ncrypt.dll")
129
130 winCertFindCertificateInStore = winCrypt32.NewProc("CertFindCertificateInStore")
131 winCertVerifyTimeValidity = winCrypt32.NewProc("CertVerifyTimeValidity")
132 winCryptAcquireCertificatePrivateKey = winCrypt32.NewProc("CryptAcquireCertificatePrivateKey")
133 winNCryptExportKey = winNCrypt.NewProc("NCryptExportKey")
134 winNCryptOpenStorageProvider = winNCrypt.NewProc("NCryptOpenStorageProvider")
135 winNCryptGetProperty = winNCrypt.NewProc("NCryptGetProperty")
136 winNCryptSignHash = winNCrypt.NewProc("NCryptSignHash")
137
138 winFnGetProperty = winGetProperty
139 )
140
141 func init() {
142 for _, d := range []*windows.LazyDLL{
143 winCrypt32, winNCrypt,
144 } {
145 if err := d.Load(); err != nil {
146 panic(err)
147 }
148 }
149 for _, p := range []*windows.LazyProc{
150 winCertFindCertificateInStore, winCryptAcquireCertificatePrivateKey,
151 winNCryptExportKey, winNCryptOpenStorageProvider,
152 winNCryptGetProperty, winNCryptSignHash,
153 } {
154 if err := p.Find(); err != nil {
155 panic(err)
156 }
157 }
158 }
159
160 type winPKCS1PaddingInfo struct {
161 pszAlgID *uint16
162 }
163
164 type winPSSPaddingInfo struct {
165 pszAlgID *uint16
166 cbSalt uint32
167 }
168
169 // createCACertsPool generates a CertPool from the Windows certificate store,
170 // adding all matching certificates from the caCertsMatch array to the pool.
171 // All matching certificates (vs first) are added to the pool based on a user
172 // request. If no certificates are found an error is returned.
173 func createCACertsPool(cs *winCertStore, storeType uint32, caCertsMatch []string, skipInvalid bool) (*x509.CertPool, error) {
174 var errs []error
175 caPool := x509.NewCertPool()
176 for _, s := range caCertsMatch {
177 lfs, err := cs.caCertsBySubjectMatch(s, storeType, skipInvalid)
178 if err != nil {
179 errs = append(errs, err)
180 } else {
181 for _, lf := range lfs {
182 caPool.AddCert(lf)
183 }
184 }
185 }
186 // If every lookup failed return the errors.
187 if len(errs) == len(caCertsMatch) {
188 return nil, fmt.Errorf("unable to match any CA certificate: %v", errs)
189 }
190 return caPool, nil
191 }
192
193 // TLSConfig fulfills the same function as reading cert and key pair from
194 // pem files but sources the Windows certificate store instead. The
195 // certMatchBy and certMatch fields search the "MY" certificate location
196 // for the first certificate that matches the certMatch field. The
197 // caCertsMatch field is used to search the Trusted Root, Third Party Root,
198 // and Intermediate Certificate Authority locations for certificates with
199 // Subjects matching the provided strings. If a match is found, the
200 // certificate is added to the pool that is used to verify the certificate
201 // chain.
202 func TLSConfig(certStore StoreType, certMatchBy MatchByType, certMatch string, caCertsMatch []string, skipInvalid bool, config *tls.Config) error {
203 var (
204 leaf *x509.Certificate
205 leafCtx *windows.CertContext
206 pk *winKey
207 vOpts = x509.VerifyOptions{}
208 chains [][]*x509.Certificate
209 chain []*x509.Certificate
210 rawChain [][]byte
211 )
212
213 // By StoreType, open a store
214 if certStore == windowsCurrentUser || certStore == windowsLocalMachine {
215 var scope uint32
216 cs, err := winOpenCertStore(providerMSSoftware)
217 if err != nil || cs == nil {
218 return err
219 }
220 if certStore == windowsCurrentUser {
221 scope = winCertStoreCurrentUser
222 }
223 if certStore == windowsLocalMachine {
224 scope = winCertStoreLocalMachine
225 }
226
227 // certByIssuer or certBySubject
228 if certMatchBy == matchBySubject || certMatchBy == MATCHBYEMPTY {
229 leaf, leafCtx, err = cs.certBySubject(certMatch, scope, skipInvalid)
230 } else if certMatchBy == matchByIssuer {
231 leaf, leafCtx, err = cs.certByIssuer(certMatch, scope, skipInvalid)
232 } else if certMatchBy == matchByThumbprint {
233 leaf, leafCtx, err = cs.certByThumbprint(certMatch, scope, skipInvalid)
234 } else {
235 return ErrBadMatchByType
236 }
237 if err != nil {
238 // pass through error from cert search
239 return err
240 }
241 if leaf == nil || leafCtx == nil {
242 return ErrFailedCertSearch
243 }
244 pk, err = cs.certKey(leafCtx)
245 if err != nil {
246 return err
247 }
248 if pk == nil {
249 return ErrNoPrivateKeyStoreRef
250 }
251 // Look for CA Certificates
252 if len(caCertsMatch) != 0 {
253 caPool, err := createCACertsPool(cs, scope, caCertsMatch, skipInvalid)
254 if err != nil {
255 return err
256 }
257 config.ClientCAs = caPool
258 }
259 } else {
260 return ErrBadCertStore
261 }
262
263 // Get intermediates in the cert store for the found leaf IFF there is a full chain of trust in the store
264 // otherwise just use leaf as the final chain.
265 //
266 // Using std lib Verify as a reliable way to get valid chains out of the win store for the leaf; however,
267 // using empty options since server TLS stanza could be TLS role as server identity or client identity.
268 chains, err := leaf.Verify(vOpts)
269 if err != nil || len(chains) == 0 {
270 chains = append(chains, []*x509.Certificate{leaf})
271 }
272
273 // We have at least one verified chain so pop the first chain and remove the self-signed CA cert (if present)
274 // from the end of the chain
275 chain = chains[0]
276 if len(chain) > 1 {
277 chain = chain[:len(chain)-1]
278 }
279
280 // For tls.Certificate.Certificate need a [][]byte from []*x509.Certificate
281 // Approximate capacity for efficiency
282 rawChain = make([][]byte, 0, len(chain))
283 for _, link := range chain {
284 rawChain = append(rawChain, link.Raw)
285 }
286
287 tlsCert := tls.Certificate{
288 Certificate: rawChain,
289 PrivateKey: pk,
290 Leaf: leaf,
291 }
292 config.Certificates = []tls.Certificate{tlsCert}
293
294 // note: pk is a windows pointer (not freed by Go) but needs to live the life of the server for Signing.
295 // The cert context (leafCtx) windows pointer must not be freed underneath the pk so also life of the server.
296 return nil
297 }
298
299 // winWide returns a pointer to uint16 representing the equivalent
300 // to a Windows LPCWSTR.
301 func winWide(s string) *uint16 {
302 w := utf16.Encode([]rune(s))
303 w = append(w, 0)
304 return &w[0]
305 }
306
307 // winOpenProvider gets a provider handle for subsequent calls
308 func winOpenProvider(provider string) (uintptr, error) {
309 var hProv uintptr
310 pname := winWide(provider)
311 // Open the provider, the last parameter is not used
312 r, _, err := winNCryptOpenStorageProvider.Call(uintptr(unsafe.Pointer(&hProv)), uintptr(unsafe.Pointer(pname)), 0)
313 if r == 0 {
314 return hProv, nil
315 }
316 return hProv, fmt.Errorf("NCryptOpenStorageProvider returned %X: %v", r, err)
317 }
318
319 // winFindCert wraps the CertFindCertificateInStore library call. Note that any cert context passed
320 // into prev will be freed. If no certificate was found, nil will be returned.
321 func winFindCert(store windows.Handle, enc, findFlags, findType uint32, para *uint16, prev *windows.CertContext) (*windows.CertContext, error) {
322 h, _, err := winCertFindCertificateInStore.Call(
323 uintptr(store),
324 uintptr(enc),
325 uintptr(findFlags),
326 uintptr(findType),
327 uintptr(unsafe.Pointer(para)),
328 uintptr(unsafe.Pointer(prev)),
329 )
330 if h == 0 {
331 // Actual error, or simply not found?
332 if errno, ok := err.(syscall.Errno); ok && errno == syscall.Errno(winCryptENotFound) {
333 return nil, ErrFailedCertSearch
334 }
335 return nil, ErrFailedCertSearch
336 }
337 // nolint:govet
338 return (*windows.CertContext)(unsafe.Pointer(h)), nil
339 }
340
341 // winVerifyCertValid wraps the CertVerifyTimeValidity and simply returns true if the certificate is valid
342 func winVerifyCertValid(timeToVerify *windows.Filetime, certInfo *windows.CertInfo) bool {
343 // this function does not document returning errors / setting lasterror
344 r, _, _ := winCertVerifyTimeValidity.Call(
345 uintptr(unsafe.Pointer(timeToVerify)),
346 uintptr(unsafe.Pointer(certInfo)),
347 )
348 return r == 0
349 }
350
351 // winCertStore is a store implementation for the Windows Certificate Store
352 type winCertStore struct {
353 Prov uintptr
354 ProvName string
355 stores map[string]*winStoreHandle
356 mu sync.Mutex
357 }
358
359 // winOpenCertStore creates a winCertStore
360 func winOpenCertStore(provider string) (*winCertStore, error) {
361 cngProv, err := winOpenProvider(provider)
362 if err != nil {
363 // pass through error from winOpenProvider
364 return nil, err
365 }
366
367 wcs := &winCertStore{
368 Prov: cngProv,
369 ProvName: provider,
370 stores: make(map[string]*winStoreHandle),
371 }
372
373 return wcs, nil
374 }
375
376 // winCertContextToX509 creates an x509.Certificate from a Windows cert context.
377 func winCertContextToX509(ctx *windows.CertContext) (*x509.Certificate, error) {
378 var der []byte
379 slice := (*reflect.SliceHeader)(unsafe.Pointer(&der))
380 slice.Data = uintptr(unsafe.Pointer(ctx.EncodedCert))
381 slice.Len = int(ctx.Length)
382 slice.Cap = int(ctx.Length)
383 return x509.ParseCertificate(der)
384 }
385
386 // certByIssuer matches and returns the first certificate found by passed issuer.
387 // CertContext pointer returned allows subsequent key operations like Sign. Caller specifies
388 // current user's personal certs or local machine's personal certs using storeType.
389 // See CERT_FIND_ISSUER_STR description at https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfindcertificateinstore
390 func (w *winCertStore) certByIssuer(issuer string, storeType uint32, skipInvalid bool) (*x509.Certificate, *windows.CertContext, error) {
391 return w.certSearch(winFindIssuerStr, issuer, winMyStore, storeType, skipInvalid)
392 }
393
394 // certBySubject matches and returns the first certificate found by passed subject field.
395 // CertContext pointer returned allows subsequent key operations like Sign. Caller specifies
396 // current user's personal certs or local machine's personal certs using storeType.
397 // See CERT_FIND_SUBJECT_STR description at https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfindcertificateinstore
398 func (w *winCertStore) certBySubject(subject string, storeType uint32, skipInvalid bool) (*x509.Certificate, *windows.CertContext, error) {
399 return w.certSearch(winFindSubjectStr, subject, winMyStore, storeType, skipInvalid)
400 }
401
402 // certByThumbprint matches and returns the first certificate found by passed SHA1 thumbprint.
403 // CertContext pointer returned allows subsequent key operations like Sign. Caller specifies
404 // current user's personal certs or local machine's personal certs using storeType.
405 // See CERT_FIND_SUBJECT_STR description at https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfindcertificateinstore
406 func (w *winCertStore) certByThumbprint(hash string, storeType uint32, skipInvalid bool) (*x509.Certificate, *windows.CertContext, error) {
407 return w.certSearch(winFindHashStr, hash, winMyStore, storeType, skipInvalid)
408 }
409
410 // caCertsBySubjectMatch matches and returns all matching certificates of the subject field.
411 //
412 // The following locations are searched:
413 // 1) Root (Trusted Root Certification Authorities)
414 // 2) AuthRoot (Third-Party Root Certification Authorities)
415 // 3) CA (Intermediate Certification Authorities)
416 //
417 // Caller specifies current user's personal certs or local machine's personal certs using storeType.
418 // See CERT_FIND_SUBJECT_STR description at https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certfindcertificateinstore
419 func (w *winCertStore) caCertsBySubjectMatch(subject string, storeType uint32, skipInvalid bool) ([]*x509.Certificate, error) {
420 var (
421 leaf *x509.Certificate
422 searchLocations = [3]*uint16{winRootStore, winAuthRootStore, winIntermediateCAStore}
423 rv []*x509.Certificate
424 )
425 // surprisingly, an empty string returns a result. We'll treat this as an error.
426 if subject == "" {
427 return nil, ErrBadCaCertMatchField
428 }
429 for _, sr := range searchLocations {
430 var err error
431 if leaf, _, err = w.certSearch(winFindSubjectStr, subject, sr, storeType, skipInvalid); err == nil {
432 rv = append(rv, leaf)
433 } else {
434 // Ignore the failed search from a single location. Errors we catch include
435 // ErrFailedX509Extract (resulting from a malformed certificate) and errors
436 // around invalid attributes, unsupported algorithms, etc. These are corner
437 // cases as certificates with these errors shouldn't have been allowed
438 // to be added to the store in the first place.
439 if err != ErrFailedCertSearch {
440 return nil, err
441 }
442 }
443 }
444 // Not found anywhere
445 if len(rv) == 0 {
446 return nil, ErrFailedCertSearch
447 }
448 return rv, nil
449 }
450
451 // certSearch is a helper function to lookup certificates based on search type and match value.
452 // store is used to specify which store to perform the lookup in (system or user).
453 func (w *winCertStore) certSearch(searchType uint32, matchValue string, searchRoot *uint16, store uint32, skipInvalid bool) (*x509.Certificate, *windows.CertContext, error) {
454 // store handle to "MY" store
455 h, err := w.storeHandle(store, searchRoot)
456 if err != nil {
457 return nil, nil, err
458 }
459
460 var prev *windows.CertContext
461 var cert *x509.Certificate
462
463 i, err := windows.UTF16PtrFromString(matchValue)
464 if err != nil {
465 return nil, nil, ErrFailedCertSearch
466 }
467
468 // pass 0 as the third parameter because it is not used
469 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa376064(v=vs.85).aspx
470
471 for {
472 nc, err := winFindCert(h, winEncodingX509ASN|winEncodingPKCS7, 0, searchType, i, prev)
473 if err != nil {
474 return nil, nil, err
475 }
476 if nc != nil {
477 // certificate found
478 prev = nc
479
480 var now *windows.Filetime
481 if skipInvalid && !winVerifyCertValid(now, nc.CertInfo) {
482 continue
483 }
484
485 // Extract the DER-encoded certificate from the cert context
486 xc, err := winCertContextToX509(nc)
487 if err == nil {
488 cert = xc
489 break
490 } else {
491 return nil, nil, ErrFailedX509Extract
492 }
493 } else {
494 return nil, nil, ErrFailedCertSearch
495 }
496 }
497
498 if cert == nil {
499 return nil, nil, ErrFailedX509Extract
500 }
501
502 return cert, prev, nil
503 }
504
505 type winStoreHandle struct {
506 handle *windows.Handle
507 }
508
509 func winNewStoreHandle(provider uint32, store *uint16) (*winStoreHandle, error) {
510 var s winStoreHandle
511 if s.handle != nil {
512 return &s, nil
513 }
514 st, err := windows.CertOpenStore(
515 winCertStoreProvSystem,
516 0,
517 0,
518 provider|winCertStoreReadOnly,
519 uintptr(unsafe.Pointer(store)))
520 if err != nil {
521 return nil, ErrBadCryptoStoreProvider
522 }
523 s.handle = &st
524 return &s, nil
525 }
526
527 // winKey implements crypto.Signer and crypto.Decrypter for key based operations.
528 type winKey struct {
529 handle uintptr
530 pub crypto.PublicKey
531 Container string
532 AlgorithmGroup string
533 }
534
535 // Public exports a public key to implement crypto.Signer
536 func (k winKey) Public() crypto.PublicKey {
537 return k.pub
538 }
539
540 // Sign returns the signature of a hash to implement crypto.Signer
541 func (k winKey) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
542 switch k.AlgorithmGroup {
543 case "ECDSA", "ECDH":
544 return winSignECDSA(k.handle, digest)
545 case "RSA":
546 hf := opts.HashFunc()
547 algID, ok := winAlgIDs[hf]
548 if !ok {
549 return nil, ErrBadRSAHashAlgorithm
550 }
551 switch opts.(type) {
552 case *rsa.PSSOptions:
553 return winSignRSAPSSPadding(k.handle, digest, algID)
554 default:
555 return winSignRSAPKCS1Padding(k.handle, digest, algID)
556 }
557 default:
558 return nil, ErrBadSigningAlgorithm
559 }
560 }
561
562 func winSignECDSA(kh uintptr, digest []byte) ([]byte, error) {
563 var size uint32
564 // Obtain the size of the signature
565 r, _, _ := winNCryptSignHash.Call(
566 kh,
567 0,
568 uintptr(unsafe.Pointer(&digest[0])),
569 uintptr(len(digest)),
570 0,
571 0,
572 uintptr(unsafe.Pointer(&size)),
573 0)
574 if r != 0 {
575 return nil, ErrStoreECDSASigningError
576 }
577
578 // Obtain the signature data
579 buf := make([]byte, size)
580 r, _, _ = winNCryptSignHash.Call(
581 kh,
582 0,
583 uintptr(unsafe.Pointer(&digest[0])),
584 uintptr(len(digest)),
585 uintptr(unsafe.Pointer(&buf[0])),
586 uintptr(size),
587 uintptr(unsafe.Pointer(&size)),
588 0)
589 if r != 0 {
590 return nil, ErrStoreECDSASigningError
591 }
592 if len(buf) != int(size) {
593 return nil, ErrStoreECDSASigningError
594 }
595
596 return winPackECDSASigValue(bytes.NewReader(buf[:size]), int(size/2))
597 }
598
599 func winPackECDSASigValue(r io.Reader, digestLength int) ([]byte, error) {
600 sigR := make([]byte, digestLength)
601 if _, err := io.ReadFull(r, sigR); err != nil {
602 return nil, ErrStoreECDSASigningError
603 }
604
605 sigS := make([]byte, digestLength)
606 if _, err := io.ReadFull(r, sigS); err != nil {
607 return nil, ErrStoreECDSASigningError
608 }
609
610 var b cryptobyte.Builder
611 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
612 b.AddASN1BigInt(new(big.Int).SetBytes(sigR))
613 b.AddASN1BigInt(new(big.Int).SetBytes(sigS))
614 })
615 return b.Bytes()
616 }
617
618 func winSignRSAPKCS1Padding(kh uintptr, digest []byte, algID *uint16) ([]byte, error) {
619 // PKCS#1 v1.5 padding for some TLS 1.2
620 padInfo := winPKCS1PaddingInfo{pszAlgID: algID}
621 var size uint32
622 // Obtain the size of the signature
623 r, _, _ := winNCryptSignHash.Call(
624 kh,
625 uintptr(unsafe.Pointer(&padInfo)),
626 uintptr(unsafe.Pointer(&digest[0])),
627 uintptr(len(digest)),
628 0,
629 0,
630 uintptr(unsafe.Pointer(&size)),
631 winBCryptPadPKCS1)
632 if r != 0 {
633 return nil, ErrStoreRSASigningError
634 }
635
636 // Obtain the signature data
637 sig := make([]byte, size)
638 r, _, _ = winNCryptSignHash.Call(
639 kh,
640 uintptr(unsafe.Pointer(&padInfo)),
641 uintptr(unsafe.Pointer(&digest[0])),
642 uintptr(len(digest)),
643 uintptr(unsafe.Pointer(&sig[0])),
644 uintptr(size),
645 uintptr(unsafe.Pointer(&size)),
646 winBCryptPadPKCS1)
647 if r != 0 {
648 return nil, ErrStoreRSASigningError
649 }
650
651 return sig[:size], nil
652 }
653
654 func winSignRSAPSSPadding(kh uintptr, digest []byte, algID *uint16) ([]byte, error) {
655 // PSS padding for TLS 1.3 and some TLS 1.2
656 padInfo := winPSSPaddingInfo{pszAlgID: algID, cbSalt: winBCryptPadPSSSalt}
657
658 var size uint32
659 // Obtain the size of the signature
660 r, _, _ := winNCryptSignHash.Call(
661 kh,
662 uintptr(unsafe.Pointer(&padInfo)),
663 uintptr(unsafe.Pointer(&digest[0])),
664 uintptr(len(digest)),
665 0,
666 0,
667 uintptr(unsafe.Pointer(&size)),
668 winBCryptPadPSS)
669 if r != 0 {
670 return nil, ErrStoreRSASigningError
671 }
672
673 // Obtain the signature data
674 sig := make([]byte, size)
675 r, _, _ = winNCryptSignHash.Call(
676 kh,
677 uintptr(unsafe.Pointer(&padInfo)),
678 uintptr(unsafe.Pointer(&digest[0])),
679 uintptr(len(digest)),
680 uintptr(unsafe.Pointer(&sig[0])),
681 uintptr(size),
682 uintptr(unsafe.Pointer(&size)),
683 winBCryptPadPSS)
684 if r != 0 {
685 return nil, ErrStoreRSASigningError
686 }
687
688 return sig[:size], nil
689 }
690
691 // certKey wraps CryptAcquireCertificatePrivateKey. It obtains the CNG private
692 // key of a known certificate and returns a pointer to a winKey which implements
693 // both crypto.Signer. When a nil cert context is passed
694 // a nil key is intentionally returned, to model the expected behavior of a
695 // non-existent cert having no private key.
696 // https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecertificateprivatekey
697 func (w *winCertStore) certKey(cert *windows.CertContext) (*winKey, error) {
698 // Return early if a nil cert was passed.
699 if cert == nil {
700 return nil, nil
701 }
702 var (
703 kh uintptr
704 spec uint32
705 mustFree int
706 )
707 r, _, _ := winCryptAcquireCertificatePrivateKey.Call(
708 uintptr(unsafe.Pointer(cert)),
709 winAcquireCached|winAcquireSilent|winAcquireOnlyNCryptKey,
710 0, // Reserved, must be null.
711 uintptr(unsafe.Pointer(&kh)),
712 uintptr(unsafe.Pointer(&spec)),
713 uintptr(unsafe.Pointer(&mustFree)),
714 )
715 // If the function succeeds, the return value is nonzero (TRUE).
716 if r == 0 {
717 return nil, ErrNoPrivateKeyStoreRef
718 }
719 if mustFree != 0 {
720 return nil, ErrNoPrivateKeyStoreRef
721 }
722 if spec != winNcryptKeySpec {
723 return nil, ErrNoPrivateKeyStoreRef
724 }
725
726 return winKeyMetadata(kh)
727 }
728
729 func winKeyMetadata(kh uintptr) (*winKey, error) {
730 // uc is used to populate the unique container name attribute of the private key
731 uc, err := winGetPropertyStr(kh, winNCryptUniqueNameProperty)
732 if err != nil {
733 // unable to determine key unique name
734 return nil, ErrExtractingPrivateKeyMetadata
735 }
736
737 alg, err := winGetPropertyStr(kh, winNCryptAlgorithmGroupProperty)
738 if err != nil {
739 // unable to determine key algorithm
740 return nil, ErrExtractingPrivateKeyMetadata
741 }
742
743 var pub crypto.PublicKey
744
745 switch alg {
746 case "ECDSA", "ECDH":
747 buf, err := winExport(kh, winBCryptECCPublicBlob)
748 if err != nil {
749 // failed to export ECC public key
750 return nil, ErrExtractingECCPublicKey
751 }
752 pub, err = unmarshalECC(buf, kh)
753 if err != nil {
754 return nil, ErrExtractingECCPublicKey
755 }
756 case "RSA":
757 buf, err := winExport(kh, winBCryptRSAPublicBlob)
758 if err != nil {
759 return nil, ErrExtractingRSAPublicKey
760 }
761 pub, err = winUnmarshalRSA(buf)
762 if err != nil {
763 return nil, ErrExtractingRSAPublicKey
764 }
765 default:
766 return nil, ErrBadPublicKeyAlgorithm
767 }
768
769 return &winKey{handle: kh, pub: pub, Container: uc, AlgorithmGroup: alg}, nil
770 }
771
772 func winGetProperty(kh uintptr, property *uint16) ([]byte, error) {
773 var strSize uint32
774 r, _, _ := winNCryptGetProperty.Call(
775 kh,
776 uintptr(unsafe.Pointer(property)),
777 0,
778 0,
779 uintptr(unsafe.Pointer(&strSize)),
780 0,
781 0)
782 if r != 0 {
783 return nil, ErrExtractPropertyFromKey
784 }
785
786 buf := make([]byte, strSize)
787 r, _, _ = winNCryptGetProperty.Call(
788 kh,
789 uintptr(unsafe.Pointer(property)),
790 uintptr(unsafe.Pointer(&buf[0])),
791 uintptr(strSize),
792 uintptr(unsafe.Pointer(&strSize)),
793 0,
794 0)
795 if r != 0 {
796 return nil, ErrExtractPropertyFromKey
797 }
798
799 return buf, nil
800 }
801
802 func winGetPropertyStr(kh uintptr, property *uint16) (string, error) {
803 buf, err := winFnGetProperty(kh, property)
804 if err != nil {
805 return "", ErrExtractPropertyFromKey
806 }
807 uc := bytes.ReplaceAll(buf, []byte{0x00}, []byte(""))
808 return string(uc), nil
809 }
810
811 func winExport(kh uintptr, blobType *uint16) ([]byte, error) {
812 var size uint32
813 // When obtaining the size of a public key, most parameters are not required
814 r, _, _ := winNCryptExportKey.Call(
815 kh,
816 0,
817 uintptr(unsafe.Pointer(blobType)),
818 0,
819 0,
820 0,
821 uintptr(unsafe.Pointer(&size)),
822 0)
823 if r != 0 {
824 return nil, ErrExtractingPublicKey
825 }
826
827 // Place the exported key in buf now that we know the size required
828 buf := make([]byte, size)
829 r, _, _ = winNCryptExportKey.Call(
830 kh,
831 0,
832 uintptr(unsafe.Pointer(blobType)),
833 0,
834 uintptr(unsafe.Pointer(&buf[0])),
835 uintptr(size),
836 uintptr(unsafe.Pointer(&size)),
837 0)
838 if r != 0 {
839 return nil, ErrExtractingPublicKey
840 }
841 return buf, nil
842 }
843
844 func unmarshalECC(buf []byte, kh uintptr) (*ecdsa.PublicKey, error) {
845 // BCRYPT_ECCKEY_BLOB from bcrypt.h
846 header := struct {
847 Magic uint32
848 Key uint32
849 }{}
850
851 r := bytes.NewReader(buf)
852 if err := binary.Read(r, binary.LittleEndian, &header); err != nil {
853 return nil, ErrExtractingECCPublicKey
854 }
855
856 curve, ok := winCurveIDs[header.Magic]
857 if !ok {
858 // Fix for b/185945636, where despite specifying the curve, nCrypt returns
859 // an incorrect response with BCRYPT_ECDSA_PUBLIC_GENERIC_MAGIC.
860 var err error
861 curve, err = winCurveName(kh)
862 if err != nil {
863 // unsupported header magic or cannot match the curve by name
864 return nil, err
865 }
866 }
867
868 keyX := make([]byte, header.Key)
869 if n, err := r.Read(keyX); n != int(header.Key) || err != nil {
870 // failed to read key X
871 return nil, ErrExtractingECCPublicKey
872 }
873
874 keyY := make([]byte, header.Key)
875 if n, err := r.Read(keyY); n != int(header.Key) || err != nil {
876 // failed to read key Y
877 return nil, ErrExtractingECCPublicKey
878 }
879
880 pub := &ecdsa.PublicKey{
881 Curve: curve,
882 X: new(big.Int).SetBytes(keyX),
883 Y: new(big.Int).SetBytes(keyY),
884 }
885 return pub, nil
886 }
887
888 // winCurveName reads the curve name property and returns the corresponding curve.
889 func winCurveName(kh uintptr) (elliptic.Curve, error) {
890 cn, err := winGetPropertyStr(kh, winNCryptECCCurveNameProperty)
891 if err != nil {
892 // unable to determine the curve property name
893 return nil, ErrExtractPropertyFromKey
894 }
895 curve, ok := winCurveNames[cn]
896 if !ok {
897 // unknown curve name
898 return nil, ErrBadECCCurveName
899 }
900 return curve, nil
901 }
902
903 func winUnmarshalRSA(buf []byte) (*rsa.PublicKey, error) {
904 // BCRYPT_RSA_BLOB from bcrypt.h
905 header := struct {
906 Magic uint32
907 BitLength uint32
908 PublicExpSize uint32
909 ModulusSize uint32
910 UnusedPrime1 uint32
911 UnusedPrime2 uint32
912 }{}
913
914 r := bytes.NewReader(buf)
915 if err := binary.Read(r, binary.LittleEndian, &header); err != nil {
916 return nil, ErrExtractingRSAPublicKey
917 }
918
919 if header.Magic != winRSA1Magic {
920 // invalid header magic
921 return nil, ErrExtractingRSAPublicKey
922 }
923
924 if header.PublicExpSize > 8 {
925 // unsupported public exponent size
926 return nil, ErrExtractingRSAPublicKey
927 }
928
929 exp := make([]byte, 8)
930 if n, err := r.Read(exp[8-header.PublicExpSize:]); n != int(header.PublicExpSize) || err != nil {
931 // failed to read public exponent
932 return nil, ErrExtractingRSAPublicKey
933 }
934
935 mod := make([]byte, header.ModulusSize)
936 if n, err := r.Read(mod); n != int(header.ModulusSize) || err != nil {
937 // failed to read modulus
938 return nil, ErrExtractingRSAPublicKey
939 }
940
941 pub := &rsa.PublicKey{
942 N: new(big.Int).SetBytes(mod),
943 E: int(binary.BigEndian.Uint64(exp)),
944 }
945 return pub, nil
946 }
947
948 // storeHandle returns a handle to a given cert store, opening the handle as needed.
949 func (w *winCertStore) storeHandle(provider uint32, store *uint16) (windows.Handle, error) {
950 w.mu.Lock()
951 defer w.mu.Unlock()
952
953 key := fmt.Sprintf("%d%s", provider, windows.UTF16PtrToString(store))
954 var err error
955 if w.stores[key] == nil {
956 w.stores[key], err = winNewStoreHandle(provider, store)
957 if err != nil {
958 return 0, ErrBadCryptoStoreProvider
959 }
960 }
961 return *w.stores[key].handle, nil
962 }
963
964 // Verify interface conformance.
965 var _ credential = &winKey{}