/
init.go
109 lines (84 loc) · 2.38 KB
/
init.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
package sys
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
type vaultInitPayload struct {
SecretShares int `json:"secret_shares"`
SecretThreshold int `json:"secret_threshold"`
RecoveryShares int `json:"recovery_shares"`
RecoveryThreshold int `json:"recovery_threshold"`
}
type vaultInitResp struct {
Keys []string `json:"keys"`
KeysBase64 []string `json:"keys_base64"`
RecoveryKeys []string `json:"recovery_keys"`
RecoveryKeysBase64 []string `json:"recovery_keys_base64"`
RootToken string `json:"root_token"`
}
// VaultInit This endpoint initializes a new Vault. The Vault must not have been previously initialized.
// The recovery options, as well as the stored shares option, are only available when using Vault HSM.
// https://www.vaultproject.io/api-docs/system/init
func VaultInit(vaultAddress, vaultPort string, shares, threshold int, caChainFile, clientCertFile, clientKeyFile string) vaultInitResp {
cert, err := tls.LoadX509KeyPair(clientCertFile, clientKeyFile)
if err != nil {
log.Fatal(err)
}
caCert, err := ioutil.ReadFile(caChainFile)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
t := &http.Transport{
TLSClientConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
},
}
client := http.Client{Transport: t, Timeout: 15 * time.Second}
var data vaultInitPayload
var output vaultInitResp
/*
Auto-Unseal uses the recovery key options for initialization.
Therefore, "recovery_shares" and "recovery_threshold" should be used
*/
data.SecretShares = 5
data.SecretThreshold = 3
data.RecoveryShares = shares
data.RecoveryThreshold = threshold
dataJSON, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("PUT", fmt.Sprintf("https://%s:%s/v1/sys/init", vaultAddress, vaultPort), bytes.NewBuffer(dataJSON))
if err != nil {
log.Fatal(err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(bodyBytes, &output)
if err != nil {
log.Fatal(err)
}
if strings.Contains(string(bodyBytes), "Vault is already initialized") {
os.Exit(1)
}
return output
}