-
Notifications
You must be signed in to change notification settings - Fork 1
/
cert.go
81 lines (68 loc) · 1.49 KB
/
cert.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
package vproxy
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/jittering/truststore"
"github.com/mitchellh/go-homedir"
)
var ts *truststore.MkcertLib
func InitTrustStore() error {
var err error
ts, err = truststore.NewLib()
return err
}
func InstallTrustStore() error {
if ts == nil {
return fmt.Errorf("error: truststore not initialized")
}
return ts.Install()
}
func UninstallTrustStore() error {
if ts == nil {
return fmt.Errorf("error: truststore not initialized")
}
return ts.Uninstall()
}
func CARootPath() string {
if cp := os.Getenv("CAROOT_PATH"); cp != "" {
// override from env
return cp
}
return truststore.GetCAROOT()
}
func CertPath() string {
if cp := os.Getenv("CERT_PATH"); cp != "" {
// override from env
return cp
}
// default to user homedir
d, err := homedir.Dir()
if err != nil {
log.Fatalf("failed to locate homedir: %s", err)
}
return filepath.Join(d, ".vproxy")
}
// MakeCert for the give hostname, if it doesn't already exist.
func MakeCert(host string) (certFile string, keyFile string, err error) {
cp := CertPath() + string(filepath.Separator)
err = os.MkdirAll(cp, 0755)
if err != nil {
return "", "", err
}
cert, err := ts.CertFile([]string{host}, cp)
if err != nil {
return "", "", err
}
if cert.Exists() {
// nothing to do
return cert.CertFile, cert.KeyFile, nil
}
// generate new cert
cert, err = ts.MakeCert([]string{host}, cp)
if err != nil {
return "", "", err
}
return cert.CertFile, cert.KeyFile, nil
}