-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
452 lines (390 loc) · 13.7 KB
/
main.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package main
import (
"context"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/signal"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/charmbracelet/lipgloss"
"github.com/cli/cli/v2/pkg/surveyext"
"github.com/google/go-jsonnet"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/passbolt/go-passbolt/api"
"golang.org/x/term"
"gopkg.in/yaml.v3"
ky "sigs.k8s.io/yaml"
"github.com/vshn/emergency-credentials-receive/pkg/config"
"github.com/vshn/emergency-credentials-receive/pkg/inputs"
)
//go:embed kubectl-config-tmpl.jsonnet
var kubectlTemplate string
var sampleConfig = `
passbolt_key: |
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: OpenPGP.js v4.10.9
Comment: https://openpgpjs.org
[...]
-----END PGP PRIVATE KEY BLOCK-----
`
const (
envVarPassphrase = "EMR_PASSPHRASE"
envVarTOTPToken = "EMR_TOTP_TOKEN"
envVarKubernetesEndpoint = "EMR_KUBERNETES_ENDPOINT"
defaultEndpoint = "https://cloud.passbolt.com/vshn"
defaultKubernetesEndpoint = "https://kubernetes.default.svc:6443"
// defaultEmergencyCredentialsBucketConfigName is the name of the resource in passbolt that contains the bucket configuration.
defaultEmergencyCredentialsBucketConfigName = "emergency-cedentials-buckets"
clusterOverviewPage = "https://wiki.vshn.net/x/4whJF"
passboltMFACookieName = "passbolt_mfa"
userAgent = "emergency-credentials-receive/0.0.0"
)
var (
tokenOutputStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575"))
boldStyle = lipgloss.NewStyle().Bold(true)
isTerminal = term.IsTerminal(int(os.Stdout.Fd()))
omitTokenOutput bool
)
func main() {
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [options] [cluster_id]\n\n", os.Args[0])
fmt.Fprintf(flag.CommandLine.Output(), "Available env variables:\n")
fmt.Fprintf(flag.CommandLine.Output(), "\t%s\t\tthe passphrase to unlock the Passbolt key\n", envVarPassphrase)
fmt.Fprintf(flag.CommandLine.Output(), "\t%s\tthe Kubernetes endpoint written to the created kubeconfig file\n", envVarKubernetesEndpoint)
fmt.Fprintf(flag.CommandLine.Output(), "\t%s\t\tthe directory the configuration is stored in\n", config.EnvConfigDir)
flag.PrintDefaults()
}
flag.BoolVar(&omitTokenOutput, "omit-token-output", false, "omit token output to STDOUT")
flag.Parse()
clusterId := flag.Arg(0)
var saveConfig bool
lln("Welcome to the Emergency Credentials Receive tool!")
lf("This tool will help you receive your cluster emergency credentials from Passbolt.\n\n")
c, err := config.RetrieveConfig()
if err != nil && errors.Is(err, fs.ErrNotExist) {
lf("No config file found at %q.\n", config.ConfigFile())
lln("File will be created after a successful login.")
} else if err != nil {
lln("Error retrieving config: ", err)
}
if c.PassboltKey == "" && isTerminal {
k, err := surveyext.Edit("", "", "\n\n# Paste your Passbolt private key from\n# https://cloud.passbolt.com/vshn/app/settings/keys\n", os.Stdin, os.Stdout, os.Stderr)
if err != nil {
lln("Error retrieving passbolt key: ", err)
os.Exit(1)
}
saveConfig = true
c.PassboltKey = k
}
if c.PassboltKey == "" {
lf("Passbolt key cannot be empty. Please provide interactively or create a config file at %q:\n%s", config.ConfigFile(), sampleConfig)
os.Exit(1)
}
passphrase := envOrPrompt(envVarPassphrase, "Passbolt passphrase", true)
if clusterId == "" {
cid, err := inputs.LineInput("Enter the ID of the cluster you want to access", "c-crashy-wreck-1234")
if err != nil {
lln("Error retrieving cluster ID: ", err)
os.Exit(1)
}
clusterId = cid
}
if clusterId == "" {
lln("Cluster ID cannot be empty.")
lln("Provide interactively or as argument.")
os.Exit(1)
}
client, err := api.NewClient(nil, userAgent, defaultEndpoint, c.PassboltKey, passphrase)
if err != nil {
lf("Error creating passbolt client: %v\n", err)
os.Exit(1)
}
client.MFACallback = mfaCallback
lln("Logging into passbolt...")
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := client.Login(ctx); err != nil {
lf("Error logging into passbolt: %v\n", err)
os.Exit(1)
}
if saveConfig {
if err := config.SaveConfig(c); err != nil {
lln("Error saving config: ", err)
}
}
lf("Logged in. Retrieving bucket configuration from %q...\n", defaultEmergencyCredentialsBucketConfigName)
res, err := client.GetResources(ctx, &api.GetResourcesOptions{})
if err != nil {
lln("Error retrieving resources from passbolt: ", err)
}
var resource api.Resource
for _, r := range res {
if r.Name == defaultEmergencyCredentialsBucketConfigName {
resource = r
break
}
}
if resource.ID == "" {
lln("Error retrieving bucket configuration from passbolt: ", fmt.Errorf("could not find resource %q", defaultEmergencyCredentialsBucketConfigName))
os.Exit(1)
}
lln(" Retrieving bucket secret...")
secret, err := client.GetSecret(ctx, resource.ID)
if err != nil {
lln("Error retrieving bucket secret from passbolt: ", err)
os.Exit(1)
}
lln(" Decrypting bucket secret...")
conf, err := client.DecryptMessage(secret.Data)
if err != nil {
lln("Error decrypting bucket secret in passbolt: ", err)
os.Exit(1)
}
lln(" Parsing passbolt secret...")
var pbsc api.SecretDataTypePasswordAndDescription
if err := json.Unmarshal([]byte(conf), &pbsc); err != nil {
lln("Error parsing the decrypted passbolt secret: ", err)
os.Exit(1)
}
lln(" Parsing bucket configuration from secret...")
var bc bucketConfig
if err := yaml.Unmarshal([]byte(pbsc.Password), &bc); err != nil {
lln("Error parsing bucket configuration from passbolt secrets password field: ", err)
os.Exit(1)
}
lf("%d buckets with credentials found\n", len(bc.Buckets))
var emcreds []string
for _, b := range bc.Buckets {
lf("Trying %q (bucket %q, region %q, keyId %q)\n", b.Endpoint, b.Bucket, b.Region, b.AccessKeyId)
mc, err := minio.New(b.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(b.AccessKeyId, b.SecretAccessKey, ""),
Secure: !b.Insecure,
Region: b.Region,
})
if err != nil {
lln(" Error creating minio client: ", err)
continue
}
objectName := clusterId
if b.ObjectNameTemplate != "" {
lln(" Constructing object name from template...")
t, err := template.New("fileName").Funcs(sprig.TxtFuncMap()).Parse(b.ObjectNameTemplate)
if err != nil {
lln(" unable to parse file name template:", err)
continue
}
buf := new(strings.Builder)
if err := t.Execute(buf, struct {
ClusterId string
Context map[string]string
}{
ClusterId: clusterId,
Context: map[string]string{"ClusterId": clusterId},
}); err != nil {
lln(" unable to execute file name template:", err)
continue
}
objectName = buf.String()
}
lf(" Downloading %q...\n", objectName)
// fully read object into memory, otherwise the error message can be very confusing
// it says something like "JSON unmarshal error: not found"
buf, err := minioGetReadAll(ctx, mc, b.Bucket, objectName)
if err != nil {
lln(" Error downloading object: ", err)
continue
}
lln(" Parsing object...")
var et encryptedToken
if err := json.Unmarshal(buf, &et); err != nil {
lln(" Error parsing object: ", err)
continue
}
lln(" Trying to decrypt object...")
var decrypted string
for _, s := range et.Secrets {
d, err := client.DecryptMessage(s.Data)
if err == nil {
decrypted = d
break
}
}
if decrypted == "" {
lln(" No decryptable secret found")
continue
}
emcreds = append(emcreds, decrypted)
}
if len(emcreds) == 0 {
lln("No valid emergency credentials found")
os.Exit(1)
}
lf("Emergency credentials found\n\n")
for i, c := range emcreds {
fmt.Println("# ", "Token", i)
if omitTokenOutput {
fmt.Println(tokenOutputStyle.Render("*** OMITTED ***"))
} else {
fmt.Println(tokenOutputStyle.Render(c))
}
}
kep := os.Getenv("EMR_KUBERNETES_ENDPOINT")
if kep == "" && isTerminal {
ih := fmt.Sprintf("Provide API endpoint to render kubeconfig. See %q for an overview.", clusterOverviewPage)
k, err := inputs.LineInput(ih, defaultKubernetesEndpoint)
if err != nil {
lln("Error retrieving kubernetes endpoint: ", err)
os.Exit(1)
}
kep = k
}
if kep == "" {
lln("Assuming default kubernetes endpoint.")
kep = defaultKubernetesEndpoint
}
kubeconfig, err := renderKubeconfig(kep, emcreds)
if err != nil {
lln("Error rendering kubeconfig: ", err)
lln("The tokens printed above should continue to work, but you will have to create the kubeconfig manually.")
os.Exit(1)
}
kcFileName := "em-" + clusterId
if err := os.WriteFile(kcFileName, []byte("# Generated by emergency-credentials-receive\n"+kubeconfig), 0600); err != nil {
lln("Error writing kubeconfig: ", err)
lln("The tokens printed above should continue to work, but you will have to create the kubeconfig manually.")
os.Exit(1)
}
lf("Wrote kubeconfig to %q. Use with:\n\n", kcFileName)
lln(boldStyle.Render("##", "The cluster might require you to use a jump host:", clusterOverviewPage))
lln(boldStyle.Render("#", "ssh -D 12000 -q -N $JUMPHOST"))
lln(boldStyle.Render("#", "export HTTPS_PROXY=socks5://localhost:12000"))
lln(boldStyle.Render(fmt.Sprintf("export KUBECONFIG=%q", kcFileName)))
lln(boldStyle.Render("kubectl get nodes"))
}
// minioGetReadAll is a helper function to fully download a S3 object into memory.
func minioGetReadAll(ctx context.Context, mc *minio.Client, bucket, objectName string) ([]byte, error) {
object, err := mc.GetObject(ctx, bucket, objectName, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
defer object.Close()
return io.ReadAll(object)
}
func lf(format string, a ...any) {
fmt.Fprintf(os.Stderr, format, a...)
}
func lln(a ...any) {
fmt.Fprintln(os.Stderr, a...)
}
func renderKubeconfig(server string, tokens []string) (string, error) {
vm := jsonnet.MakeVM()
tks, err := json.Marshal(tokens)
if err != nil {
return "", err
}
vm.ExtVar("server", server)
vm.ExtCode("tokens", string(tks))
json, err := vm.EvaluateAnonymousSnippet("kubeconfig", kubectlTemplate)
if err != nil {
return "", err
}
yml, err := ky.JSONToYAML([]byte(json))
return string(yml), err
}
type bucketConfig struct {
Buckets []bucket `yaml:"buckets"`
}
type bucket struct {
// Endpoint is the S3 endpoint to use.
Endpoint string `yaml:"endpoint"`
// Bucket is the S3 bucket to use.
Bucket string `yaml:"bucket"`
// AccessKeyId and SecretAccessKey are the S3 credentials to use.
AccessKeyId string `yaml:"accessKeyId"`
// SecretAccessKey is the S3 secret access key to use.
SecretAccessKey string `yaml:"secretAccessKey"`
// Region is the AWS region to use.
Region string `yaml:"region,omitempty"`
// Insecure allows to use an insecure connection to the S3 endpoint.
Insecure bool `yaml:"insecure,omitempty"`
// ObjectNameTemplate is a template for the object name to use.
ObjectNameTemplate string `yaml:"objectNameTemplate,omitempty"`
}
// encryptedToken is the JSON structure of an encrypted token.
type encryptedToken struct {
Secrets []encryptedTokenSecret `json:"secrets"`
}
// encryptedTokenSecret is the JSON structure of an encrypted token secret.
type encryptedTokenSecret struct {
Data string `json:"data"`
}
// mfaCallback is a callback function for the passbolt client to handle MFA challenges.
// It will prompt the user for a TOTP token if needed.
// It will return the MFA cookie if successful.
// Currently only TOTP is supported, Passbolt does not support other MFA methods as of 05.04.2024.
func mfaCallback(ctx context.Context, c *api.Client, res *api.APIResponse) (http.Cookie, error) {
var challenge api.MFAChallenge
if err := json.Unmarshal(res.Body, &challenge); err != nil {
return http.Cookie{}, fmt.Errorf("error parsing MFA Challenge: %w", err)
}
if challenge.Provider.TOTP == "" {
return http.Cookie{}, fmt.Errorf("server provided no TOTP provider, only TOTP is supported currently")
}
code := envOrPrompt(envVarTOTPToken, "Passbolt TOTP token", false)
if code == "" {
lln("Passbolt TOTP token is required.")
os.Exit(1)
}
raw, apiRes, err := c.DoCustomRequestAndReturnRawResponse(ctx, "POST", "mfa/verify/totp.json", "v2", api.MFAChallengeResponse{
TOTP: code,
}, nil)
if err != nil {
return http.Cookie{}, fmt.Errorf("error verifying MFA challenge: %w (api response: %+v, code: %d)", err, apiRes, raw.StatusCode)
}
// MFA worked so lets find the cookie and return it
cookieNames := make([]string, 0, len(raw.Cookies()))
for _, cookie := range raw.Cookies() {
cookieNames = append(cookieNames, cookie.Name)
if cookie.Name == passboltMFACookieName {
return *cookie, nil
}
}
return http.Cookie{}, fmt.Errorf("unable to find MFA cookie %q, cookies found: %v", passboltMFACookieName, cookieNames)
}
// envOrPrompt returns the value of an environment variable or prompts the user for input.
// If the environment variable is empty, it will prompt the user for input.
// If the environment variable is empty and the terminal is not interactive, it will exit the program with an error.
// If the environment variable is not empty, it will return the value.
func envOrPrompt(envVar, inputDesc string, mask bool) string {
in := os.Getenv(envVar)
if in == "" && isTerminal {
var pf string
var err error
if mask {
pf, err = inputs.PassphraseInput(fmt.Sprintf("Enter your %s", inputDesc), "")
} else {
pf, err = inputs.LineInput(fmt.Sprintf("Enter your %s", inputDesc), "")
}
if err != nil {
lf("Error retrieving %s: %s\n", inputDesc, err)
os.Exit(1)
}
in = pf
} else if in == "" {
lf("%s cannot be empty.\n", inputDesc)
lf("Provide interactively or set %q environment variable.\n", envVar)
os.Exit(1)
} else {
lf("Using TOTP token from %q environment variable.\n", envVar)
}
return in
}