-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspecifics_windows.go
76 lines (66 loc) · 1.83 KB
/
specifics_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"crypto/x509"
"fmt"
"errors"
"io/ioutil"
"syscall"
"unsafe"
)
const CRYPT_E_NOT_FOUND = 0x80092004
// This code adapted from https://github.com/golang/go/issues/16736#issuecomment-540373689.
func WindowsSystemRoots() (*x509.CertPool, error) {
storeHandle, err := syscall.CertOpenSystemStore(0, syscall.StringToUTF16Ptr("Root"))
if err != nil {
return nil, fmt.Errorf("could not open system cert store: %w", syscall.GetLastError())
}
certPool := x509.NewCertPool()
var cert *syscall.CertContext
for {
cert, err = syscall.CertEnumCertificatesInStore(storeHandle, cert)
if err != nil {
if errno, ok := err.(syscall.Errno); ok {
if errno == CRYPT_E_NOT_FOUND {
break
}
}
return nil, fmt.Errorf("could not enumerate certificates: %w", syscall.GetLastError())
}
if cert == nil {
break
}
// Copy the buf, since ParseCertificate does not create its own copy.
buf := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
buf2 := make([]byte, cert.Length)
copy(buf2, buf)
if c, err := x509.ParseCertificate(buf2); err == nil {
certPool.AddCert(c)
}
}
return certPool, nil
}
// loadRootCertPool builds a trust store (cert pool) containing our CA's root
// certificate.
func loadRootCertPool(rootCertPath string) (*x509.CertPool, error) {
pool, err := WindowsSystemRoots()
if err != nil {
return nil, errors.New("cannot load system certs")
}
if rootCertPath != "" {
root, err := ioutil.ReadFile(rootCertPath)
if err != nil {
return nil, err
}
if ok := pool.AppendCertsFromPEM(root); !ok {
return nil, errors.New("missing or invalid root certificate")
}
}
return pool, nil
}
func WritePrivateKeyToFile(outputFileName, privateKeyPEM string) error {
err := ioutil.WriteFile(outputFileName, []byte(privateKeyPEM), 0600)
if err != nil{
return err
}
return nil
}