-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathconfig_trust.go
693 lines (553 loc) · 16.2 KB
/
config_trust.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
package main
import (
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
"github.com/canonical/lxd/shared/termios"
)
type cmdConfigTrust struct {
global *cmdGlobal
config *cmdConfig
}
func (c *cmdConfigTrust) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("trust")
cmd.Short = i18n.G("Manage trusted clients")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage trusted clients`))
// Add
configTrustAddCmd := cmdConfigTrustAdd{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustAddCmd.command())
// Edit
configTrustEditCmd := cmdConfigTrustEdit{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustEditCmd.command())
// List
configTrustListCmd := cmdConfigTrustList{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustListCmd.command())
// List tokens
configTrustListTokensCmd := cmdConfigTrustListTokens{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustListTokensCmd.command())
// Remove
configTrustRemoveCmd := cmdConfigTrustRemove{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustRemoveCmd.command())
// Revoke token
configTrustRevokeTokenCmd := cmdConfigTrustRevokeToken{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustRevokeTokenCmd.command())
// Show
configTrustShowCmd := cmdConfigTrustShow{global: c.global, config: c.config, configTrust: c}
cmd.AddCommand(configTrustShowCmd.command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
// Add.
type cmdConfigTrustAdd struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
flagName string
flagProjects string
flagRestricted bool
flagType string
}
func (c *cmdConfigTrustAdd) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("add", i18n.G("[<remote>:] [<cert>]"))
cmd.Short = i18n.G("Add new trusted client")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Add new trusted client
The following certificate types are supported:
- client (default)
- metrics
If the certificate is omitted, a token will be generated and returned. A client
providing a valid token will have its client certificate added to the trusted list
and the consumed token will be invalidated. Similar to certificates, tokens can be
restricted to one or more projects.
`))
cmd.Flags().BoolVar(&c.flagRestricted, "restricted", false, i18n.G("Restrict the certificate to one or more projects"))
cmd.Flags().StringVar(&c.flagProjects, "projects", "", i18n.G("List of projects to restrict the certificate to")+"``")
cmd.Flags().StringVar(&c.flagName, "name", "", i18n.G("Alternative certificate name")+"``")
cmd.Flags().StringVar(&c.flagType, "type", "client", i18n.G("Type of certificate")+"``")
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustAdd) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 2)
if exit {
return err
}
// Validate flags.
if !shared.ValueInSlice(c.flagType, []string{"client", "metrics"}) {
return fmt.Errorf(i18n.G("Unknown certificate type %q"), c.flagType)
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
if c.flagType == "metrics" && !resource.server.HasExtension("metrics") {
return errors.New("The server doesn't implement metrics")
}
cert := api.CertificatesPost{}
// Check if remote is the first argument
// to detect method of adding trusted client
useToken := false
if len(args) == 0 || (len(args) == 1 && resource.name == "") {
useToken = true
}
if useToken {
// Use token
cert.Token = true
if c.flagName != "" {
cert.Name = c.flagName
} else {
cert.Name, err = c.global.asker.AskString(i18n.G("Please provide client name: "), "", nil)
if err != nil {
return err
}
}
} else {
// Load the certificate.
fname := args[len(args)-1]
if fname == "-" {
fname = "/dev/stdin"
} else {
fname = shared.HostPathFollow(fname)
}
var name string
if c.flagName != "" {
name = c.flagName
} else {
name = filepath.Base(fname)
}
// Add trust relationship.
x509Cert, err := shared.ReadCert(fname)
if err != nil {
return err
}
cert.Certificate = base64.StdEncoding.EncodeToString(x509Cert.Raw)
cert.Name = name
}
if c.flagType == "client" {
cert.Type = api.CertificateTypeClient
} else if c.flagType == "metrics" {
if cert.Token {
return errors.New(i18n.G("Cannot use metrics type certificate when using a token"))
}
cert.Type = api.CertificateTypeMetrics
}
cert.Restricted = c.flagRestricted
if c.flagProjects != "" {
cert.Projects = strings.Split(c.flagProjects, ",")
}
if cert.Token {
op, err := resource.server.CreateCertificateToken(cert)
if err != nil {
return err
}
opAPI := op.Get()
certificateToken, err := opAPI.ToCertificateAddToken()
if err != nil {
return fmt.Errorf(i18n.G("Failed converting token operation to certificate add token: %w"), err)
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Client %s certificate add token:")+"\n", cert.Name)
}
fmt.Println(certificateToken.String())
return nil
}
return resource.server.CreateCertificate(cert)
}
// Edit.
type cmdConfigTrustEdit struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
}
func (c *cmdConfigTrustEdit) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<fingerprint>"))
cmd.Short = i18n.G("Edit trust configurations as YAML")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit trust configurations as YAML`))
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustEdit) helpTemplate() string {
return i18n.G(
`### This is a YAML representation of the certificate.
### Any line starting with a '# will be ignored.
###
### Note that the fingerprint is shown but cannot be changed`)
}
func (c *cmdConfigTrustEdit) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
if resource.name == "" {
return errors.New(i18n.G("Missing certificate fingerprint"))
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
contents, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
newdata := api.CertificatePut{}
err = yaml.Unmarshal(contents, &newdata)
if err != nil {
return err
}
return resource.server.UpdateCertificate(resource.name, newdata, "")
}
// Extract the current value
cert, etag, err := resource.server.GetCertificate(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&cert)
if err != nil {
return err
}
// Spawn the editor
content, err := shared.TextEditor("", []byte(c.helpTemplate()+"\n\n"+string(data)))
if err != nil {
return err
}
for {
// Parse the text received from the editor
newdata := api.CertificatePut{}
err = yaml.Unmarshal(content, &newdata)
if err == nil {
err = resource.server.UpdateCertificate(resource.name, newdata, etag)
}
// Respawn the editor
if err != nil {
fmt.Fprintf(os.Stderr, i18n.G("Config parsing error: %s")+"\n", err)
fmt.Println(i18n.G("Press enter to open the editor again or ctrl+c to abort change"))
_, err := os.Stdin.Read(make([]byte, 1))
if err != nil {
return err
}
content, err = shared.TextEditor("", content)
if err != nil {
return err
}
continue
}
break
}
return nil
}
// List.
type cmdConfigTrustList struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
flagFormat string
}
func (c *cmdConfigTrustList) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list", i18n.G("[<remote>:]"))
cmd.Aliases = []string{"ls"}
cmd.Short = i18n.G("List trusted clients")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List trusted clients`))
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustList) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote
remote := ""
if len(args) > 0 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// List trust relationships
trust, err := resource.server.GetCertificates()
if err != nil {
return err
}
data := [][]string{}
for _, cert := range trust {
fp := cert.Fingerprint[0:12]
certBlock, _ := pem.Decode([]byte(cert.Certificate))
if certBlock == nil {
return errors.New(i18n.G("Invalid certificate"))
}
tlsCert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return err
}
const layout = "Jan 2, 2006 at 3:04pm (MST)"
issue := tlsCert.NotBefore.Format(layout)
expiry := tlsCert.NotAfter.Format(layout)
data = append(data, []string{cert.Type, cert.Name, tlsCert.Subject.CommonName, fp, issue, expiry})
}
sort.Sort(cli.StringList(data))
header := []string{
i18n.G("TYPE"),
i18n.G("NAME"),
i18n.G("COMMON NAME"),
i18n.G("FINGERPRINT"),
i18n.G("ISSUE DATE"),
i18n.G("EXPIRY DATE"),
}
return cli.RenderTable(c.flagFormat, header, data, trust)
}
// List tokens.
type cmdConfigTrustListTokens struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
flagFormat string
}
func (c *cmdConfigTrustListTokens) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("list-tokens", i18n.G("[<remote>:]"))
cmd.Short = i18n.G("List all active certificate add tokens")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`List all active certificate add tokens`))
cmd.Flags().StringVarP(&c.flagFormat, "format", "f", "table", i18n.G("Format (csv|json|table|yaml|compact)")+"``")
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustListTokens) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 0, 1)
if exit {
return err
}
// Parse remote.
remote := ""
if len(args) == 1 {
remote = args[0]
}
resources, err := c.global.ParseServers(remote)
if err != nil {
return err
}
resource := resources[0]
// Get the certificate add tokens. Use default project as join tokens are created in default project.
ops, err := resource.server.UseProject("default").GetOperations()
if err != nil {
return err
}
// Convert the join token operation into encoded form for display.
type displayToken struct {
ClientName string
Token string
ExpiresAt string
}
displayTokens := make([]displayToken, 0)
for _, op := range ops {
if op.Class != api.OperationClassToken {
continue
}
if op.StatusCode != api.Running {
continue // Tokens are single use, so if cancelled but not deleted yet its not available.
}
joinToken, err := op.ToCertificateAddToken()
if err != nil {
continue // Operation is not a valid certificate add token operation.
}
var expiresAt string
// Only show the expiry date if available, otherwise show an empty string.
if joinToken.ExpiresAt.Unix() > 0 {
expiresAt = joinToken.ExpiresAt.Format("2006/01/02 15:04 MST")
}
displayTokens = append(displayTokens, displayToken{
ClientName: joinToken.ClientName,
Token: joinToken.String(),
ExpiresAt: expiresAt,
})
}
// Render the table.
data := [][]string{}
for _, token := range displayTokens {
line := []string{token.ClientName, token.Token, token.ExpiresAt}
data = append(data, line)
}
sort.Sort(cli.SortColumnsNaturally(data))
header := []string{
i18n.G("NAME"),
i18n.G("TOKEN"),
i18n.G("EXPIRES AT"),
}
return cli.RenderTable(c.flagFormat, header, data, displayTokens)
}
// Remove.
type cmdConfigTrustRemove struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
}
func (c *cmdConfigTrustRemove) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("remove", i18n.G("[<remote>:]<fingerprint>"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Remove trusted client")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Remove trusted client`))
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustRemove) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 2)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
// Support both legacy "<remote>: <fingerprint>" and current "<remote>:<fingerprint>".
var fingerprint string
if len(args) == 2 {
fingerprint = args[1]
} else {
fingerprint = resource.name
}
// Remove trust relationship
return resource.server.DeleteCertificate(fingerprint)
}
// List tokens.
type cmdConfigTrustRevokeToken struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
}
func (c *cmdConfigTrustRevokeToken) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("revoke-token", i18n.G("[<remote>:] <name>"))
cmd.Short = i18n.G("Revoke certificate add token")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Revoke certificate add token`))
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustRevokeToken) run(cmd *cobra.Command, args []string) error {
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
// Get the certificate add tokens. Use default project as certificate add tokens are created in default project.
ops, err := resource.server.UseProject("default").GetOperations()
if err != nil {
return err
}
for _, op := range ops {
if op.Class != api.OperationClassToken {
continue
}
if op.StatusCode != api.Running {
continue // Tokens are single use, so if cancelled but not deleted yet its not available.
}
joinToken, err := op.ToCertificateAddToken()
if err != nil {
continue // Operation is not a valid certificate add token operation.
}
if joinToken.ClientName == resource.name {
// Delete the operation
err = resource.server.DeleteOperation(op.ID)
if err != nil {
return err
}
if !c.global.flagQuiet {
fmt.Printf(i18n.G("Certificate add token for %s deleted")+"\n", resource.name)
}
return nil
}
}
return fmt.Errorf(i18n.G("No certificate add token for member %s on remote: %s"), resource.name, resource.remote)
}
// Show.
type cmdConfigTrustShow struct {
global *cmdGlobal
config *cmdConfig
configTrust *cmdConfigTrust
}
func (c *cmdConfigTrustShow) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("show", i18n.G("[<remote>:]<fingerprint>"))
cmd.Short = i18n.G("Show trust configurations")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Show trust configurations`))
cmd.RunE = c.run
return cmd
}
func (c *cmdConfigTrustShow) run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
client := resource.server
if resource.name == "" {
return errors.New(i18n.G("Missing certificate fingerprint"))
}
// Show the certificate configuration
cert, _, err := client.GetCertificate(resource.name)
if err != nil {
return err
}
data, err := yaml.Marshal(&cert)
if err != nil {
return err
}
fmt.Printf("%s", data)
return nil
}