forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
windows_cert_manager.go
94 lines (82 loc) · 2.32 KB
/
windows_cert_manager.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package cert
import (
"fmt"
"os"
"path"
"strconv"
boshdir "github.com/cloudfoundry/bosh-agent/settings/directories"
"github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
type windowsCertManager struct {
fs boshsys.FileSystem
runner boshsys.CmdRunner
dirProvider boshdir.Provider
logger logger.Logger
backupPath string
}
const rootCertStore string = `Cert:\LocalMachine\Root`
func NewWindowsCertManager(fs boshsys.FileSystem, runner boshsys.CmdRunner, dirProvider boshdir.Provider, logger logger.Logger) Manager {
return &windowsCertManager{
fs: fs,
runner: runner,
dirProvider: dirProvider,
logger: logger,
backupPath: path.Join(dirProvider.TmpDir(), "rootCertBackup.sst"),
}
}
func (c *windowsCertManager) createBackup() error {
if _, err := os.Stat(c.backupPath); os.IsNotExist(err) {
err = c.fs.MkdirAll(c.dirProvider.TmpDir(), os.FileMode(0777))
if err != nil {
return err
}
_, _, _, err := c.runner.RunCommand("powershell", "-Command",
fmt.Sprintf(`"Get-ChildItem %s | Export-Certificate -Type SST -FilePath %s"`, rootCertStore, c.backupPath))
if err != nil {
return err
}
}
return nil
}
func (c *windowsCertManager) resetCerts() error {
_, _, _, err := c.runner.RunCommand("powershell", "-Command", fmt.Sprintf(`Remove-Item %s\*`, rootCertStore))
if err != nil {
return err
}
importCertsCmd := fmt.Sprintf("Import-Certificate -FilePath %s -CertStoreLocation %s", c.backupPath, rootCertStore)
_, _, _, err = c.runner.RunCommand("powershell", "-Command", importCertsCmd)
if err != nil {
return err
}
return nil
}
func (c *windowsCertManager) UpdateCertificates(rawCerts string) error {
err := c.createBackup()
if err != nil {
return err
}
err = c.resetCerts()
if err != nil {
return err
}
certs := splitCerts(rawCerts)
tempCertDir, err := c.fs.TempDir("")
if err != nil {
return err
}
defer c.fs.RemoveAll(tempCertDir)
for i, cert := range certs {
filename := path.Join(tempCertDir, strconv.Itoa(i))
err = c.fs.WriteFileString(filename, cert)
if err != nil {
return err
}
_, _, _, err = c.runner.RunCommand("powershell", "-Command",
fmt.Sprintf("Import-Certificate -FilePath %s -CertStoreLocation %s", filename, rootCertStore))
if err != nil {
return err
}
}
return nil
}