-
Notifications
You must be signed in to change notification settings - Fork 2
/
ca.go
110 lines (96 loc) · 2.53 KB
/
ca.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package insecure
import (
"crypto"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
)
// This file borrows heavily from the mkcert project:
// https://github.com/FiloSottile/mkcert
//
// This package will attempt to sign generated certs with your local mkcert CA, if present.
const (
rootName = "rootCA.pem"
rootKeyName = "rootCA-key.pem"
)
// CA returns the mkcert CA certificate and key if found.
// Returns an error if either fail to load or parse.
func CA() (cert *x509.Certificate, key crypto.PrivateKey, err error) {
certPEMBlock, keyPEMBlock, err := CAPEM()
if err != nil {
return nil, nil, err
}
certDERBlock, _ := pem.Decode(certPEMBlock)
if certDERBlock == nil || certDERBlock.Type != "CERTIFICATE" {
return nil, nil, errors.New("failed to read the CA certificate: unexpected content")
}
cert, err = x509.ParseCertificate(certDERBlock.Bytes)
if err != nil {
return nil, nil, err
}
keyDERBlock, _ := pem.Decode(keyPEMBlock)
if keyDERBlock == nil || keyDERBlock.Type != "PRIVATE KEY" {
return nil, nil, errors.New("failed to read the CA key: unexpected content")
}
key, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes)
if err != nil {
return nil, nil, err
}
return
}
// CAPEM returns the raw PEM mkcert CA certificate and key if found.
// Returns an error if either doesn’t exist or fails to load.
func CAPEM() (cert []byte, key []byte, err error) {
caRoot := getCARoot()
caPath := filepath.Join(caRoot, rootName)
if !pathExists(caPath) {
return nil, nil, fmt.Errorf("no CA certificate located at: %s", caPath)
}
cert, err = ioutil.ReadFile(caPath)
if err != nil {
return nil, nil, err
}
keyPath := filepath.Join(caRoot, rootKeyName)
if !pathExists(keyPath) {
return nil, nil, fmt.Errorf("no CA key located at: %s", keyPath)
}
key, err = ioutil.ReadFile(keyPath)
if err != nil {
return nil, nil, err
}
return
}
func pathExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func getCARoot() string {
if env := os.Getenv("CAROOT"); env != "" {
return env
}
var dir string
switch {
case runtime.GOOS == "windows":
dir = os.Getenv("LocalAppData")
case os.Getenv("XDG_DATA_HOME") != "":
dir = os.Getenv("XDG_DATA_HOME")
case runtime.GOOS == "darwin":
dir = os.Getenv("HOME")
if dir == "" {
return ""
}
dir = filepath.Join(dir, "Library", "Application Support")
default: // Unix
dir = os.Getenv("HOME")
if dir == "" {
return ""
}
dir = filepath.Join(dir, ".local", "share")
}
return filepath.Join(dir, "mkcert")
}