/
client.go
1351 lines (1262 loc) · 38.4 KB
/
client.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ui
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/chzyer/readline"
"golang.org/x/crypto/ed25519"
"github.com/labstack/gommon/log"
"github.com/aakso/ssh-inscribe/internal/globals"
"github.com/aakso/ssh-inscribe/internal/util"
"github.com/ScaleFT/sshkeys"
"github.com/blang/semver/v4"
"github.com/pkg/errors"
"github.com/skratchdot/open-golang/open"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"gopkg.in/resty.v1"
"github.com/aakso/ssh-inscribe/internal/auth"
"github.com/aakso/ssh-inscribe/internal/server/signapi/objects"
)
const (
CredentialTypeUser = "username"
CredentialTypePassword = "password"
CredentialTypePin = "pin"
CurrentApiVersion = "v1"
// AgentComment is a comment to use for keys on agent.
AgentComment = "ssh-inscribe managed"
FederatedAuthenticatorPollInterval = 3
DefaultGenerateKeypairSize = 2048
)
const spinner = `\|/-`
type ignoreRedirects struct{}
func (ir *ignoreRedirects) Apply(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
type Client struct {
Config *Config
rest *resty.Client
restSRV *resty.SRVRecord
agentClient agent.Agent
agentConn net.Conn
credentialInput func(name, realm, credentialType, def string) ([]byte, error)
ca ssh.PublicKey
userPrivateKey interface{}
userCerts []*ssh.Certificate
signerToken []byte
serverVersion semver.Version
}
func (c *Client) getCredential(name, realm, credentialType, def string) ([]byte, error) {
if c.credentialInput == nil {
c.credentialInput = interactiveCredentialsPrompt
}
return c.credentialInput(name, realm, credentialType, def)
}
func (c *Client) AddCA() error {
if err := c.initREST(); err != nil {
return errors.Wrap(err, "could not add ca")
}
if err := c.checkVersion(); err != nil {
return errors.Wrap(err, "could not add ca")
}
if err := c.authenticate(); err != nil {
return errors.Wrap(err, "could not add ca")
}
if c.Config.CAChallenge {
return c.caChallenge()
}
return c.addCAKey()
}
func (c *Client) ChallengeResponse() error {
if err := c.initREST(); err != nil {
return errors.Wrap(err, "could not add ca")
}
if err := c.checkVersion(); err != nil {
return errors.Wrap(err, "could not add ca")
}
if err := c.authenticate(); err != nil {
return errors.Wrap(err, "could not add ca")
}
return c.sendChallengeResponse()
}
func (c *Client) GetCA() (ssh.PublicKey, error) {
if err := c.initREST(); err != nil {
return nil, errors.Wrap(err, "could not get ca")
}
if err := c.checkVersion(); err != nil {
return nil, errors.Wrap(err, "could not get ca")
}
if err := c.discoverCA(); err != nil {
return nil, errors.Wrap(err, "could not get ca")
}
return c.ca, nil
}
func (c *Client) GetServerVersion() (semver.Version, error) {
if err := c.initREST(); err != nil {
return semver.Version{}, errors.Wrap(err, "could not get server version")
}
if err := c.discoverServerVersion(); err != nil {
return semver.Version{}, errors.Wrap(err, "could not get server version")
}
if c.serverVersion.EQ(semver.Version{}) {
return semver.Version{}, errors.New("no server version available")
}
return c.serverVersion, nil
}
func (c *Client) GetAuthenticators() ([]objects.DiscoverResult, error) {
if err := c.initREST(); err != nil {
return nil, errors.Wrap(err, "could not get ca")
}
return c.discoverAuthenticators()
}
func (c *Client) Logout() error {
if err := c.initREST(); err != nil {
return errors.Wrap(err, "could not logout")
}
if err := c.checkVersion(); err != nil {
return errors.Wrap(err, "could not logout")
}
if err := c.discoverCA(); err != nil {
return errors.Wrap(err, "could not logout")
}
if c.Config.UseAgent {
if err := c.connectAgent(); err != nil {
return errors.Wrap(err, "could not logout")
}
if err := c.deleteCertsFromAgent(); err != nil {
return errors.Wrap(err, "could not logout")
}
}
return nil
}
func (c *Client) Login() error {
if err := c.initREST(); err != nil {
return errors.Wrap(err, "could not login")
}
if err := c.checkVersion(); err != nil {
return errors.Wrap(err, "could not login")
}
if err := c.discoverCA(); err != nil {
return errors.Wrap(err, "could not login")
}
if c.Config.UseAgent {
if err := c.connectAgent(); err != nil {
return errors.Wrap(err, "could not login")
}
if err := c.discoverCertFromAgent(); err != nil {
return errors.Wrap(err, "could not login")
}
if !c.Config.AlwaysRenew && len(c.userCerts) > 0 {
Log.Debug("certificate found on agent and already valid")
return nil
}
}
if c.Config.IdentityFile != "" && !c.Config.GenerateKeypair {
if err := c.discoverIdentityFile(); err != nil {
return errors.Wrap(err, "could not login")
}
if !c.Config.AlwaysRenew && c.userCerts != nil {
Log.Debug("certificate found from file and already valid")
return nil
}
}
// Generate ad-hoc keypair in case no private key is provided
if c.Config.GenerateKeypair && c.userPrivateKey == nil {
if err := c.generate(); err != nil {
return errors.Wrap(err, "could not login")
}
}
if c.userPrivateKey == nil {
return errors.New("could not continue. No private key")
}
c.userCerts = nil
if err := c.authenticate(); err != nil {
return errors.Wrap(err, "could not login")
}
if err := c.sign(); err != nil {
return errors.Wrap(err, "could not login")
}
if c.Config.UseAgent {
if err := c.storeInAgent(); err != nil {
return errors.Wrap(err, "could not store certificate to an agent")
}
}
if c.Config.IdentityFile != "" && c.Config.WriteCert {
if err := c.storeInFile(); err != nil {
return errors.Wrap(err, "could not store certificate to a file")
}
}
if !c.Config.UseAgent && !c.Config.WriteCert {
for _, cert := range c.userCerts {
fmt.Printf("%s", ssh.MarshalAuthorizedKey(cert))
}
}
if !c.Config.Quiet {
for i, cert := range c.userCerts {
if i > 0 {
fmt.Println()
}
if len(c.userCerts) > 1 {
fmt.Printf("CERT DETAILS (%d/%d):\n", i+1, len(c.userCerts))
} else {
fmt.Println("CERT DETAILS:")
}
c.printCertificate(cert)
}
}
return nil
}
// Add CA key to server from file.
func (c *Client) addCAKey() error {
log := Log.WithField("action", "addCAKey")
log.Debug("reading ca key file")
var (
content []byte
err error
)
if c.Config.CAKeyFile == "" {
fmt.Println("Paste in the private key. End of file terminates (Ctrl+d).")
err = readMultipleLines("> ", func(l []byte) bool {
content = append(content, l...)
content = append(content, '\n')
return true
})
if err != nil {
return err
}
} else {
content, err = os.ReadFile(c.Config.CAKeyFile)
if err != nil {
return errors.Wrap(err, "could not open ca key file")
}
}
key, err := c.parsePrivateKey(content, "CA private key")
if err != nil {
return errors.Wrap(err, "could not parse ca key")
}
opts := &sshkeys.MarshalOptions{}
switch key.(type) {
case *ed25519.PrivateKey:
opts.Format = sshkeys.FormatOpenSSHv1
default:
opts.Format = sshkeys.FormatClassicPEM
}
content, err = sshkeys.Marshal(key, opts)
if err != nil {
return errors.Wrap(err, "could not marshal ca key")
}
log.Debug("sending ca key to the server")
res, err := c.newReq().
SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken)).
SetBody(content).
Post(c.urlFor("ca"))
if err != nil {
return errors.Wrap(err, "could not send key")
}
if res.StatusCode() != http.StatusAccepted {
return errors.Errorf("could not send key, got code %d and message: %s", res.StatusCode(), res.Body())
}
log.Debug("sent ca key to the server")
return nil
}
func (c *Client) caChallenge() error {
log := Log.WithField("action", "addCAKeyViaChallenge")
log.Debug("reading ca key file")
var (
content []byte
err error
)
if c.Config.CAKeyFile == "" {
fmt.Println("Paste in the private key. End of file terminates (Ctrl+d).")
err = readMultipleLines("> ", func(l []byte) bool {
content = append(content, l...)
content = append(content, '\n')
return true
})
if err != nil {
return err
}
} else {
content, err = os.ReadFile(c.Config.CAKeyFile)
if err != nil {
return errors.Wrap(err, "could not open ca key file")
}
}
log.Debug("sending ca key to the server to initiate challenge")
log.Debug(string(content))
res, err := c.newReq().
SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken)).
SetBody(content).
Post(c.urlFor("ca") + "?init_challenge=true")
if err != nil {
return errors.Wrap(err, "could not send key")
}
if res.StatusCode() != http.StatusAccepted {
return errors.Errorf("could not send key, got code %d and message: %s", res.StatusCode(), res.Body())
}
log.Debug("initiated a CA challenge")
fmt.Printf("Challenge:\n%v\n", string(res.Body()))
return nil
}
func (c *Client) sendChallengeResponse() error {
log := Log.WithField("action", "sendChallengeResponse")
challenge, err := c.getCredential("ca-challenge", "signer", "challenge", "")
if err != nil {
return err
}
response, err := c.getCredential("ca-challenge-response", "signer", CredentialTypePassword, "")
if err != nil {
return err
}
log.Debug("sending challenge-response to the server")
res, err := c.newReq().
SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken)).
SetBody(challenge).
SetBasicAuth("", string(response)).
Post(c.urlFor("ca/response"))
if err != nil {
return errors.Wrap(err, "could not send challenge-response")
}
if res.StatusCode() != http.StatusOK {
return errors.Errorf("could not send challenge-response, got code %d and message: %s", res.StatusCode(), res.Body())
}
log.Debug("sent challenge-response to the server")
return nil
}
// generate generates an ad-hoc keypair.
func (c *Client) generate() error {
var (
key interface{}
err error
)
log := Log.WithField("action", "generate").
WithField("type", c.Config.GenerateKeypairType)
size := c.Config.GenerateKeypairSize
if size == 0 {
size = DefaultGenerateKeypairSize
}
switch strings.ToLower(c.Config.GenerateKeypairType) {
case "rsa":
log = log.WithField("size", size)
key, err = rsa.GenerateKey(rand.Reader, size)
if err != nil {
return errors.Wrap(err, "could not generate RSA key")
}
case "ed25519":
log = log.WithField("size", ed25519.PrivateKeySize)
_, edKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return errors.Wrap(err, "could not generate RSA key")
}
// Workaround: store ed25519 as pointer to slice as that is what
// golang.org/x/crypto/ssh parsing functions return
key = &edKey
}
log.Debug("generated keypair")
c.userPrivateKey = key
return nil
}
func (c *Client) windowsStoreInAgentWorkaround(addedKey *agent.AddedKey) error {
// At the moment Microsoft's ssh-agent doesn't seem to support constraints
// Add this workaround to try to add the without them and warn the user
log := Log.WithField("action", "windowsStoreInAgentWorkaround")
log.Warn("Failed to add key to the agent. Running on Windows, trying to add the key without constraints")
// We need to reconnect after a failure
if err := c.connectAgent(); err != nil {
return err
}
addedKey.LifetimeSecs = 0
addedKey.ConfirmBeforeUse = false
return c.agentClient.Add(*addedKey)
}
// storeInAgent stores the signed certs to an ssh-agent and removes all other instances of certificates
// signed by the CA.
func (c *Client) storeInAgent() error {
log := Log.WithField("action", "storeInAgent")
log.Debug("cleaning up old certificates")
err := c.deleteCertsFromAgent()
if err != nil {
return err
}
for i, cert := range c.userCerts {
// Find out if our private key is already in the agent. In that case let us not
// add time constraint to it
keyInAgent := i > 0
if i == 0 {
err = iterAgentKeys(c.agentClient, func(key ssh.PublicKey, comment string) error {
if bytes.Equal(key.Marshal(), cert.Key.Marshal()) {
log.Debug("private key already in agent")
keyInAgent = true
}
return nil
})
if err != nil {
return errors.Wrap(err, "could not get agent keys")
}
}
var lifetime uint32
if cert.ValidBefore != 0 {
lifetime = uint32(time.Until(time.Unix(int64(cert.ValidBefore), 0)).Seconds())
}
addedKey := agent.AddedKey{
PrivateKey: c.userPrivateKey,
Certificate: cert,
Comment: AgentComment,
LifetimeSecs: lifetime,
ConfirmBeforeUse: c.Config.AgentConfirm,
}
microsoftSSHAgent := false
if err := c.agentClient.Add(addedKey); err != nil {
if runtime.GOOS == "windows" {
err = c.windowsStoreInAgentWorkaround(&addedKey)
microsoftSSHAgent = true
}
if err != nil {
return errors.Wrap(err, "could not add to agent")
}
}
log.WithField("keyid", cert.KeyId).
WithField("confirm_before_use", c.Config.AgentConfirm).
WithField("lifetime_secs", addedKey.LifetimeSecs).Debug("added certificate")
// Microsoft ssh-agent seems to overwrite the certificate
if !keyInAgent && !microsoftSSHAgent {
addedKey = agent.AddedKey{
PrivateKey: c.userPrivateKey,
Comment: AgentComment,
LifetimeSecs: lifetime,
ConfirmBeforeUse: c.Config.AgentConfirm,
}
if err := c.agentClient.Add(addedKey); err != nil {
if runtime.GOOS == "windows" {
err = c.windowsStoreInAgentWorkaround(&addedKey)
}
if err != nil {
return errors.Wrap(err, "could not add to agent")
}
}
log.WithField("lifetime_secs", addedKey.LifetimeSecs).
WithField("confirm_before_use", addedKey.ConfirmBeforeUse).Debug("added private key")
} else if c.Config.AgentConfirm {
log.Warning("agent confirmation requested but the private key is already in the agent, not adding the constraint")
}
}
return nil
}
func (c *Client) storeInFile() error {
log := Log.WithField("action", "storeInFile")
// If we have been requested to generate a keypair, save it
if c.Config.GenerateKeypair {
privFile := c.Config.IdentityFile
if abs, _ := filepath.Abs(privFile); abs != "" {
privFile = abs
}
// Save private
log.WithField("file", privFile).Debug("saving to file")
fhPriv, err := os.OpenFile(c.Config.IdentityFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return errors.Wrap(err, "could not save to file")
}
defer fhPriv.Close()
opts := &sshkeys.MarshalOptions{}
switch c.userPrivateKey.(type) {
case *ed25519.PrivateKey:
opts.Format = sshkeys.FormatOpenSSHv1
default:
opts.Format = sshkeys.FormatClassicPEM
}
content, err := sshkeys.Marshal(c.userPrivateKey, opts)
if err != nil {
return errors.Wrap(err, "could not marshal private key")
}
if _, err := fhPriv.Write(content); err != nil {
return errors.Wrap(err, "could not write private key")
}
fmt.Println(privFile)
log.WithField("file", privFile).Debug("saved to file")
// Save public
pubFile := c.Config.IdentityFile + ".pub"
if abs, _ := filepath.Abs(pubFile); abs != "" {
pubFile = abs
}
log.WithField("file", pubFile).Debug("saving to file")
fhPub, err := os.Create(pubFile)
if err != nil {
return errors.Wrap(err, "could not save to file")
}
defer fhPub.Close()
signer, err := ssh.NewSignerFromKey(c.userPrivateKey)
if err != nil {
return errors.Wrap(err, "unexpected error")
}
if _, err := fhPub.Write(ssh.MarshalAuthorizedKey(signer.PublicKey())); err != nil {
return errors.Wrap(err, "could not write public key")
}
fmt.Println(pubFile)
log.WithField("file", pubFile).Debug("saved to file")
}
multipleCerts := len(c.userCerts) > 1
createdFileHandles := make([]*os.File, 0, len(c.userCerts))
defer func() {
for _, fh := range createdFileHandles {
_ = fh.Close()
}
}()
for i, cert := range c.userCerts {
var certFile string
if multipleCerts {
certFile = fmt.Sprintf("%s-cert%d.pub", c.Config.IdentityFile, i+1)
} else {
certFile = c.Config.IdentityFile + "-cert.pub"
}
if abs, _ := filepath.Abs(certFile); abs != "" {
certFile = abs
}
log.WithField("file", certFile).Debug("saving to file")
fh, err := os.Create(certFile)
if err != nil {
return errors.Wrap(err, "could not save to file")
}
createdFileHandles = append(createdFileHandles, fh)
if _, err := fh.Write(ssh.MarshalAuthorizedKey(cert)); err != nil {
return errors.Wrap(err, "could not save to file")
}
fmt.Println(certFile)
log.WithField("file", certFile).Debug("saved to file")
}
return nil
}
// sign requests signed certificate from the server.
func (c *Client) sign() error {
log := Log.WithField("action", "sign")
log.Debug("requesting certificate")
signer, err := ssh.NewSignerFromKey(c.userPrivateKey)
if err != nil {
return errors.Wrap(err, "unexpected error")
}
req := c.newReq().
SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken)).
SetBody(ssh.MarshalAuthorizedKey(signer.PublicKey()))
if c.Config.CertLifetime != 0 {
expires := time.Now().Add(c.Config.CertLifetime).Format(time.RFC3339)
req.SetQueryParam("expires", expires)
}
if c.Config.IncludePrincipals != "" {
req.SetQueryParam("include_principals", c.Config.IncludePrincipals)
}
if c.Config.ExcludePrincipals != "" {
req.SetQueryParam("exclude_principals", c.Config.ExcludePrincipals)
}
if c.Config.SigningOption != "" {
req.SetQueryParam("signing_option", c.Config.SigningOption)
}
if c.Config.MaxPrincipalsPerCertificate > 0 {
req.SetQueryParam("max_principals_per_certificate",
strconv.FormatInt(int64(c.Config.MaxPrincipalsPerCertificate), 10))
}
res, err := req.Post(c.urlFor("sign"))
if err != nil {
return errors.Wrap(err, "could not sign")
}
if res.StatusCode() != http.StatusOK {
return errors.Errorf("could not sign got code %d and message: %s", res.StatusCode(), res.Body())
}
rawCerts := res.Body()
for len(rawCerts) > 0 {
var pubKey ssh.PublicKey
pubKey, _, _, rawCerts, err = ssh.ParseAuthorizedKey(rawCerts)
if err != nil {
return errors.Wrap(err, "cannot parse ssh public key")
}
cert, _ := pubKey.(*ssh.Certificate)
if cert == nil {
return errors.Errorf("could not parse certificate. Unexpected type %T", pubKey)
}
c.userCerts = append(c.userCerts, cert)
log.WithField("keyid", cert.KeyId).Debug("certificate received")
}
return nil
}
func (c *Client) authenticateFederated(authName, authRealm string) error {
log := Log.WithField("action", "authenticateFederated").
WithField("authenticator", authName)
log.Debug("making initial authentication request to get the auth url")
initial := true
req := c.newReq()
for i := 0; true; i++ {
if c.signerToken != nil {
req.SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken))
}
res, err := req.Post(c.urlFor("auth/" + authName))
if err != nil {
return errors.Wrap(err, "could not authenticate")
}
switch res.StatusCode() {
case http.StatusSeeOther:
c.signerToken = res.Body()
if initial {
url := res.Header().Get("Location")
openFederatedAuthURL(url)
}
fmt.Printf("\rWaiting for authentication to complete for %q (%s) %s ",
authName,
authRealm,
string(spinner[i%4]))
time.Sleep(FederatedAuthenticatorPollInterval * time.Second)
initial = false
case http.StatusOK:
fmt.Println()
c.signerToken = res.Body()
log.Debug("authentication successful")
return nil
case http.StatusUnauthorized:
return errors.New("authentication failed")
default:
return errors.Errorf("unknown federated auth response: %d", res.StatusCode())
}
}
return errors.New("could not authenticate")
}
func (c *Client) discoverAuthenticators() ([]objects.DiscoverResult, error) {
log := Log.WithField("action", "discoverAuthenticators")
log.Debug("discovering authenticators")
res, err := c.newReq().
SetResult([]objects.DiscoverResult{}).
Get(c.urlFor("auth"))
if err != nil {
return nil, errors.Wrap(err, "could not discover authenticators")
}
discoverResult, _ := res.Result().(*[]objects.DiscoverResult)
if discoverResult == nil {
return nil, errors.New("could not parse auth discovery result")
}
return *discoverResult, nil
}
// authenticate performs authentication discovery and login.
func (c *Client) authenticate() error {
log := Log.WithField("action", "authenticate")
log.Debug("discovering authenticators")
discoverResult, err := c.discoverAuthenticators()
if err != nil {
return err
}
// Make the final authenticator list based on user request or the
// default setting in server configuration
var (
defaultAuthenticators []objects.DiscoverResult
finalAuthenticators []objects.DiscoverResult
)
availableAuthenticators := map[string]objects.DiscoverResult{}
for _, au := range discoverResult {
if au.Default {
defaultAuthenticators = append(defaultAuthenticators, au)
}
availableAuthenticators[au.AuthenticatorName] = au
}
switch {
case len(c.Config.LoginAuthEndpoints) > 0:
for _, v := range c.Config.LoginAuthEndpoints {
if au, ok := availableAuthenticators[v]; !ok {
return errors.Errorf("unknown auth endpoint name: %s", v)
} else {
finalAuthenticators = append(finalAuthenticators, au)
}
}
case len(defaultAuthenticators) > 0:
finalAuthenticators = defaultAuthenticators
case len(discoverResult) > 0:
finalAuthenticators = append(finalAuthenticators, discoverResult[0])
default:
return errors.New("cannot continue, no authenticators returned from the server")
}
log.WithField("authenticator_list", finalAuthenticators).Debug("begin authentication")
outer:
for _, au := range finalAuthenticators {
var (
userName string
err error
)
for {
var (
cred []byte
secret string
)
switch au.AuthenticatorCredentialType {
case auth.CredentialUserPassword:
if userName == "" {
userName = getCurrentUsername()
}
if cred, err = c.getCredential(au.AuthenticatorName, au.AuthenticatorRealm, CredentialTypeUser, userName); err != nil {
return err
}
userName = string(cred)
if cred, err = c.getCredential(au.AuthenticatorName, au.AuthenticatorRealm, CredentialTypePassword, ""); err != nil {
return err
}
secret = string(cred)
case auth.CredentialPin:
if cred, err = c.getCredential(au.AuthenticatorName, au.AuthenticatorRealm, CredentialTypePin, ""); err != nil {
return err
}
secret = string(cred)
case auth.CredentialFederated:
if err = c.authenticateFederated(au.AuthenticatorName, au.AuthenticatorRealm); err != nil {
return err
}
continue outer
default:
return errors.Errorf("unknown credential type %s", au.AuthenticatorCredentialType)
}
log.WithField("authenticator", au.AuthenticatorName).Debug("authenticating")
// Send Credentials
req := c.newReq().SetBasicAuth(userName, secret)
if c.signerToken != nil {
req.SetHeader("X-Auth", fmt.Sprintf("Bearer %s", c.signerToken))
}
res, err := req.Post(c.urlFor("auth/" + au.AuthenticatorName))
if err != nil {
return errors.Wrap(err, "could not authenticate")
}
if res.StatusCode() == http.StatusOK {
c.signerToken = res.Body()
log.WithField("authenticator", au.AuthenticatorName).Debug("authentication successful")
break
}
log.WithField("authenticator", au.AuthenticatorName).Debug("authentication failed")
fmt.Println("Authentication failed.")
}
}
return nil
}
// parsePrivateKey parses the private key and decrypts it if necessary.
func (c *Client) parsePrivateKey(raw []byte, desc string) (interface{}, error) {
var (
secret []byte
key interface{}
err error
)
haveSecret := false
outer:
for {
key, err = sshkeys.ParseEncryptedRawPrivateKey(raw, secret)
switch err := err.(type) {
case *ssh.PassphraseMissingError:
if haveSecret {
return nil, err
}
log.Debug("encrypted identity file")
var err2 error
if secret, err2 = c.getCredential("private key", desc, CredentialTypePassword, ""); err2 != nil {
return nil, err2
}
haveSecret = true
default:
if err == nil {
break outer
}
return nil, err
}
}
return key, nil
}
// discoverIdentityFile discovers users private key and certificate from file.
func (c *Client) discoverIdentityFile() error {
log := Log.WithField("action", "discoverIdentityFile")
log.Debug("reading identity file")
content, err := os.ReadFile(c.Config.IdentityFile)
if err != nil {
return errors.Wrap(err, "could not open identity file")
}
key, err := c.parsePrivateKey(content, c.Config.IdentityFile)
if err != nil {
return errors.Wrap(err, "could not parse private key")
}
c.userPrivateKey = key
log.Debug("parsed identity file")
// Certificate
certFiles := []string{
fmt.Sprintf("%s-cert.pub", c.Config.IdentityFile),
fmt.Sprintf("%s-cert1.pub", c.Config.IdentityFile),
}
for _, certFile := range certFiles {
log := log.WithField("file", certFile)
content, err = os.ReadFile(certFile)
if os.IsNotExist(err) {
log.Debug("no certificate file found")
continue
} else if err != nil {
return errors.Wrap(err, "could not open certificate file")
}
log.Debug("found certificate")
parsed, _, _, _, err := ssh.ParseAuthorizedKey(content)
if err != nil {
return errors.Wrapf(err, "could not parse certificate file %q", certFile)
}
cert, _ := parsed.(*ssh.Certificate)
if cert == nil {
return errors.New("could not parse certificate")
}
if !shallowCertChecker(cert, c.ca) {
log.WithField("keyid", cert.KeyId).Debug("invalid or expired certificate, skipping")
continue
}
log.WithField("keyid", cert.KeyId).Debug("parsed certificate")
c.userCerts = append(c.userCerts, cert)
}
return nil
}
// discoverCA discovers the signing ca from remote server.
func (c *Client) discoverCA() error {
log := Log.WithField("action", "discoverCA")
if c.ca != nil {
return nil
}
log.Debug("discovering ca")
res, err := c.newReq().Get(c.urlFor("ca"))
if err != nil {
return errors.Wrap(err, "could not discover CA")
}
if res.StatusCode() != http.StatusOK {
return errors.Errorf("could not discover CA, got code %d and message: %s", res.StatusCode(), res.Body())
}
key, _, _, _, err := ssh.ParseAuthorizedKey(res.Body())
if err != nil {
return errors.Wrap(err, "could not parse CA key")
}
log.WithField("fingerprint", ssh.FingerprintSHA256(key)).Debug("discovered ca")
c.ca = key
return nil
}
func (c *Client) discoverServerVersion() error {
log := Log.WithField("action", "discoverServerVersion")
log.Debug("query server version")
res, err := c.newReq().Get("/version")
if err != nil {
return errors.Wrap(err, "could not get server version")
}
if res.StatusCode() != http.StatusOK {
log.Debug("no version endpoint available, ignoring")
return nil
}
ver, err := semver.Parse(string(res.Body()))
if err != nil {
return errors.Wrap(err, "could not parse server version")
}
c.serverVersion = ver
return nil
}
func (c *Client) checkVersion() error {
log := Log.WithField("action", "checkVersion")
log = log.WithField("client_version", globals.Version())
if c.serverVersion.EQ(semver.Version{}) {
if err := c.discoverServerVersion(); err != nil {
return errors.Wrap(err, "could not validate server version")
}
} else {
return nil
}
log = log.WithField("server_version", c.serverVersion)
if c.serverVersion.EQ(semver.Version{}) {
log.Info("Server version is unknown. Things should work but notify your administrator about this")
return nil
}
if globals.IsSnapshotVersion(c.serverVersion) || globals.IsSnapshotVersion(globals.Version()) {
log.Debug("you are running a development version. Skipping version checks")
return nil
}
if c.serverVersion.Major != globals.Version().Major {
log.Error("major version mismatch. Expect errors to happen")
return nil
}
if c.serverVersion.GT(globals.Version()) {
log.Info("server is running a newer version. Consider installing an updated client")
}
if globals.Version().GT(c.serverVersion) {
log.Info("client version is newer. Things should work but notify your administrator about this")
}
return nil
}
// connectAgent connects to an SSH agent
func (c *Client) connectAgent() error {
conn, err := util.DialAuthSock("")
if err != nil {
return errors.Wrap(err, "could not connect to ssh-agent")
}
Log.WithField("socket", conn.RemoteAddr()).Debug("connecting to ssh-agent")
c.agentConn = conn
agentClient := agent.NewClient(c.agentConn)
if _, err := agentClient.List(); err != nil {
return errors.Wrap(err, "could not connect to ssh-agent")
}
c.agentClient = agentClient
Log.WithField("socket", conn.RemoteAddr()).Debug("connected to ssh-agent")
return nil
}
// discoverCertFromAgent discovers certificates from agent.
func (c *Client) discoverCertFromAgent() error {
log := Log.WithField("action", "discoverCertFromAgent")
log.Debug("discovering certificates from the agent")
err := iterAgentKeys(c.agentClient, func(key ssh.PublicKey, comment string) error {
cert, _ := key.(*ssh.Certificate)
if cert == nil {
return nil
}
log := log.WithField("keyid", cert.KeyId).
WithField("signature_format", cert.Signature.Format).
WithField("key_type", strings.TrimPrefix(cert.Key.Type(), "ssh-"))
log.Debug("checking cert")
if !shallowCertChecker(cert, c.ca) {
log.Debug("skipping cert, not valid")
return nil
}
if cert.Signature.Format != util.SignatureFormatFromSigningOptionAndCA(c.Config.SigningOption, c.ca) {
log.WithField("chosen_signature_format", util.SignatureFormatFromSigningOptionAndCA(c.Config.SigningOption, c.ca)).
Debug("cert valid but has different signature format")
return nil
}
if c.Config.GenerateKeypair && cert.Key.Type() != "ssh-"+c.Config.GenerateKeypairType {
log.WithField("chosen_key_type", c.Config.GenerateKeypairType).
Debug("cert valid but has different key type")
return nil
}
c.userCerts = append(c.userCerts, cert)
log.Debug("found cert")
return nil
})