This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
forked from pdlan/sshpiper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshpiper.go
1074 lines (878 loc) · 25.7 KB
/
sshpiper.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
// Copyright 2014, 2015 tgic<[email protected]>. All rights reserved.
// this file is governed by MIT-license
//
// https://github.com/tg123/sshpiper
package ssh
import (
"errors"
"fmt"
"time"
"net"
"encoding/json"
)
// AuthPipeType declares how sshpiper handle piped auth message
type AuthPipeType int
const (
// AuthPipeTypePassThrough does nothing but pass auth message to upstream
AuthPipeTypePassThrough AuthPipeType = iota
// AuthPipeTypeMap converts auth message to AuthMetod return by callback and pass it to upstream
AuthPipeTypeMap
// AuthPipeTypeDiscard discards auth message, do not pass it to uptream
AuthPipeTypeDiscard
// AuthPipeTypeNone converts auth message to NoneAuth and pass it to upstream
AuthPipeTypeNone
)
// AuthPipe contains the callbacks of auth msg mapping from downstream to upstream
//
// when AuthPipeType == AuthPipeTypeMap && AuthMethod == PublicKey
// SSHPiper will sign the auth packet message using the returned Signer.
// This func might be called twice, one is for query message, the other
// is real auth packet message.
// If any error occurs during this period, a NoneAuth packet will be sent to
// upstream ssh server instead.
// More info: https://github.com/tg123/sshpiper#publickey-sign-again
type AuthPipe struct {
// Username to upstream
User string
// NoneAuthCallback, if non-nil, is called when downstream requests a none auth,
// typically the first auth msg from client to see what auth methods can be used..
NoneAuthCallback func(conn ConnMetadata) (AuthPipeType, AuthMethod, error)
// PublicKeyCallback, if non-nil, is called when downstream requests a password auth.
PasswordCallback func(conn ConnMetadata, password []byte, data *AuthData) (AuthPipeType, AuthMethod, error)
// PublicKeyCallback, if non-nil, is called when downstream requests a publickey auth.
PublicKeyCallback func(conn ConnMetadata, key PublicKey, data *AuthData) (AuthPipeType, AuthMethod, error)
// UpstreamHostKeyCallback is called during the cryptographic
// handshake to validate the uptream server's host key. The piper
// configuration must supply this callback for the connection
// to succeed. The functions InsecureIgnoreHostKey or
// FixedHostKey can be used for simplistic host key checks.
UpstreamHostKeyCallback HostKeyCallback
PasswordBeforePublicKeyCallback func(password []byte, data *AuthData)
InteractiveQuestions []string
InteractiveEcho []bool
InteractiveInstrution string
}
// AdditionalChallengeContext is the context returned by AdditionalChallenge and will pass to FindUpstream for building
// upstream AuthPipe
type AdditionalChallengeContext interface {
// Chanllenger name
ChallengerName() string
// Meta info filled by chanllenger
// can be nil if no meta data
Meta() interface{}
// Username used during the chanllenge
// Can be different from ConnMeta.User() and could be a useful hint in FindUpstream
ChallengedUsername() string
}
// PiperConfig holds SSHPiper specific configuration data.
type PiperConfig struct {
Config
hostKeys []Signer
// AdditionalChallenge, if non-nil, is called before calling FindUpstream.
// This allows you do a KeyboardInteractiveChallenge before connecting to upstream.
// It must return non error if downstream passed the challenge, otherwise,
// the piped connection will be closed.
//
// AdditionalChallengeContext can be nil if challenger has no more information to provide.
AdditionalChallenge func(conn ConnMetadata, client KeyboardInteractiveChallenge) (AdditionalChallengeContext, error)
// FindUpstream, must not be nil, is called when SSHPiper decided to establish a
// ssh connection to upstream server. a connection, net.Conn, to upstream
// and upstream username should be returned.
// SSHPiper will use the username from downstream if empty username is returned.
// If any error occurs, the piped connection will be closed.
FindUpstream func(conn ConnMetadata, challengeCtx AdditionalChallengeContext) (
func (unix_username string, key PublicKey, answers []string, data *AuthData) (net.Conn, error), *AuthPipe, error)
// ServerVersion is the version identification string to announce in
// the public handshake.
// If empty, a reasonable default is used.
// Note that RFC 4253 section 4.2 requires that this string start with
// "SSH-2.0-".
ServerVersion string
// BannerCallback, if present, is called and the return string is sent to
// the client after key exchange completed but before authentication.
BannerCallback func(conn ConnMetadata) string
LogCallback func(msg []byte)
}
type upstream struct{ *connection }
type downstream struct{ *connection }
type pipedConn struct {
upstream *upstream
downstream *downstream
processAuthMsg func(msg *userAuthRequestMsg) (*userAuthRequestMsg, error)
hookUpstreamMsg func(msg []byte) ([]byte, error)
hookDownstreamMsg func(msg []byte) ([]byte, error)
}
// PiperConn is a piped SSH connection, linking upstream ssh server and
// downstream ssh client together. After the piped connection was created,
// The downstream ssh client is authenticated by upstream ssh server and
// AdditionalChallenge from SSHPiper.
type PiperConn struct {
*pipedConn
LoginTime int64
DisconnectTime int64
ClientIp string
Username string
HostIp string
HookUpstreamMsg func(conn ConnMetadata, msg []byte) ([]byte, error)
HookDownstreamMsg func(conn ConnMetadata, msg []byte) ([]byte, error)
LogCallback func(msg []byte)
}
type AuthData struct {
HasCheckedPublicKey bool
HasSentPassword bool
Password []byte
CertSigner Signer
CustomData interface{}
}
// Wait blocks until the piped connection has shut down, and returns the
// error causing the shutdown.
func (p *PiperConn) Wait() error {
p.pipedConn.hookUpstreamMsg = func(msg []byte) ([]byte, error) {
if p.HookUpstreamMsg != nil {
// api always using p.downstream as conn meta
return p.HookUpstreamMsg(p.downstream, msg)
}
return msg, nil
}
p.pipedConn.hookDownstreamMsg = func(msg []byte) ([]byte, error) {
if p.HookDownstreamMsg != nil {
return p.HookDownstreamMsg(p.downstream, msg)
}
return msg, nil
}
return p.pipedConn.loop()
}
// Close the piped connection create by SSHPiper
func (p *PiperConn) Close() {
p.pipedConn.Close()
p.DisconnectTime = time.Now().Unix()
type LogMessage struct {
LoginTime int64 `json:"login_time"`
DisconnectTime int64 `json:"disconnect_time"`
ClientIp string `json:"remote_ip"`
HostIp string `json:"host_ip"`
Username string `json:"user_name"`
}
logMsg := LogMessage {
LoginTime: p.LoginTime,
DisconnectTime: p.DisconnectTime,
ClientIp: p.ClientIp,
HostIp: p.HostIp,
Username: p.Username,
}
jsonMsg, err := json.Marshal(logMsg)
if err != nil {
return
}
if p.LogCallback != nil {
p.LogCallback(jsonMsg)
}
}
// UpstreamConnMeta returns the ConnMetadata of the piper and upstream
func (p *PiperConn) UpstreamConnMeta() ConnMetadata {
return p.pipedConn.upstream
}
// DownstreamConnMeta returns the ConnMetadata of the piper and downstream
func (p *PiperConn) DownstreamConnMeta() ConnMetadata {
return p.pipedConn.downstream
}
// AddHostKey adds a private key as a SSHPiper host key. If an existing host
// key exists with the same algorithm, it is overwritten. Each SSHPiper
// config must have at least one host key.
func (s *PiperConfig) AddHostKey(key Signer) {
for i, k := range s.hostKeys {
if k.PublicKey().Type() == key.PublicKey().Type() {
s.hostKeys[i] = key
return
}
}
s.hostKeys = append(s.hostKeys, key)
}
// NewSSHPiperConn starts a piped ssh connection witch conn as its downstream transport.
// It handshake with downstream ssh client and upstream ssh server provicde by FindUpstream.
// If either handshake is unsuccessful, the whole piped connection will be closed.
func NewSSHPiperConn(conn net.Conn, piper *PiperConfig) (pipe *PiperConn, err error) {
if piper.FindUpstream == nil {
return nil, errors.New("sshpiper: must specify FindUpstream")
}
d, err := newDownstream(conn, &ServerConfig{
Config: piper.Config,
hostKeys: piper.hostKeys,
ServerVersion: piper.ServerVersion,
})
if err != nil {
return nil, err
}
defer func() {
if pipe == nil {
d.Close()
}
}()
userAuthReq, err := d.nextAuthMsg()
if err != nil {
return nil, err
}
d.user = userAuthReq.User
if piper.BannerCallback != nil {
msg := piper.BannerCallback(d)
if msg != "" {
bannerMsg := &userAuthBannerMsg{
Message: msg,
}
if err := d.transport.writePacket(Marshal(bannerMsg)); err != nil {
return nil, err
}
}
}
var challengeCtx AdditionalChallengeContext
// need additional challenge
if piper.AdditionalChallenge != nil {
for {
err := d.transport.writePacket(Marshal(&userAuthFailureMsg{
Methods: []string{"keyboard-interactive"},
}))
if err != nil {
return nil, err
}
userAuthReq, err := d.nextAuthMsg()
if err != nil {
return nil, err
}
if userAuthReq.Method == "keyboard-interactive" {
break
}
}
prompter := &sshClientKeyboardInteractive{d.connection}
challengeCtx, err = piper.AdditionalChallenge(d, prompter.Challenge)
if err != nil {
return nil, err
}
}
upconnCallback, pipeauth, err := piper.FindUpstream(d, challengeCtx)
if err != nil {
return nil, err
}
if pipeauth.UpstreamHostKeyCallback == nil {
return nil, errors.New("sshpiper: must specify UpstreamHostKeyCallback")
}
mappedUser := pipeauth.User
// addr := upconn.RemoteAddr().String()
if mappedUser == "" {
mappedUser = d.user
}
// u, err := newUpstream(upconn, addr, &ClientConfig{
// HostKeyCallback: pipeauth.UpstreamHostKeyCallback,
// })
// if err != nil {
// return nil, err
// }
// defer func() {
// if pipe == nil {
// u.Close()
// }
// }()
// u.user = mappedUser
p := &pipedConn{
upstream: nil,
downstream: d,
}
var upconn net.Conn
var data AuthData
var hostIp, clientIp, userName string
clientIp = conn.RemoteAddr().String()
p.processAuthMsg = func(msg *userAuthRequestMsg) (*userAuthRequestMsg, error) {
var authType = AuthPipeTypeDiscard
var authMethod AuthMethod
switch msg.Method {
case "none":
if p.upstream == nil {
p.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"publickey", "keyboard-interactive"},
PartialSuccess: false,
}))
}
if pipeauth.NoneAuthCallback == nil {
return nil, nil
}
authType, authMethod, err = pipeauth.NoneAuthCallback(d)
if err != nil {
return nil, err
}
case "publickey":
if pipeauth.PublicKeyCallback == nil {
break
}
// pubKey MAP
algo, downKey, isQuery, sig, err := parsePublicKeyMsg(msg)
if err != nil {
return nil, err
}
if isQuery {
// reply for query msg
// skip query from upstream
err = p.ack(downKey)
if err != nil {
return nil, err
}
// discard msg
return nil, nil
}
ok, err := p.checkPublicKey(algo, msg, downKey, sig)
if err != nil {
return nil, err
}
if !ok {
p.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"publickey", "keyboard-interactive"},
PartialSuccess: false,
}))
return nil, nil
//return noneAuthMsg(mappedUser), nil
//return nil, errors.New("failed to check public key")
}
if p.upstream == nil {
upconn, err = upconnCallback(mappedUser, downKey, nil, &data)
if err != nil {
return nil, err
}
if upconn == nil {
p.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"publickey", "keyboard-interactive"},
PartialSuccess: false,
}))
return nil, nil
}
addr := upconn.RemoteAddr().String()
hostIp = addr
u, err := newUpstream(upconn, addr, &ClientConfig{
HostKeyCallback: pipeauth.UpstreamHostKeyCallback,
})
if err != nil {
return nil, err
}
defer func() {
if p == nil {
u.Close()
}
}()
u.user = mappedUser
userName = u.user
p.upstream = u
err = p.upstream.sendAuthReq()
if err != nil {
return nil, err
}
}
data.HasCheckedPublicKey = true
authType, authMethod, err = pipeauth.PublicKeyCallback(d, downKey, &data)
if err != nil {
return nil, err
}
if authType == AuthPipeTypeDiscard {
p.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"password"},
PartialSuccess: true,
}))
return nil, nil
}
case "password":
if pipeauth.PasswordCallback == nil {
break
}
payload := msg.Payload
if len(payload) < 1 || payload[0] != 0 {
return nil, parseError(msgUserAuthRequest)
}
payload = payload[1:]
password, payload, ok := parseString(payload)
if !ok || len(payload) > 0 {
return nil, parseError(msgUserAuthRequest)
}
if p.upstream == nil {
if pipeauth.PasswordBeforePublicKeyCallback != nil {
pipeauth.PasswordBeforePublicKeyCallback(password, &data)
}
p.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"publickey"},
PartialSuccess: true,
}))
return nil, nil
}
authType, authMethod, err = pipeauth.PasswordCallback(d, password, &data)
if err != nil {
return nil, err
}
case "keyboard-interactive":
if p.upstream == nil {
prompter := &sshClientKeyboardInteractive{d.connection}
answers, err := prompter.Challenge("", pipeauth.InteractiveInstrution, pipeauth.InteractiveQuestions, pipeauth.InteractiveEcho)
if err != nil {
return nil, err
}
upconn, err = upconnCallback(mappedUser, nil, answers, &data)
if err != nil || upconn == nil {
return nil, err
}
addr := upconn.RemoteAddr().String()
hostIp = addr
u, err := newUpstream(upconn, addr, &ClientConfig{
HostKeyCallback: pipeauth.UpstreamHostKeyCallback,
})
if err != nil {
return nil, err
}
defer func() {
if p == nil {
u.Close()
}
}()
u.user = mappedUser
userName = u.user
p.upstream = u
err = p.upstream.sendAuthReq()
if err != nil {
return nil, err
}
authType = AuthPipeTypeMap
if data.HasSentPassword {
authMethod = Password(string(data.Password))
} else if data.CertSigner != nil {
authMethod = PublicKeys(data.CertSigner)
} else {
return nil, errors.New("No auth credential provided")
}
}
default:
}
switch authType {
case AuthPipeTypePassThrough:
msg.User = mappedUser
return msg, nil
case AuthPipeTypeDiscard:
return nil, nil
case AuthPipeTypeNone:
return noneAuthMsg(mappedUser), nil
case AuthPipeTypeMap:
}
// map publickey, password, etc to auth
switch authMethod.method() {
case "publickey":
f, ok := authMethod.(publicKeyCallback)
if !ok {
return nil, errors.New("sshpiper: publicKeyCallback type assertions failed")
}
signers, err := f()
// no mapped user change it to none or error occur
if err != nil || len(signers) == 0 {
return nil, err
}
for _, signer := range signers {
msg, err = p.signAgain(mappedUser, msg, signer)
if err != nil {
return nil, err
}
return msg, nil
}
case "password":
f, ok := authMethod.(passwordCallback)
if !ok {
return nil, errors.New("sshpiper: passwordCallback type assertions failed")
}
pw, err := f()
if err != nil {
return nil, err
}
type passwordAuthMsg struct {
User string `sshtype:"50"`
Service string
Method string
Reply bool
Password string
}
Unmarshal(Marshal(passwordAuthMsg{
User: mappedUser,
Service: serviceSSH,
Method: "password",
Reply: false,
Password: pw,
}), msg)
return msg, nil
default:
}
msg.User = mappedUser
return msg, nil
}
err = p.pipeAuth(userAuthReq)
if err != nil {
return nil, err
}
loginTime := time.Now().Unix()
return &PiperConn{
pipedConn: p,
LoginTime: loginTime,
HostIp: hostIp,
ClientIp: clientIp,
Username: userName,
LogCallback: piper.LogCallback,
}, nil
}
func (pipe *pipedConn) ack(key PublicKey) error {
okMsg := userAuthPubKeyOkMsg{
Algo: key.Type(),
PubKey: key.Marshal(),
}
return pipe.downstream.transport.writePacket(Marshal(&okMsg))
}
// not used after method to method map enable
//func (pipe *pipedConn) validAndAck(user string, upKey, downKey PublicKey) (*userAuthRequestMsg, error) {
//
// ok, err := validateKey(upKey, user, pipe.upstream.transport)
//
// if ok {
//
// if err = pipe.ack(downKey); err != nil {
// return nil, err
// }
//
// return nil, nil
// }
//
// return noneAuthMsg(user), nil
//}
func (pipe *pipedConn) checkPublicKey(algo string, msg *userAuthRequestMsg, pubkey PublicKey, sig *Signature) (bool, error) {
if !isAcceptableAlgo(sig.Format) {
return false, fmt.Errorf("ssh: algorithm %q not accepted", sig.Format)
}
if underlyingAlgo(algo) != sig.Format {
return false, fmt.Errorf("ssh: signature %q not compatible with selected algorithm %q", sig.Format, algo)
}
signedData := buildDataSignedForAuth(pipe.downstream.transport.getSessionID(), *msg, algo, pubkey.Marshal())
if err := pubkey.Verify(signedData, sig); err != nil {
return false, nil
}
return true, nil
}
func (pipe *pipedConn) signAgain(user string, msg *userAuthRequestMsg, signer Signer) (*userAuthRequestMsg, error) {
rand := pipe.upstream.transport.config.Rand
session := pipe.upstream.transport.getSessionID()
upKey := signer.PublicKey()
upKeyData := upKey.Marshal()
sign, err := signer.Sign(rand, buildDataSignedForAuth(session, userAuthRequestMsg{
User: user,
Service: serviceSSH,
Method: "publickey",
}, upKey.Type(), upKeyData))
if err != nil {
return nil, err
}
// manually wrap the serialized signature in a string
s := Marshal(sign)
sig := make([]byte, stringLength(len(s)))
marshalString(sig, s)
pubkeyMsg := &publickeyAuthMsg{
User: user,
Service: serviceSSH,
Method: "publickey",
HasSig: true,
Algoname: upKey.Type(),
PubKey: upKeyData,
Sig: sig,
}
Unmarshal(Marshal(pubkeyMsg), msg)
return msg, nil
}
func parsePublicKeyMsg(userAuthReq *userAuthRequestMsg) (string, PublicKey, bool, *Signature, error) {
if userAuthReq.Method != "publickey" {
return "", nil, false, nil, fmt.Errorf("not a publickey auth msg")
}
payload := userAuthReq.Payload
if len(payload) < 1 {
return "", nil, false, nil, parseError(msgUserAuthRequest)
}
isQuery := payload[0] == 0
payload = payload[1:]
algoBytes, payload, ok := parseString(payload)
if !ok {
return "", nil, false, nil, parseError(msgUserAuthRequest)
}
algo := string(algoBytes)
if !isAcceptableAlgo(algo) {
return "", nil, false, nil, fmt.Errorf("ssh: algorithm %q not accepted", algo)
}
pubKeyData, payload, ok := parseString(payload)
if !ok {
return "", nil, false, nil, parseError(msgUserAuthRequest)
}
pubKey, err := ParsePublicKey(pubKeyData)
if err != nil {
return "", nil, false, nil, err
}
var sig *Signature
if !isQuery {
sig, payload, ok = parseSignature(payload)
if !ok || len(payload) > 0 {
return "", nil, false, nil, parseError(msgUserAuthRequest)
}
}
return algo, pubKey, isQuery, sig, nil
}
func piping(dst, src packetConn, hooker func(msg []byte) ([]byte, error)) error {
for {
p, err := src.readPacket()
if err != nil {
return err
}
p, err = hooker(p)
if err != nil {
return err
}
err = dst.writePacket(p)
if err != nil {
return err
}
}
}
func (pipe *pipedConn) loop() error {
c := make(chan error)
go func() {
c <- piping(pipe.upstream.transport, pipe.downstream.transport, pipe.hookDownstreamMsg)
}()
go func() {
c <- piping(pipe.downstream.transport, pipe.upstream.transport, pipe.hookUpstreamMsg)
}()
defer pipe.Close()
// wait until either connection closed
return <-c
}
func (pipe *pipedConn) Close() {
pipe.upstream.transport.Close()
pipe.downstream.transport.Close()
}
func (pipe *pipedConn) pipeAuthSkipBanner(method string, packet []byte) (bool, error) {
// pipe to auth succ if not a authreq
// typically, authinfo see RFC 4256
// TODO support hook this msg
err := pipe.upstream.transport.writePacket(packet)
if err != nil {
return false, err
}
for {
packet, err := pipe.upstream.transport.readPacket()
if err != nil {
return false, err
}
msgType := packet[0]
if msgType == msgUserAuthFailure && method == "publickey" {
err = pipe.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"password"},
PartialSuccess: true,
}))
return false, err
}
if err = pipe.downstream.transport.writePacket(packet); err != nil {
return false, err
}
switch msgType {
case msgUserAuthSuccess:
return true, nil
case msgUserAuthBanner:
// should read another packet from upstream
continue
case msgUserAuthFailure:
default:
}
return false, nil
}
}
func (pipe *pipedConn) pipeAuth(initUserAuthMsg *userAuthRequestMsg) error {
var err error
// err := pipe.upstream.sendAuthReq()
// if err != nil {
// return err
// }
userAuthMsg := initUserAuthMsg
for {
// hook msg
userAuthMsg, err = pipe.processAuthMsg(userAuthMsg)
if err != nil {
return err
}
// nil for ignore
if userAuthMsg != nil {
// send a mapped auth msg
succ, err := pipe.pipeAuthSkipBanner(userAuthMsg.Method, Marshal(userAuthMsg))
if err != nil {
return err
}
if succ {
return nil
}
}/* else {
pipe.downstream.transport.writePacket(Marshal(userAuthFailureMsg {
Methods: []string {"publickey"},
PartialSuccess: false,
}))
}*/
var packet []byte
for {
// find next msg which need to be hooked
if packet, err = pipe.downstream.transport.readPacket(); err != nil {
return err
}
// we can only handle auth req at the moment
if packet[0] == msgUserAuthRequest {
// should hook, deal with it
break
}
if pipe.upstream == nil {
break
}
// pipe other auth msg
succ, err := pipe.pipeAuthSkipBanner("", packet)
if err != nil {
return err
}
if succ {
return nil
}
}
var userAuthReq userAuthRequestMsg
if err = Unmarshal(packet, &userAuthReq); err != nil {
return err
}
userAuthMsg = &userAuthReq
}
}
func (u *upstream) sendAuthReq() error {
if err := u.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil {
return err
}
packet, err := u.transport.readPacket()
if err != nil {
return err
}
if len(packet) > 0 && packet[0] == msgExtInfo {
_, err = parseExtInfoMsg(packet)
if err != nil {
return err
}
packet, err = u.transport.readPacket()
if err != nil {
return err
}
}
var serviceAccept serviceAcceptMsg
return Unmarshal(packet, &serviceAccept)
}
func newDownstream(c net.Conn, config *ServerConfig) (*downstream, error) {
fullConf := *config
fullConf.SetDefaults()
s := &connection{
sshConn: sshConn{conn: c},
}
_, err := s.serverHandshakeNoAuth(&fullConf)
if err != nil {
c.Close()
return nil, err
}
return &downstream{s}, nil
}
func newUpstream(c net.Conn, addr string, config *ClientConfig) (*upstream, error) {
fullConf := *config
fullConf.SetDefaults()
conn := &connection{
sshConn: sshConn{conn: c},
}
if err := conn.clientHandshakeNoAuth(addr, &fullConf); err != nil {
c.Close()
return nil, err
}
return &upstream{conn}, nil
}
func (d *downstream) nextAuthMsg() (*userAuthRequestMsg, error) {
var userAuthReq userAuthRequestMsg
if packet, err := d.transport.readPacket(); err != nil {
return nil, err
} else if err = Unmarshal(packet, &userAuthReq); err != nil {
return nil, err
}
if userAuthReq.Service != serviceSSH {
return nil, errors.New("ssh: client attempted to negotiate for unknown service: " + userAuthReq.Service)
}
return &userAuthReq, nil
}
func noneAuthMsg(user string) *userAuthRequestMsg {
return &userAuthRequestMsg{
User: user,
Service: serviceSSH,
Method: "none",
}
}
func (c *connection) clientHandshakeNoAuth(dialAddress string, config *ClientConfig) error {
c.clientVersion = []byte(packageVersion)
if config.ClientVersion != "" {
c.clientVersion = []byte(config.ClientVersion)
}
var err error