-
-
Notifications
You must be signed in to change notification settings - Fork 945
Expand file tree
/
Copy pathsshclient.go
More file actions
1193 lines (1090 loc) · 43.5 KB
/
sshclient.go
File metadata and controls
1193 lines (1090 loc) · 43.5 KB
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
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package remote
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"fmt"
"log"
"math"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/kevinburke/ssh_config"
"github.com/skeema/knownhosts"
"github.com/wavetermdev/waveterm/pkg/blocklogger"
"github.com/wavetermdev/waveterm/pkg/panichandler"
"github.com/wavetermdev/waveterm/pkg/secretstore"
"github.com/wavetermdev/waveterm/pkg/trimquotes"
"github.com/wavetermdev/waveterm/pkg/userinput"
"github.com/wavetermdev/waveterm/pkg/util/shellutil"
"github.com/wavetermdev/waveterm/pkg/util/utilfn"
"github.com/wavetermdev/waveterm/pkg/wavebase"
"github.com/wavetermdev/waveterm/pkg/wconfig"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
xknownhosts "golang.org/x/crypto/ssh/knownhosts"
)
const SshProxyJumpMaxDepth = 10
var waveSshConfigUserSettingsInternal *ssh_config.UserSettings
var configUserSettingsOnce = &sync.Once{}
func WaveSshConfigUserSettings() *ssh_config.UserSettings {
configUserSettingsOnce.Do(func() {
waveSshConfigUserSettingsInternal = ssh_config.DefaultUserSettings
waveSshConfigUserSettingsInternal.IgnoreMatchDirective = true
})
return waveSshConfigUserSettingsInternal
}
type UserInputCancelError struct {
Err error
}
type HostKeyAlgorithms = func(hostWithPort string) (algos []string)
func (uice UserInputCancelError) Error() string {
return uice.Err.Error()
}
type ConnectionDebugInfo struct {
CurrentClient *ssh.Client
NextOpts *SSHOpts
JumpNum int32
}
type ConnectionError struct {
*ConnectionDebugInfo
Err error
}
func (ce ConnectionError) Error() string {
if ce.CurrentClient == nil {
return fmt.Sprintf("Connecting to %s, Error: %v", MaskString(ce.NextOpts.String()), ce.Err)
}
return fmt.Sprintf("Connecting from client to %s (jump number %d), Error: %v", MaskString(ce.NextOpts.String()), ce.JumpNum, ce.Err)
}
func SimpleMessageFromPossibleConnectionError(err error) string {
if err == nil {
return ""
}
if ce, ok := err.(ConnectionError); ok {
return ce.Err.Error()
}
return err.Error()
}
// logSSHKeywords logs SSH configuration in a sanitized way (DEBUG level)
func logSSHKeywords(ctx context.Context, sshKeywords *wconfig.ConnKeywords) {
blocklogger.Debugf(ctx, "[ssh-config] User: %s\n", MaskString(utilfn.SafeDeref(sshKeywords.SshUser)))
blocklogger.Debugf(ctx, "[ssh-config] HostName: %s\n", MaskString(utilfn.SafeDeref(sshKeywords.SshHostName)))
blocklogger.Debugf(ctx, "[ssh-config] Port: %s\n", utilfn.SafeDeref(sshKeywords.SshPort))
blocklogger.Debugf(ctx, "[ssh-config] IdentityAgent: %s\n", filepath.Base(utilfn.SafeDeref(sshKeywords.SshIdentityAgent)))
blocklogger.Debugf(ctx, "[ssh-config] IdentitiesOnly: %v\n", utilfn.SafeDeref(sshKeywords.SshIdentitiesOnly))
blocklogger.Debugf(ctx, "[ssh-config] IdentityFile count: %d\n", len(sshKeywords.SshIdentityFile))
// Log masked identity file paths for privacy
for i, f := range sshKeywords.SshIdentityFile {
blocklogger.Debugf(ctx, "[ssh-config] IdentityFile[%d]: %s\n", i, maskIdentityFile(f))
}
blocklogger.Debugf(ctx, "[ssh-config] PubkeyAuthentication: %v\n", utilfn.SafeDeref(sshKeywords.SshPubkeyAuthentication))
blocklogger.Debugf(ctx, "[ssh-config] PasswordAuthentication: %v\n", utilfn.SafeDeref(sshKeywords.SshPasswordAuthentication))
blocklogger.Debugf(ctx, "[ssh-config] KbdInteractiveAuthentication: %v\n", utilfn.SafeDeref(sshKeywords.SshKbdInteractiveAuthentication))
blocklogger.Debugf(ctx, "[ssh-config] PreferredAuthentications: %v\n", sshKeywords.SshPreferredAuthentications)
blocklogger.Debugf(ctx, "[ssh-config] AddKeysToAgent: %v\n", utilfn.SafeDeref(sshKeywords.SshAddKeysToAgent))
blocklogger.Debugf(ctx, "[ssh-config] ProxyJump count: %d\n", len(sshKeywords.SshProxyJump))
// Note: do not log PasswordSecretName value, only indicate if configured
if sshKeywords.SshPasswordSecretName != nil && *sshKeywords.SshPasswordSecretName != "" {
blocklogger.Debugf(ctx, "[ssh-config] PasswordSecretName: <configured>\n")
}
}
// MaskString masks a string for privacy, showing only first 3 and last 3 characters.
// Uses rune-based slicing to properly handle multi-byte UTF-8 characters.
func MaskString(s string) string {
if s == "" {
return "<empty>"
}
runes := []rune(s)
if len(runes) <= 6 {
return "***"
}
return string(runes[:3]) + "***" + string(runes[len(runes)-3:])
}
// maskIdentityFile masks an identity file path for privacy.
// It masks the username in home directory paths (/home/user/ or C:\Users\user\)
// and masks the filename while preserving .pub suffix if present.
func maskIdentityFile(path string) string {
if path == "" {
return "<empty>"
}
// Normalize path separators for consistent handling
normalizedPath := filepath.ToSlash(path)
// Extract directory and filename
dir := filepath.Dir(path)
filename := filepath.Base(path)
// Check for .pub suffix
hasPubSuffix := strings.HasSuffix(filename, ".pub")
if hasPubSuffix {
filename = strings.TrimSuffix(filename, ".pub")
}
// Mask the filename
maskedFilename := MaskString(filename)
if hasPubSuffix {
maskedFilename += ".pub"
}
// Mask username in home directory paths
// Unix: /home/username/... or /Users/username/...
// Windows: C:\Users\username\... (normalized to C:/Users/username/...)
maskedDir := dir
if strings.HasPrefix(normalizedPath, "/home/") {
parts := strings.SplitN(normalizedPath, "/", 4) // ["", "home", "username", "rest..."]
if len(parts) >= 3 {
maskedUsername := MaskString(parts[2])
if len(parts) >= 4 {
subDir := filepath.Dir(parts[3])
if subDir == "." {
maskedDir = "/home/" + maskedUsername
} else {
maskedDir = "/home/" + maskedUsername + "/" + subDir
}
} else {
maskedDir = "/home/" + maskedUsername
}
}
} else if strings.Contains(normalizedPath, "/Users/") {
// Handle both Unix /Users/ and Windows C:/Users/
idx := strings.Index(normalizedPath, "/Users/")
prefix := normalizedPath[:idx]
rest := normalizedPath[idx+7:] // Skip "/Users/"
parts := strings.SplitN(rest, "/", 2)
if len(parts) >= 1 {
maskedUsername := MaskString(parts[0])
if len(parts) >= 2 {
subDir := filepath.Dir(parts[1])
if subDir == "." {
maskedDir = prefix + "/Users/" + maskedUsername
} else {
maskedDir = prefix + "/Users/" + maskedUsername + "/" + subDir
}
} else {
maskedDir = prefix + "/Users/" + maskedUsername
}
}
}
// Convert back to native path separators
maskedDir = filepath.FromSlash(maskedDir)
return filepath.Join(maskedDir, maskedFilename)
}
// This exists to trick the ssh library into continuing to try
// different public keys even when the current key cannot be
// properly parsed
func createDummySigner() ([]ssh.Signer, error) {
dummyKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
dummySigner, err := ssh.NewSignerFromKey(dummyKey)
if err != nil {
return nil, err
}
return []ssh.Signer{dummySigner}, nil
}
// This is a workaround to only process one identity file at a time,
// even if they have passphrases. It must be combined with retryable
// authentication to work properly
//
// Despite returning an array of signers, we only ever provide one since
// it allows proper user interaction in between attempts
//
// A significant number of errors end up returning dummy values as if
// they were successes. An error in this function prevents any other
// keys from being attempted. But if there's an error because of a dummy
// file, the library can still try again with a new key.
func createPublicKeyCallback(connCtx context.Context, sshKeywords *wconfig.ConnKeywords, authSockSignersExt []ssh.Signer, agentClient agent.ExtendedAgent, debugInfo *ConnectionDebugInfo) func() ([]ssh.Signer, error) {
var identityFiles []string
existingKeys := make(map[string][]byte)
// checking the file early prevents us from needing to send a
// dummy signer if there's a problem with the signer
for _, identityFile := range sshKeywords.SshIdentityFile {
filePath, err := wavebase.ExpandHomeDir(identityFile)
if err != nil {
continue
}
privateKey, err := os.ReadFile(filePath)
if err != nil {
// skip this key and try with the next
continue
}
existingKeys[identityFile] = privateKey
identityFiles = append(identityFiles, identityFile)
}
// require pointer to modify list in closure
identityFilesPtr := &identityFiles
var authSockSigners []ssh.Signer
authSockSigners = append(authSockSigners, authSockSignersExt...)
authSockSignersPtr := &authSockSigners
return func() (outSigner []ssh.Signer, outErr error) {
defer func() {
panicErr := panichandler.PanicHandler("sshclient:publickey-callback", recover())
if panicErr != nil {
outErr = panicErr
}
}()
// try auth sock
if len(*authSockSignersPtr) != 0 {
authSockSigner := (*authSockSignersPtr)[0]
*authSockSignersPtr = (*authSockSignersPtr)[1:]
return []ssh.Signer{authSockSigner}, nil
}
if len(*identityFilesPtr) == 0 {
return nil, ConnectionError{ConnectionDebugInfo: debugInfo, Err: fmt.Errorf("no identity files remaining")}
}
identityFile := (*identityFilesPtr)[0]
blocklogger.Infof(connCtx, "[conndebug] trying keyfile %q...\n", identityFile)
*identityFilesPtr = (*identityFilesPtr)[1:]
privateKey, ok := existingKeys[identityFile]
if !ok {
log.Printf("error with existingKeys, this should never happen")
// skip this key and try with the next
return createDummySigner()
}
unencryptedPrivateKey, err := ssh.ParseRawPrivateKey(privateKey)
if err == nil {
signer, err := ssh.NewSignerFromKey(unencryptedPrivateKey)
if err == nil {
if utilfn.SafeDeref(sshKeywords.SshAddKeysToAgent) && agentClient != nil {
agentClient.Add(agent.AddedKey{
PrivateKey: unencryptedPrivateKey,
})
}
return []ssh.Signer{signer}, nil
}
}
if _, ok := err.(*ssh.PassphraseMissingError); !ok {
// skip this key and try with the next
return createDummySigner()
}
// batch mode deactivates user input
if utilfn.SafeDeref(sshKeywords.SshBatchMode) {
// skip this key and try with the next
return createDummySigner()
}
request := &userinput.UserInputRequest{
ResponseType: "text",
QueryText: fmt.Sprintf("Enter passphrase for the SSH key: %s", identityFile),
Title: "Publickey Auth + Passphrase",
}
ctx, cancelFn := context.WithTimeout(connCtx, 60*time.Second)
defer cancelFn()
response, err := userinput.GetUserInput(ctx, request)
if err != nil {
// this is an error where we actually do want to stop
// trying keys
return nil, ConnectionError{ConnectionDebugInfo: debugInfo, Err: UserInputCancelError{Err: err}}
}
unencryptedPrivateKey, err = ssh.ParseRawPrivateKeyWithPassphrase(privateKey, []byte([]byte(response.Text)))
if err != nil {
// skip this key and try with the next
return createDummySigner()
}
signer, err := ssh.NewSignerFromKey(unencryptedPrivateKey)
if err != nil {
// skip this key and try with the next
return createDummySigner()
}
if utilfn.SafeDeref(sshKeywords.SshAddKeysToAgent) && agentClient != nil {
agentClient.Add(agent.AddedKey{
PrivateKey: unencryptedPrivateKey,
})
}
return []ssh.Signer{signer}, nil
}
}
func createPasswordCallbackPrompt(connCtx context.Context, remoteDisplayName string, password *string, debugInfo *ConnectionDebugInfo) func() (secret string, err error) {
return func() (secret string, outErr error) {
defer func() {
panicErr := panichandler.PanicHandler("sshclient:password-callback", recover())
if panicErr != nil {
outErr = panicErr
}
}()
blocklogger.Infof(connCtx, "[conndebug] Password Authentication requested from connection %s...\n", remoteDisplayName)
if password != nil {
blocklogger.Infof(connCtx, "[conndebug] using password from secret store, sending to ssh\n")
return *password, nil
}
ctx, cancelFn := context.WithTimeout(connCtx, 60*time.Second)
defer cancelFn()
queryText := fmt.Sprintf(
"Password Authentication requested from connection \n"+
"%s\n\n"+
"Password:", remoteDisplayName)
request := &userinput.UserInputRequest{
ResponseType: "text",
QueryText: queryText,
Markdown: true,
Title: "Password Authentication",
}
response, err := userinput.GetUserInput(ctx, request)
if err != nil {
blocklogger.Infof(connCtx, "[conndebug] ERROR Password Authentication failed: %v\n", SimpleMessageFromPossibleConnectionError(err))
return "", ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
blocklogger.Infof(connCtx, "[conndebug] got password from user, sending to ssh\n")
return response.Text, nil
}
}
func createInteractiveKbdInteractiveChallenge(connCtx context.Context, remoteName string, debugInfo *ConnectionDebugInfo) func(name, instruction string, questions []string, echos []bool) (answers []string, err error) {
return func(name, instruction string, questions []string, echos []bool) (answers []string, outErr error) {
defer func() {
panicErr := panichandler.PanicHandler("sshclient:kbdinteractive-callback", recover())
if panicErr != nil {
outErr = panicErr
}
}()
if len(questions) != len(echos) {
return nil, fmt.Errorf("bad response from server: questions has len %d, echos has len %d", len(questions), len(echos))
}
for i, question := range questions {
echo := echos[i]
answer, err := promptChallengeQuestion(connCtx, question, echo, remoteName)
if err != nil {
return nil, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
answers = append(answers, answer)
}
return answers, nil
}
}
func promptChallengeQuestion(connCtx context.Context, question string, echo bool, remoteName string) (answer string, err error) {
// limited to 15 seconds for some reason. this should be investigated more
// in the future
ctx, cancelFn := context.WithTimeout(connCtx, 60*time.Second)
defer cancelFn()
queryText := fmt.Sprintf(
"Keyboard Interactive Authentication requested from connection \n"+
"%s\n\n"+
"%s", remoteName, question)
request := &userinput.UserInputRequest{
ResponseType: "text",
QueryText: queryText,
Markdown: true,
Title: "Keyboard Interactive Authentication",
PublicText: echo,
}
response, err := userinput.GetUserInput(ctx, request)
if err != nil {
return "", err
}
return response.Text, nil
}
func openKnownHostsForEdit(knownHostsFilename string) (*os.File, error) {
path, _ := filepath.Split(knownHostsFilename)
err := os.MkdirAll(path, 0700)
if err != nil {
return nil, err
}
return os.OpenFile(knownHostsFilename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
}
func writeToKnownHosts(knownHostsFile string, newLine string, getUserVerification func() (*userinput.UserInputResponse, error)) error {
if getUserVerification == nil {
getUserVerification = func() (*userinput.UserInputResponse, error) {
return &userinput.UserInputResponse{
Type: "confirm",
Confirm: true,
}, nil
}
}
path, _ := filepath.Split(knownHostsFile)
err := os.MkdirAll(path, 0700)
if err != nil {
return err
}
f, err := os.OpenFile(knownHostsFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
// do not close writeable files with defer
// this file works, so let's ask the user for permission
response, err := getUserVerification()
if err != nil {
f.Close()
return UserInputCancelError{Err: err}
}
if !response.Confirm {
f.Close()
return UserInputCancelError{Err: fmt.Errorf("canceled by the user")}
}
_, err = f.WriteString(newLine + "\n")
if err != nil {
f.Close()
return err
}
return f.Close()
}
func createUnknownKeyVerifier(ctx context.Context, knownHostsFile string, hostname string, remote string, key ssh.PublicKey) func() (*userinput.UserInputResponse, error) {
base64Key := base64.StdEncoding.EncodeToString(key.Marshal())
queryText := fmt.Sprintf(
"The authenticity of host '%s (%s)' can't be established "+
"as it **does not exist in any checked known_hosts files**. "+
"The host you are attempting to connect to provides this %s key: \n"+
"%s.\n\n"+
"**Would you like to continue connecting?** If so, the key will be permanently "+
"added to the file %s "+
"to protect from future man-in-the-middle attacks.", hostname, remote, key.Type(), base64Key, knownHostsFile)
request := &userinput.UserInputRequest{
ResponseType: "confirm",
QueryText: queryText,
Markdown: true,
Title: "Known Hosts Key Missing",
}
return func() (*userinput.UserInputResponse, error) {
ctx, cancelFn := context.WithTimeout(ctx, 60*time.Second)
defer cancelFn()
resp, err := userinput.GetUserInput(ctx, request)
if err != nil {
return nil, err
}
if !resp.Confirm {
return nil, fmt.Errorf("user selected no")
}
return resp, nil
}
}
func createMissingKnownHostsVerifier(knownHostsFile string, hostname string, remote string, key ssh.PublicKey) func() (*userinput.UserInputResponse, error) {
base64Key := base64.StdEncoding.EncodeToString(key.Marshal())
queryText := fmt.Sprintf(
"The authenticity of host '%s (%s)' can't be established "+
"as **no known_hosts files could be found**. "+
"The host you are attempting to connect to provides this %s key: \n"+
"%s.\n\n"+
"**Would you like to continue connecting?** If so: \n"+
"- %s will be created \n"+
"- the key will be added to %s\n\n"+
"This will protect from future man-in-the-middle attacks.", hostname, remote, key.Type(), base64Key, knownHostsFile, knownHostsFile)
request := &userinput.UserInputRequest{
ResponseType: "confirm",
QueryText: queryText,
Markdown: true,
Title: "Known Hosts File Missing",
}
return func() (*userinput.UserInputResponse, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), 60*time.Second)
defer cancelFn()
resp, err := userinput.GetUserInput(ctx, request)
if err != nil {
return nil, err
}
if !resp.Confirm {
return nil, fmt.Errorf("user selected no")
}
return resp, nil
}
}
func lineContainsMatch(line []byte, matches [][]byte) bool {
for _, match := range matches {
if bytes.Contains(line, match) {
return true
}
}
return false
}
func createHostKeyCallback(ctx context.Context, sshKeywords *wconfig.ConnKeywords) (ssh.HostKeyCallback, HostKeyAlgorithms, error) {
globalKnownHostsFiles := sshKeywords.SshGlobalKnownHostsFile
userKnownHostsFiles := sshKeywords.SshUserKnownHostsFile
osUser, err := user.Current()
if err != nil {
return nil, nil, err
}
var unexpandedKnownHostsFiles []string
if osUser.Username == "root" {
unexpandedKnownHostsFiles = globalKnownHostsFiles
} else {
unexpandedKnownHostsFiles = append(userKnownHostsFiles, globalKnownHostsFiles...)
}
var knownHostsFiles []string
for _, filename := range unexpandedKnownHostsFiles {
filePath, err := wavebase.ExpandHomeDir(filename)
if err != nil {
continue
}
knownHostsFiles = append(knownHostsFiles, filePath)
}
// there are no good known hosts files
if len(knownHostsFiles) == 0 {
return nil, nil, fmt.Errorf("no known_hosts files provided by ssh. defaults are overridden")
}
var unreadableFiles []string
// the library we use isn't very forgiving about files that are formatted
// incorrectly. if a problem file is found, it is removed from our list
// and we try again
var basicCallback ssh.HostKeyCallback
var hostKeyAlgorithms HostKeyAlgorithms
for basicCallback == nil && len(knownHostsFiles) > 0 {
keyDb, err := knownhosts.NewDB(knownHostsFiles...)
if serr, ok := err.(*os.PathError); ok {
badFile := serr.Path
unreadableFiles = append(unreadableFiles, badFile)
var okFiles []string
for _, filename := range knownHostsFiles {
if filename != badFile {
okFiles = append(okFiles, filename)
}
}
if len(okFiles) >= len(knownHostsFiles) {
return nil, nil, fmt.Errorf("problem file (%s) doesn't exist. this should not be possible", badFile)
}
knownHostsFiles = okFiles
} else if err != nil {
// TODO handle obscure problems if possible
return nil, nil, fmt.Errorf("known_hosts formatting error: %+v", err)
} else {
basicCallback = keyDb.HostKeyCallback()
hostKeyAlgorithms = keyDb.HostKeyAlgorithms
}
}
if basicCallback == nil {
basicCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return &xknownhosts.KeyError{}
}
// need to return nil here to avoid null pointer from attempting to call
// the one provided by the db if nothing was found
hostKeyAlgorithms = func(hostWithPort string) (algos []string) {
return nil
}
}
waveHostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) (outErr error) {
defer func() {
panicErr := panichandler.PanicHandler("sshclient:wave-hostkey-callback", recover())
if panicErr != nil {
outErr = panicErr
}
}()
err := basicCallback(hostname, remote, key)
if err == nil {
// success
return nil
} else if _, ok := err.(*xknownhosts.RevokedError); ok {
// revoked credentials are refused outright
return err
} else if _, ok := err.(*xknownhosts.KeyError); !ok {
// this is an unknown error (note the !ok is opposite of usual)
return err
}
serr, _ := err.(*xknownhosts.KeyError)
if len(serr.Want) == 0 {
// the key was not found
// try to write to a file that could be read
err := fmt.Errorf("placeholder, should not be returned") // a null value here can cause problems with empty slice
for _, filename := range knownHostsFiles {
newLine := xknownhosts.Line([]string{xknownhosts.Normalize(hostname)}, key)
getUserVerification := createUnknownKeyVerifier(ctx, filename, hostname, remote.String(), key)
err = writeToKnownHosts(filename, newLine, getUserVerification)
if err == nil {
break
}
if serr, ok := err.(UserInputCancelError); ok {
return serr
}
}
// try to write to a file that could not be read (file likely doesn't exist)
// should catch cases where there is no known_hosts file
if err != nil {
for _, filename := range unreadableFiles {
newLine := xknownhosts.Line([]string{xknownhosts.Normalize(hostname)}, key)
getUserVerification := createMissingKnownHostsVerifier(filename, hostname, remote.String(), key)
err = writeToKnownHosts(filename, newLine, getUserVerification)
if err == nil {
knownHostsFiles = []string{filename}
break
}
if serr, ok := err.(UserInputCancelError); ok {
return serr
}
}
}
if err != nil {
return fmt.Errorf("unable to create new knownhost key: %e", err)
}
} else {
// the key changed
correctKeyFingerprint := base64.StdEncoding.EncodeToString(key.Marshal())
var bulletListKnownHosts []string
for _, knownHostName := range knownHostsFiles {
withBulletPoint := "- " + knownHostName
bulletListKnownHosts = append(bulletListKnownHosts, withBulletPoint)
}
var offendingKeysFmt []string
for _, badKey := range serr.Want {
formattedKey := "- " + base64.StdEncoding.EncodeToString(badKey.Key.Marshal())
offendingKeysFmt = append(offendingKeysFmt, formattedKey)
}
// todo
errorMsg := fmt.Sprintf("**WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!**\n\n"+
"If this is not expected, it is possible that someone could be trying to "+
"eavesdrop on you via a man-in-the-middle attack. "+
"Alternatively, the host you are connecting to may have changed its key. "+
"The %s key sent by the remote hist has the fingerprint: \n"+
"%s\n\n"+
"If you are sure this is correct, please update your known_hosts files to "+
"remove the lines with the offending before trying to connect again. \n"+
"**Known Hosts Files** \n"+
"%s\n\n"+
"**Offending Keys** \n"+
"%s", key.Type(), correctKeyFingerprint, strings.Join(bulletListKnownHosts, " \n"), strings.Join(offendingKeysFmt, " \n"))
log.Print(errorMsg)
//update := scbus.MakeUpdatePacket()
// create update into alert message
//send update via bus?
return fmt.Errorf("remote host identification has changed")
}
updatedCallback, err := xknownhosts.New(knownHostsFiles...)
if err != nil {
return err
}
// try one final time
return updatedCallback(hostname, remote, key)
}
return waveHostKeyCallback, hostKeyAlgorithms, nil
}
func createClientConfig(connCtx context.Context, sshKeywords *wconfig.ConnKeywords, debugInfo *ConnectionDebugInfo) (*ssh.ClientConfig, error) {
chosenUser := utilfn.SafeDeref(sshKeywords.SshUser)
chosenHostName := utilfn.SafeDeref(sshKeywords.SshHostName)
chosenPort := utilfn.SafeDeref(sshKeywords.SshPort)
remoteName := xknownhosts.Normalize(chosenHostName + ":" + chosenPort)
if chosenUser != "" {
remoteName = chosenUser + "@" + remoteName
}
// Log SSH configuration (DEBUG level)
logSSHKeywords(connCtx, sshKeywords)
var authSockSigners []ssh.Signer
var agentClient agent.ExtendedAgent
// IdentitiesOnly indicates that only the keys listed in the identity and certificate files or passed as arguments should be used, even if there are matches in the SSH Agent, PKCS11Provider, or SecurityKeyProvider. See https://man.openbsd.org/ssh_config#IdentitiesOnly
// TODO: Update if we decide to support PKCS11Provider and SecurityKeyProvider
agentPath := strings.TrimSpace(utilfn.SafeDeref(sshKeywords.SshIdentityAgent))
if !utilfn.SafeDeref(sshKeywords.SshIdentitiesOnly) && agentPath != "" {
blocklogger.Debugf(connCtx, "[ssh-agent] attempting to connect to agent at %q\n", filepath.Base(agentPath))
conn, err := dialIdentityAgent(agentPath)
if err != nil {
blocklogger.Infof(connCtx, "[ssh-agent] ERROR failed to connect to agent at %q: %v\n", filepath.Base(agentPath), err)
if runtime.GOOS == "windows" {
blocklogger.Infof(connCtx, "[ssh-agent] hint: ensure OpenSSH Authentication Agent service is running (Get-Service ssh-agent)\n")
}
} else {
blocklogger.Infof(connCtx, "[ssh-agent] successfully connected to agent at %q\n", filepath.Base(agentPath))
agentClient = agent.NewClient(conn)
blocklogger.Debugf(connCtx, "[ssh-agent] requesting key list from agent...\n")
var signerErr error
authSockSigners, signerErr = agentClient.Signers()
if signerErr != nil {
blocklogger.Infof(connCtx, "[ssh-agent] WARNING failed to get signers from agent: %v\n", signerErr)
} else {
blocklogger.Infof(connCtx, "[ssh-agent] retrieved %d signers from agent\n", len(authSockSigners))
// Log public key fingerprints (DEBUG level, for troubleshooting)
for i, signer := range authSockSigners {
pubKey := signer.PublicKey()
fingerprint := ssh.FingerprintSHA256(pubKey)
blocklogger.Debugf(connCtx, "[ssh-agent] key[%d]: type=%s fingerprint=%s\n", i, pubKey.Type(), MaskString(fingerprint))
}
}
}
} else {
if agentPath == "" {
blocklogger.Debugf(connCtx, "[ssh-agent] no agent path configured\n")
} else {
blocklogger.Debugf(connCtx, "[ssh-agent] agent skipped (IdentitiesOnly=%v)\n", utilfn.SafeDeref(sshKeywords.SshIdentitiesOnly))
}
}
var sshPassword *string
if sshKeywords.SshPasswordSecretName != nil && *sshKeywords.SshPasswordSecretName != "" {
secretName := *sshKeywords.SshPasswordSecretName
password, exists, err := secretstore.GetSecret(secretName)
if err != nil {
return nil, fmt.Errorf("error retrieving ssh:passwordsecretname %q: %w", secretName, err)
}
if !exists {
return nil, fmt.Errorf("ssh:passwordsecretname %q not found in secret store", secretName)
}
blocklogger.Infof(connCtx, "[conndebug] successfully retrieved ssh:passwordsecretname %q from secret store\n", secretName)
sshPassword = &password
}
publicKeyCallback := ssh.PublicKeysCallback(createPublicKeyCallback(connCtx, sshKeywords, authSockSigners, agentClient, debugInfo))
keyboardInteractive := ssh.KeyboardInteractive(createInteractiveKbdInteractiveChallenge(connCtx, remoteName, debugInfo))
passwordCallback := ssh.PasswordCallback(createPasswordCallbackPrompt(connCtx, remoteName, sshPassword, debugInfo))
// exclude gssapi-with-mic and hostbased until implemented
authMethodMap := map[string]ssh.AuthMethod{
"publickey": ssh.RetryableAuthMethod(publicKeyCallback, len(sshKeywords.SshIdentityFile)+len(authSockSigners)),
"keyboard-interactive": ssh.RetryableAuthMethod(keyboardInteractive, 1),
"password": ssh.RetryableAuthMethod(passwordCallback, 1),
}
// note: batch mode turns off interactive input
authMethodActiveMap := map[string]bool{
"publickey": utilfn.SafeDeref(sshKeywords.SshPubkeyAuthentication),
"keyboard-interactive": utilfn.SafeDeref(sshKeywords.SshKbdInteractiveAuthentication) && !utilfn.SafeDeref(sshKeywords.SshBatchMode),
"password": utilfn.SafeDeref(sshKeywords.SshPasswordAuthentication) && !utilfn.SafeDeref(sshKeywords.SshBatchMode),
}
var authMethods []ssh.AuthMethod
for _, authMethodName := range sshKeywords.SshPreferredAuthentications {
authMethodActive, ok := authMethodActiveMap[authMethodName]
if !ok || !authMethodActive {
continue
}
authMethod, ok := authMethodMap[authMethodName]
if !ok {
continue
}
authMethods = append(authMethods, authMethod)
}
hostKeyCallback, hostKeyAlgorithms, err := createHostKeyCallback(connCtx, sshKeywords)
if err != nil {
return nil, err
}
networkAddr := chosenHostName + ":" + chosenPort
return &ssh.ClientConfig{
User: chosenUser,
Auth: authMethods,
HostKeyCallback: hostKeyCallback,
HostKeyAlgorithms: hostKeyAlgorithms(networkAddr),
}, nil
}
func connectInternal(ctx context.Context, networkAddr string, clientConfig *ssh.ClientConfig, currentClient *ssh.Client) (*ssh.Client, error) {
var clientConn net.Conn
var err error
if currentClient == nil {
d := net.Dialer{Timeout: clientConfig.Timeout}
blocklogger.Infof(ctx, "[conndebug] ssh dial %s\n", MaskString(networkAddr))
clientConn, err = d.DialContext(ctx, "tcp", networkAddr)
if err != nil {
blocklogger.Infof(ctx, "[conndebug] ERROR dial error: %v\n", err)
return nil, err
}
} else {
blocklogger.Infof(ctx, "[conndebug] ssh dial (from client) %s\n", MaskString(networkAddr))
clientConn, err = currentClient.DialContext(ctx, "tcp", networkAddr)
if err != nil {
blocklogger.Infof(ctx, "[conndebug] ERROR dial error: %v\n", err)
return nil, err
}
}
c, chans, reqs, err := ssh.NewClientConn(clientConn, networkAddr, clientConfig)
if err != nil {
blocklogger.Infof(ctx, "[conndebug] ERROR ssh auth/negotiation: %s\n", SimpleMessageFromPossibleConnectionError(err))
return nil, err
}
blocklogger.Infof(ctx, "[conndebug] successful ssh connection to %s\n", MaskString(networkAddr))
return ssh.NewClient(c, chans, reqs), nil
}
func ConnectToClient(connCtx context.Context, opts *SSHOpts, currentClient *ssh.Client, jumpNum int32, connFlags *wconfig.ConnKeywords) (*ssh.Client, int32, error) {
blocklogger.Infof(connCtx, "[conndebug] ConnectToClient %s (jump:%d)...\n", MaskString(opts.String()), jumpNum)
debugInfo := &ConnectionDebugInfo{
CurrentClient: currentClient,
NextOpts: opts,
JumpNum: jumpNum,
}
if jumpNum > SshProxyJumpMaxDepth {
return nil, jumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: fmt.Errorf("ProxyJump %d exceeds Wave's max depth of %d", jumpNum, SshProxyJumpMaxDepth)}
}
rawName := opts.String()
fullConfig := wconfig.GetWatcher().GetFullConfig()
internalSshConfigKeywords, ok := fullConfig.Connections[rawName]
if !ok {
internalSshConfigKeywords = wconfig.ConnKeywords{}
}
var sshConfigKeywords *wconfig.ConnKeywords
if utilfn.SafeDeref(internalSshConfigKeywords.ConnIgnoreSshConfig) {
blocklogger.Debugf(connCtx, "[ssh-config] loading config for host %q (ignoresshconfig=true, using defaults only)\n", MaskString(opts.SSHHost))
var err error
sshConfigKeywords, err = findSshDefaults(opts.SSHHost)
if err != nil {
err = fmt.Errorf("cannot determine default config keywords: %w", err)
return nil, debugInfo.JumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
} else {
blocklogger.Debugf(connCtx, "[ssh-config] loading config for host %q (using ssh_config + internal)\n", MaskString(opts.SSHHost))
var err error
sshConfigKeywords, err = findSshConfigKeywords(opts.SSHHost)
if err != nil {
err = fmt.Errorf("cannot determine config keywords: %w", err)
return nil, debugInfo.JumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
}
parsedKeywords := &wconfig.ConnKeywords{}
if opts.SSHUser != "" {
parsedKeywords.SshUser = &opts.SSHUser
}
if opts.SSHPort != "" {
parsedKeywords.SshPort = &opts.SSHPort
}
// cascade order:
// ssh config -> (optional) internal config -> specified flag keywords -> parsed keywords
partialMerged := sshConfigKeywords
partialMerged = mergeKeywords(partialMerged, &internalSshConfigKeywords)
partialMerged = mergeKeywords(partialMerged, connFlags)
sshKeywords := mergeKeywords(partialMerged, parsedKeywords)
// handle these separately since
// - they append
// - since they append, the order is reversed
// - there is no reason to not include the internal config
// - they are never part of the parsedKeywords
sshKeywords.SshIdentityFile = append(sshKeywords.SshIdentityFile, connFlags.SshIdentityFile...)
sshKeywords.SshIdentityFile = append(sshKeywords.SshIdentityFile, internalSshConfigKeywords.SshIdentityFile...)
sshKeywords.SshIdentityFile = append(sshKeywords.SshIdentityFile, sshConfigKeywords.SshIdentityFile...)
for _, proxyName := range sshKeywords.SshProxyJump {
proxyOpts, err := ParseOpts(proxyName)
if err != nil {
return nil, debugInfo.JumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
// ensure no overflow (this will likely never happen)
if jumpNum < math.MaxInt32 {
jumpNum += 1
}
// do not apply supplied keywords to proxies - ssh config must be used for that
debugInfo.CurrentClient, jumpNum, err = ConnectToClient(connCtx, proxyOpts, debugInfo.CurrentClient, jumpNum, &wconfig.ConnKeywords{})
if err != nil {
// do not add a context on a recursive call
// (this can cause a recursive nested context that's arbitrarily deep)
return nil, jumpNum, err
}
}
clientConfig, err := createClientConfig(connCtx, sshKeywords, debugInfo)
if err != nil {
return nil, debugInfo.JumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
networkAddr := utilfn.SafeDeref(sshKeywords.SshHostName) + ":" + utilfn.SafeDeref(sshKeywords.SshPort)
client, err := connectInternal(connCtx, networkAddr, clientConfig, debugInfo.CurrentClient)
if err != nil {
return client, debugInfo.JumpNum, ConnectionError{ConnectionDebugInfo: debugInfo, Err: err}
}
return client, debugInfo.JumpNum, nil
}
// note that a `var == "yes"` will default to false
// but `var != "no"` will default to true
// when given unexpected strings
func findSshConfigKeywords(hostPattern string) (connKeywords *wconfig.ConnKeywords, outErr error) {
defer func() {
panicErr := panichandler.PanicHandler("sshclient:find-ssh-config-keywords", recover())
if panicErr != nil {
outErr = panicErr
}
}()
WaveSshConfigUserSettings().ReloadConfigs()
sshKeywords := &wconfig.ConnKeywords{}
var err error
userRaw, err := WaveSshConfigUserSettings().GetStrict(hostPattern, "User")
if err != nil {
return nil, err
}
userClean := trimquotes.TryTrimQuotes(userRaw)
if userClean == "" {
userDetails, err := user.Current()
if err != nil {
return nil, err
}
userClean = userDetails.Username
}
sshKeywords.SshUser = &userClean
hostNameRaw, err := WaveSshConfigUserSettings().GetStrict(hostPattern, "HostName")
if err != nil {
return nil, err
}
// manually implementing default HostName here as it is not handled by ssh_config library
hostNameProcessed := trimquotes.TryTrimQuotes(hostNameRaw)
if hostNameProcessed == "" {
sshKeywords.SshHostName = &hostPattern
} else {
sshKeywords.SshHostName = &hostNameRaw
}
portRaw, err := WaveSshConfigUserSettings().GetStrict(hostPattern, "Port")
if err != nil {
return nil, err
}
sshKeywords.SshPort = utilfn.Ptr(trimquotes.TryTrimQuotes(portRaw))
identityFileRaw := WaveSshConfigUserSettings().GetAll(hostPattern, "IdentityFile")
for i := 0; i < len(identityFileRaw); i++ {
identityFileRaw[i] = trimquotes.TryTrimQuotes(identityFileRaw[i])
}
sshKeywords.SshIdentityFile = identityFileRaw
batchModeRaw, err := WaveSshConfigUserSettings().GetStrict(hostPattern, "BatchMode")
if err != nil {
return nil, err
}
sshKeywords.SshBatchMode = utilfn.Ptr(strings.ToLower(trimquotes.TryTrimQuotes(batchModeRaw)) == "yes")