/
setup.go
373 lines (297 loc) · 9.43 KB
/
setup.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
Copyright 2019 The Jetstack cert-manager contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vault
import (
"crypto/x509"
"fmt"
"math/rand"
"net/http"
"os/exec"
"path"
"time"
vault "github.com/hashicorp/vault/api"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const vaultToken = "vault-root-token"
func NewVaultTokenSecret(name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
StringData: map[string]string{
"token": vaultToken,
},
}
}
func NewVaultAppRoleSecret(name, secretId string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
StringData: map[string]string{
"secretkey": secretId,
},
}
}
type VaultInitializer struct {
proxyCmd *exec.Cmd
client *vault.Client
Details
RootMount string
IntermediateMount string
Role string
AuthPath string
}
func (v *VaultInitializer) Init() error {
rand.Seed(time.Now().UnixNano())
listenPort := 30000 + rand.Intn(5000)
// TODO: we need to make this port-forward more robust.
// Currently, it's possible that the connection gets dropped causing later
// init commands to fail.
args := []string{"port-forward", "-n", v.Details.Namespace, v.Details.PodName, fmt.Sprintf("%d:8200", listenPort)}
cmd := exec.Command(v.Details.Kubectl, args...)
err := cmd.Start()
if err != nil {
return fmt.Errorf("Error starting port-forward: %s", err.Error())
}
if v.AuthPath == "" {
v.AuthPath = "approle"
}
// Wait for 7s to allow port-forward to actually start.
// We wait longer than expected, as in highly parallel e2e runs this may
// take some time to start.
time.Sleep(7 * time.Second)
// Cross our fingers and hope that it's started :this_is_fine:
cfg := vault.DefaultConfig()
cfg.Address = fmt.Sprintf("https://127.0.0.1:%d", listenPort)
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM(v.VaultCA)
if ok == false {
return fmt.Errorf("error loading Vault CA bundle")
}
cfg.HttpClient.Transport.(*http.Transport).TLSClientConfig.RootCAs = caCertPool
client, err := vault.NewClient(cfg)
if err != nil {
return fmt.Errorf("Unable to initialize vault client: %s", err.Error())
}
client.SetToken(vaultToken)
v.client = client
return nil
}
func (v *VaultInitializer) Setup() error {
if err := v.mountPKI(v.RootMount, "87600h"); err != nil {
return err
}
rootCa, err := v.generateRootCert()
if err != nil {
return err
}
if err := v.configureCert(v.RootMount); err != nil {
return err
}
if err := v.mountPKI(v.IntermediateMount, "43800h"); err != nil {
return err
}
csr, err := v.generateIntermediateSigningReq()
if err != nil {
return err
}
intermediateCa, err := v.signCertificate(csr)
if err != nil {
return err
}
if err := v.importSignIntermediate(intermediateCa, rootCa, v.IntermediateMount); err != nil {
return err
}
if err := v.configureCert(v.IntermediateMount); err != nil {
return err
}
if err := v.setupRole(); err != nil {
return err
}
return nil
}
func (v *VaultInitializer) Clean() error {
if err := v.client.Sys().Unmount("/" + v.IntermediateMount); err != nil {
return fmt.Errorf("Unable to unmount %v: %v", v.IntermediateMount, err)
}
if err := v.client.Sys().Unmount("/" + v.RootMount); err != nil {
return fmt.Errorf("Unable to unmount %v: %v", v.RootMount, err)
}
v.proxyCmd.Process.Kill()
v.proxyCmd.Process.Wait()
return nil
}
func (v *VaultInitializer) CreateAppRole() (string, string, error) {
// create policy
role_path := path.Join(v.IntermediateMount, "sign", v.Role)
policy := fmt.Sprintf("path \"%s\" { capabilities = [ \"create\", \"update\" ] }", role_path)
err := v.client.Sys().PutPolicy(v.Role, policy)
if err != nil {
return "", "", fmt.Errorf("Error creating policy: %s", err.Error())
}
// # create approle
params := map[string]string{
"period": "24h",
"policies": v.Role,
}
baseUrl := path.Join("/v1", "auth", v.AuthPath, "role", v.Role)
_, err = v.callVault("POST", baseUrl, "", params)
if err != nil {
return "", "", fmt.Errorf("Error creating approle: %s", err.Error())
}
// # read the role-id
url := path.Join(baseUrl, "role-id")
roleId, err := v.callVault("GET", url, "role_id", map[string]string{})
if err != nil {
return "", "", fmt.Errorf("Error reading role_id: %s", err.Error())
}
// # read the secret-id
url = path.Join(baseUrl, "secret-id")
secretId, err := v.callVault("POST", url, "secret_id", map[string]string{})
if err != nil {
return "", "", fmt.Errorf("Error reading secret_id: %s", err.Error())
}
return roleId, secretId, nil
}
func (v *VaultInitializer) CleanAppRole() error {
url := path.Join("/v1", "auth", v.AuthPath, "role", v.Role)
_, err := v.callVault("DELETE", url, "", map[string]string{})
if err != nil {
return fmt.Errorf("Error deleting AppRole: %s", err.Error())
}
err = v.client.Sys().DeletePolicy(v.Role)
if err != nil {
return fmt.Errorf("Error deleting policy: %s", err.Error())
}
return nil
}
func (v *VaultInitializer) mountPKI(mount, ttl string) error {
opts := &vault.MountInput{
Type: "pki",
Config: vault.MountConfigInput{
MaxLeaseTTL: "87600h",
},
}
if err := v.client.Sys().Mount("/"+mount, opts); err != nil {
return fmt.Errorf("Error mounting %s: %s", mount, err.Error())
}
return nil
}
func (v *VaultInitializer) generateRootCert() (string, error) {
params := map[string]string{
"common_name": "Root CA",
"ttl": "87600h",
"exclude_cn_from_sans": "true",
}
url := path.Join("/v1", v.RootMount, "root", "generate", "internal")
cert, err := v.callVault("POST", url, "certificate", params)
if err != nil {
return "", fmt.Errorf("Error generating CA root certificate: %s", err.Error())
}
return cert, nil
}
func (v *VaultInitializer) generateIntermediateSigningReq() (string, error) {
params := map[string]string{
"common_name": "Intermediate CA",
"ttl": "43800h",
"exclude_cn_from_sans": "true",
}
url := path.Join("/v1", v.IntermediateMount, "intermediate", "generate", "internal")
csr, err := v.callVault("POST", url, "csr", params)
if err != nil {
return "", fmt.Errorf("Error generating CA intermediate certificate: %s", err.Error())
}
return csr, nil
}
func (v *VaultInitializer) signCertificate(csr string) (string, error) {
params := map[string]string{
"use_csr_values": "true",
"ttl": "43800h",
"exclude_cn_from_sans": "true",
"csr": csr,
}
url := path.Join("/v1", v.RootMount, "root", "sign-intermediate")
cert, err := v.callVault("POST", url, "certificate", params)
if err != nil {
return "", fmt.Errorf("Error signing intermediate Vault certificate: %s", err.Error())
}
return cert, nil
}
func (v *VaultInitializer) importSignIntermediate(intermediateCa, rootCa, intermediateMount string) error {
params := map[string]string{
"certificate": intermediateCa,
}
url := path.Join("/v1", intermediateMount, "intermediate", "set-signed")
_, err := v.callVault("POST", url, "", params)
if err != nil {
return fmt.Errorf("Error importing intermediate Vault certificate: %s", err.Error())
}
return nil
}
func (v *VaultInitializer) configureCert(mount string) error {
params := map[string]string{
"issuing_certificates": fmt.Sprintf("https://vault.vault:8200/v1/%s/ca", mount),
"crl_distribution_points": fmt.Sprintf("https://vault.vault:8200/v1/%s/crl", mount),
}
url := path.Join("/v1", mount, "config", "urls")
_, err := v.callVault("POST", url, "", params)
if err != nil {
return fmt.Errorf("Error configuring Vault certificate: %s", err.Error())
}
return nil
}
func (v *VaultInitializer) setupRole() error {
// vault auth-enable approle
auths, err := v.client.Sys().ListAuth()
if err != nil {
return fmt.Errorf("Error fetching auth mounts: %s", err.Error())
}
if _, ok := auths[v.AuthPath+"/"]; !ok {
options := &vault.EnableAuthOptions{Type: "approle"}
if err := v.client.Sys().EnableAuthWithOptions(v.AuthPath, options); err != nil {
return fmt.Errorf("Error enabling approle: %s", err.Error())
}
}
params := map[string]string{
"allow_any_name": "true",
"max_ttl": "2160h",
}
url := path.Join("/v1", v.IntermediateMount, "roles", v.Role)
_, err = v.callVault("POST", url, "", params)
if err != nil {
return fmt.Errorf("Error creating role %s: %s", v.Role, err.Error())
}
return nil
}
func (v *VaultInitializer) callVault(method, url, field string, params map[string]string) (string, error) {
req := v.client.NewRequest(method, url)
err := req.SetJSONBody(params)
if err != nil {
return "", fmt.Errorf("error encoding Vault parameters: %s", err.Error())
}
resp, err := v.client.RawRequest(req)
if err != nil {
return "", fmt.Errorf("error calling Vault server: %s", err.Error())
}
defer resp.Body.Close()
result := map[string]interface{}{}
resp.DecodeJSON(&result)
fieldData := ""
if field != "" {
data := result["data"].(map[string]interface{})
fieldData = data[field].(string)
}
return fieldData, err
}