1// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package ssh
6
7import (
8 "bytes"
9 "errors"
10 "fmt"
11 "io"
12 "slices"
13 "strings"
14)
15
16type authResult int
17
18const (
19 authFailure authResult = iota
20 authPartialSuccess
21 authSuccess
22)
23
24// clientAuthenticate authenticates with the remote server. See RFC 4252.
25func (c *connection) clientAuthenticate(config *ClientConfig) error {
26 // initiate user auth session
27 if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil {
28 return err
29 }
30 packet, err := c.transport.readPacket()
31 if err != nil {
32 return err
33 }
34 // The server may choose to send a SSH_MSG_EXT_INFO at this point (if we
35 // advertised willingness to receive one, which we always do) or not. See
36 // RFC 8308, Section 2.4.
37 extensions := make(map[string][]byte)
38 if len(packet) > 0 && packet[0] == msgExtInfo {
39 var extInfo extInfoMsg
40 if err := Unmarshal(packet, &extInfo); err != nil {
41 return err
42 }
43 payload := extInfo.Payload
44 for i := uint32(0); i < extInfo.NumExtensions; i++ {
45 name, rest, ok := parseString(payload)
46 if !ok {
47 return parseError(msgExtInfo)
48 }
49 value, rest, ok := parseString(rest)
50 if !ok {
51 return parseError(msgExtInfo)
52 }
53 extensions[string(name)] = value
54 payload = rest
55 }
56 packet, err = c.transport.readPacket()
57 if err != nil {
58 return err
59 }
60 }
61 var serviceAccept serviceAcceptMsg
62 if err := Unmarshal(packet, &serviceAccept); err != nil {
63 return err
64 }
65
66 // during the authentication phase the client first attempts the "none" method
67 // then any untried methods suggested by the server.
68 var tried []string
69 var lastMethods []string
70
71 sessionID := c.transport.getSessionID()
72 for auth := AuthMethod(new(noneAuth)); auth != nil; {
73 ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand, extensions)
74 if err != nil {
75 // On disconnect, return error immediately
76 if _, ok := err.(*disconnectMsg); ok {
77 return err
78 }
79 // We return the error later if there is no other method left to
80 // try.
81 ok = authFailure
82 }
83 if ok == authSuccess {
84 // success
85 return nil
86 } else if ok == authFailure {
87 if m := auth.method(); !slices.Contains(tried, m) {
88 tried = append(tried, m)
89 }
90 }
91 if methods == nil {
92 methods = lastMethods
93 }
94 lastMethods = methods
95
96 auth = nil
97
98 findNext:
99 for _, a := range config.Auth {
100 candidateMethod := a.method()
101 if slices.Contains(tried, candidateMethod) {
102 continue
103 }
104 for _, meth := range methods {
105 if meth == candidateMethod {
106 auth = a
107 break findNext
108 }
109 }
110 }
111
112 if auth == nil && err != nil {
113 // We have an error and there are no other authentication methods to
114 // try, so we return it.
115 return err
116 }
117 }
118 return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", tried)
119}
120
121// An AuthMethod represents an instance of an RFC 4252 authentication method.
122type AuthMethod interface {
123 // auth authenticates user over transport t.
124 // Returns true if authentication is successful.
125 // If authentication is not successful, a []string of alternative
126 // method names is returned. If the slice is nil, it will be ignored
127 // and the previous set of possible methods will be reused.
128 auth(session []byte, user string, p packetConn, rand io.Reader, extensions map[string][]byte) (authResult, []string, error)
129
130 // method returns the RFC 4252 method name.
131 method() string
132}
133
134// "none" authentication, RFC 4252 section 5.2.
135type noneAuth int
136
137func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
138 if err := c.writePacket(Marshal(&userAuthRequestMsg{
139 User: user,
140 Service: serviceSSH,
141 Method: "none",
142 })); err != nil {
143 return authFailure, nil, err
144 }
145
146 return handleAuthResponse(c)
147}
148
149func (n *noneAuth) method() string {
150 return "none"
151}
152
153// passwordCallback is an AuthMethod that fetches the password through
154// a function call, e.g. by prompting the user.
155type passwordCallback func() (password string, err error)
156
157func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
158 type passwordAuthMsg struct {
159 User string `sshtype:"50"`
160 Service string
161 Method string
162 Reply bool
163 Password string
164 }
165
166 pw, err := cb()
167 // REVIEW NOTE: is there a need to support skipping a password attempt?
168 // The program may only find out that the user doesn't have a password
169 // when prompting.
170 if err != nil {
171 return authFailure, nil, err
172 }
173
174 if err := c.writePacket(Marshal(&passwordAuthMsg{
175 User: user,
176 Service: serviceSSH,
177 Method: cb.method(),
178 Reply: false,
179 Password: pw,
180 })); err != nil {
181 return authFailure, nil, err
182 }
183
184 return handleAuthResponse(c)
185}
186
187func (cb passwordCallback) method() string {
188 return "password"
189}
190
191// Password returns an AuthMethod using the given password.
192func Password(secret string) AuthMethod {
193 return passwordCallback(func() (string, error) { return secret, nil })
194}
195
196// PasswordCallback returns an AuthMethod that uses a callback for
197// fetching a password.
198func PasswordCallback(prompt func() (secret string, err error)) AuthMethod {
199 return passwordCallback(prompt)
200}
201
202type publickeyAuthMsg struct {
203 User string `sshtype:"50"`
204 Service string
205 Method string
206 // HasSig indicates to the receiver packet that the auth request is signed and
207 // should be used for authentication of the request.
208 HasSig bool
209 Algoname string
210 PubKey []byte
211 // Sig is tagged with "rest" so Marshal will exclude it during
212 // validateKey
213 Sig []byte `ssh:"rest"`
214}
215
216// publicKeyCallback is an AuthMethod that uses a set of key
217// pairs for authentication.
218type publicKeyCallback func() ([]Signer, error)
219
220func (cb publicKeyCallback) method() string {
221 return "publickey"
222}
223
224func pickSignatureAlgorithm(signer Signer, extensions map[string][]byte) (MultiAlgorithmSigner, string, error) {
225 var as MultiAlgorithmSigner
226 keyFormat := signer.PublicKey().Type()
227
228 // If the signer implements MultiAlgorithmSigner we use the algorithms it
229 // support, if it implements AlgorithmSigner we assume it supports all
230 // algorithms, otherwise only the key format one.
231 switch s := signer.(type) {
232 case MultiAlgorithmSigner:
233 as = s
234 case AlgorithmSigner:
235 as = &multiAlgorithmSigner{
236 AlgorithmSigner: s,
237 supportedAlgorithms: algorithmsForKeyFormat(underlyingAlgo(keyFormat)),
238 }
239 default:
240 as = &multiAlgorithmSigner{
241 AlgorithmSigner: algorithmSignerWrapper{signer},
242 supportedAlgorithms: []string{underlyingAlgo(keyFormat)},
243 }
244 }
245
246 getFallbackAlgo := func() (string, error) {
247 // Fallback to use if there is no "server-sig-algs" extension or a
248 // common algorithm cannot be found. We use the public key format if the
249 // MultiAlgorithmSigner supports it, otherwise we return an error.
250 if !slices.Contains(as.Algorithms(), underlyingAlgo(keyFormat)) {
251 return "", fmt.Errorf("ssh: no common public key signature algorithm, server only supports %q for key type %q, signer only supports %v",
252 underlyingAlgo(keyFormat), keyFormat, as.Algorithms())
253 }
254 return keyFormat, nil
255 }
256
257 extPayload, ok := extensions["server-sig-algs"]
258 if !ok {
259 // If there is no "server-sig-algs" extension use the fallback
260 // algorithm.
261 algo, err := getFallbackAlgo()
262 return as, algo, err
263 }
264
265 // The server-sig-algs extension only carries underlying signature
266 // algorithm, but we are trying to select a protocol-level public key
267 // algorithm, which might be a certificate type. Extend the list of server
268 // supported algorithms to include the corresponding certificate algorithms.
269 serverAlgos := strings.Split(string(extPayload), ",")
270 for _, algo := range serverAlgos {
271 if certAlgo, ok := certificateAlgo(algo); ok {
272 serverAlgos = append(serverAlgos, certAlgo)
273 }
274 }
275
276 // Filter algorithms based on those supported by MultiAlgorithmSigner.
277 // Iterate over the signer's algorithms first to preserve its preference order.
278 supportedKeyAlgos := algorithmsForKeyFormat(keyFormat)
279 var keyAlgos []string
280 for _, signerAlgo := range as.Algorithms() {
281 if idx := slices.IndexFunc(supportedKeyAlgos, func(algo string) bool {
282 return underlyingAlgo(algo) == signerAlgo
283 }); idx >= 0 {
284 keyAlgos = append(keyAlgos, supportedKeyAlgos[idx])
285 }
286 }
287
288 algo, err := findCommon("public key signature algorithm", keyAlgos, serverAlgos, true)
289 if err != nil {
290 // If there is no overlap, return the fallback algorithm to support
291 // servers that fail to list all supported algorithms.
292 algo, err := getFallbackAlgo()
293 return as, algo, err
294 }
295 return as, algo, nil
296}
297
298func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader, extensions map[string][]byte) (authResult, []string, error) {
299 // Authentication is performed by sending an enquiry to test if a key is
300 // acceptable to the remote. If the key is acceptable, the client will
301 // attempt to authenticate with the valid key. If not the client will repeat
302 // the process with the remaining keys.
303
304 signers, err := cb()
305 if err != nil {
306 return authFailure, nil, err
307 }
308 var methods []string
309 var errSigAlgo error
310
311 origSignersLen := len(signers)
312 for idx := 0; idx < len(signers); idx++ {
313 signer := signers[idx]
314 pub := signer.PublicKey()
315 as, algo, err := pickSignatureAlgorithm(signer, extensions)
316 if err != nil && errSigAlgo == nil {
317 // If we cannot negotiate a signature algorithm store the first
318 // error so we can return it to provide a more meaningful message if
319 // no other signers work.
320 errSigAlgo = err
321 continue
322 }
323 ok, err := validateKey(pub, algo, user, c)
324 if err != nil {
325 return authFailure, nil, err
326 }
327 // OpenSSH 7.2-7.7 advertises support for rsa-sha2-256 and rsa-sha2-512
328 // in the "server-sig-algs" extension but doesn't support these
329 // algorithms for certificate authentication, so if the server rejects
330 // the key try to use the obtained algorithm as if "server-sig-algs" had
331 // not been implemented if supported from the algorithm signer.
332 if !ok && idx < origSignersLen && isRSACert(algo) && algo != CertAlgoRSAv01 {
333 if slices.Contains(as.Algorithms(), KeyAlgoRSA) {
334 // We retry using the compat algorithm after all signers have
335 // been tried normally.
336 signers = append(signers, &multiAlgorithmSigner{
337 AlgorithmSigner: as,
338 supportedAlgorithms: []string{KeyAlgoRSA},
339 })
340 }
341 }
342 if !ok {
343 continue
344 }
345
346 pubKey := pub.Marshal()
347 data := buildDataSignedForAuth(session, userAuthRequestMsg{
348 User: user,
349 Service: serviceSSH,
350 Method: cb.method(),
351 }, algo, pubKey)
352 sign, err := as.SignWithAlgorithm(rand, data, underlyingAlgo(algo))
353 if err != nil {
354 return authFailure, nil, err
355 }
356
357 // manually wrap the serialized signature in a string
358 s := Marshal(sign)
359 sig := make([]byte, stringLength(len(s)))
360 marshalString(sig, s)
361 msg := publickeyAuthMsg{
362 User: user,
363 Service: serviceSSH,
364 Method: cb.method(),
365 HasSig: true,
366 Algoname: algo,
367 PubKey: pubKey,
368 Sig: sig,
369 }
370 p := Marshal(&msg)
371 if err := c.writePacket(p); err != nil {
372 return authFailure, nil, err
373 }
374 var success authResult
375 success, methods, err = handleAuthResponse(c)
376 if err != nil {
377 return authFailure, nil, err
378 }
379
380 // If authentication succeeds or the list of available methods does not
381 // contain the "publickey" method, do not attempt to authenticate with any
382 // other keys. According to RFC 4252 Section 7, the latter can occur when
383 // additional authentication methods are required.
384 if success == authSuccess || !slices.Contains(methods, cb.method()) {
385 return success, methods, err
386 }
387 }
388
389 return authFailure, methods, errSigAlgo
390}
391
392// validateKey validates the key provided is acceptable to the server.
393func validateKey(key PublicKey, algo string, user string, c packetConn) (bool, error) {
394 pubKey := key.Marshal()
395 msg := publickeyAuthMsg{
396 User: user,
397 Service: serviceSSH,
398 Method: "publickey",
399 HasSig: false,
400 Algoname: algo,
401 PubKey: pubKey,
402 }
403 if err := c.writePacket(Marshal(&msg)); err != nil {
404 return false, err
405 }
406
407 return confirmKeyAck(key, c)
408}
409
410func confirmKeyAck(key PublicKey, c packetConn) (bool, error) {
411 pubKey := key.Marshal()
412
413 for {
414 packet, err := c.readPacket()
415 if err != nil {
416 return false, err
417 }
418 switch packet[0] {
419 case msgUserAuthBanner:
420 if err := handleBannerResponse(c, packet); err != nil {
421 return false, err
422 }
423 case msgUserAuthPubKeyOk:
424 var msg userAuthPubKeyOkMsg
425 if err := Unmarshal(packet, &msg); err != nil {
426 return false, err
427 }
428 // According to RFC 4252 Section 7 the algorithm in
429 // SSH_MSG_USERAUTH_PK_OK should match that of the request but some
430 // servers send the key type instead. OpenSSH allows any algorithm
431 // that matches the public key, so we do the same.
432 // https://github.com/openssh/openssh-portable/blob/86bdd385/sshconnect2.c#L709
433 if !slices.Contains(algorithmsForKeyFormat(key.Type()), msg.Algo) {
434 return false, nil
435 }
436 if !bytes.Equal(msg.PubKey, pubKey) {
437 return false, nil
438 }
439 return true, nil
440 case msgUserAuthFailure:
441 return false, nil
442 default:
443 return false, unexpectedMessageError(msgUserAuthPubKeyOk, packet[0])
444 }
445 }
446}
447
448// PublicKeys returns an AuthMethod that uses the given key
449// pairs.
450func PublicKeys(signers ...Signer) AuthMethod {
451 return publicKeyCallback(func() ([]Signer, error) { return signers, nil })
452}
453
454// PublicKeysCallback returns an AuthMethod that runs the given
455// function to obtain a list of key pairs.
456func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod {
457 return publicKeyCallback(getSigners)
458}
459
460// handleAuthResponse returns whether the preceding authentication request succeeded
461// along with a list of remaining authentication methods to try next and
462// an error if an unexpected response was received.
463func handleAuthResponse(c packetConn) (authResult, []string, error) {
464 gotMsgExtInfo := false
465 for {
466 packet, err := c.readPacket()
467 if err != nil {
468 return authFailure, nil, err
469 }
470
471 switch packet[0] {
472 case msgUserAuthBanner:
473 if err := handleBannerResponse(c, packet); err != nil {
474 return authFailure, nil, err
475 }
476 case msgExtInfo:
477 // Ignore post-authentication RFC 8308 extensions, once.
478 if gotMsgExtInfo {
479 return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
480 }
481 gotMsgExtInfo = true
482 case msgUserAuthFailure:
483 var msg userAuthFailureMsg
484 if err := Unmarshal(packet, &msg); err != nil {
485 return authFailure, nil, err
486 }
487 if msg.PartialSuccess {
488 return authPartialSuccess, msg.Methods, nil
489 }
490 return authFailure, msg.Methods, nil
491 case msgUserAuthSuccess:
492 return authSuccess, nil, nil
493 default:
494 return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
495 }
496 }
497}
498
499func handleBannerResponse(c packetConn, packet []byte) error {
500 var msg userAuthBannerMsg
501 if err := Unmarshal(packet, &msg); err != nil {
502 return err
503 }
504
505 transport, ok := c.(*handshakeTransport)
506 if !ok {
507 return nil
508 }
509
510 if transport.bannerCallback != nil {
511 return transport.bannerCallback(msg.Message)
512 }
513
514 return nil
515}
516
517// KeyboardInteractiveChallenge should print questions, optionally
518// disabling echoing (e.g. for passwords), and return all the answers.
519// Challenge may be called multiple times in a single session. After
520// successful authentication, the server may send a challenge with no
521// questions, for which the name and instruction messages should be
522// printed. RFC 4256 section 3.3 details how the UI should behave for
523// both CLI and GUI environments.
524type KeyboardInteractiveChallenge func(name, instruction string, questions []string, echos []bool) (answers []string, err error)
525
526// KeyboardInteractive returns an AuthMethod using a prompt/response
527// sequence controlled by the server.
528func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod {
529 return challenge
530}
531
532func (cb KeyboardInteractiveChallenge) method() string {
533 return "keyboard-interactive"
534}
535
536func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
537 type initiateMsg struct {
538 User string `sshtype:"50"`
539 Service string
540 Method string
541 Language string
542 Submethods string
543 }
544
545 if err := c.writePacket(Marshal(&initiateMsg{
546 User: user,
547 Service: serviceSSH,
548 Method: "keyboard-interactive",
549 })); err != nil {
550 return authFailure, nil, err
551 }
552
553 gotMsgExtInfo := false
554 gotUserAuthInfoRequest := false
555 for {
556 packet, err := c.readPacket()
557 if err != nil {
558 return authFailure, nil, err
559 }
560
561 // like handleAuthResponse, but with less options.
562 switch packet[0] {
563 case msgUserAuthBanner:
564 if err := handleBannerResponse(c, packet); err != nil {
565 return authFailure, nil, err
566 }
567 continue
568 case msgExtInfo:
569 // Ignore post-authentication RFC 8308 extensions, once.
570 if gotMsgExtInfo {
571 return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
572 }
573 gotMsgExtInfo = true
574 continue
575 case msgUserAuthInfoRequest:
576 // OK
577 case msgUserAuthFailure:
578 var msg userAuthFailureMsg
579 if err := Unmarshal(packet, &msg); err != nil {
580 return authFailure, nil, err
581 }
582 if msg.PartialSuccess {
583 return authPartialSuccess, msg.Methods, nil
584 }
585 if !gotUserAuthInfoRequest {
586 return authFailure, msg.Methods, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
587 }
588 return authFailure, msg.Methods, nil
589 case msgUserAuthSuccess:
590 return authSuccess, nil, nil
591 default:
592 return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0])
593 }
594
595 var msg userAuthInfoRequestMsg
596 if err := Unmarshal(packet, &msg); err != nil {
597 return authFailure, nil, err
598 }
599 gotUserAuthInfoRequest = true
600
601 // Manually unpack the prompt/echo pairs.
602 rest := msg.Prompts
603 var prompts []string
604 var echos []bool
605 for i := 0; i < int(msg.NumPrompts); i++ {
606 prompt, r, ok := parseString(rest)
607 if !ok || len(r) == 0 {
608 return authFailure, nil, errors.New("ssh: prompt format error")
609 }
610 prompts = append(prompts, string(prompt))
611 echos = append(echos, r[0] != 0)
612 rest = r[1:]
613 }
614
615 if len(rest) != 0 {
616 return authFailure, nil, errors.New("ssh: extra data following keyboard-interactive pairs")
617 }
618
619 answers, err := cb(msg.Name, msg.Instruction, prompts, echos)
620 if err != nil {
621 return authFailure, nil, err
622 }
623
624 if len(answers) != len(prompts) {
625 return authFailure, nil, fmt.Errorf("ssh: incorrect number of answers from keyboard-interactive callback %d (expected %d)", len(answers), len(prompts))
626 }
627 responseLength := 1 + 4
628 for _, a := range answers {
629 responseLength += stringLength(len(a))
630 }
631 serialized := make([]byte, responseLength)
632 p := serialized
633 p[0] = msgUserAuthInfoResponse
634 p = p[1:]
635 p = marshalUint32(p, uint32(len(answers)))
636 for _, a := range answers {
637 p = marshalString(p, []byte(a))
638 }
639
640 if err := c.writePacket(serialized); err != nil {
641 return authFailure, nil, err
642 }
643 }
644}
645
646type retryableAuthMethod struct {
647 authMethod AuthMethod
648 maxTries int
649}
650
651func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader, extensions map[string][]byte) (ok authResult, methods []string, err error) {
652 for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ {
653 ok, methods, err = r.authMethod.auth(session, user, c, rand, extensions)
654 if ok != authFailure || err != nil { // either success, partial success or error terminate
655 return ok, methods, err
656 }
657 }
658 return ok, methods, err
659}
660
661func (r *retryableAuthMethod) method() string {
662 return r.authMethod.method()
663}
664
665// RetryableAuthMethod is a decorator for other auth methods enabling them to
666// be retried up to maxTries before considering that AuthMethod itself failed.
667// If maxTries is <= 0, will retry indefinitely
668//
669// This is useful for interactive clients using challenge/response type
670// authentication (e.g. Keyboard-Interactive, Password, etc) where the user
671// could mistype their response resulting in the server issuing a
672// SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4
673// [keyboard-interactive]); Without this decorator, the non-retryable
674// AuthMethod would be removed from future consideration, and never tried again
675// (and so the user would never be able to retry their entry).
676func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod {
677 return &retryableAuthMethod{authMethod: auth, maxTries: maxTries}
678}
679
680// GSSAPIWithMICAuthMethod is an AuthMethod with "gssapi-with-mic" authentication.
681// See RFC 4462 section 3
682// gssAPIClient is implementation of the GSSAPIClient interface, see the definition of the interface for details.
683// target is the server host you want to log in to.
684func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod {
685 if gssAPIClient == nil {
686 panic("gss-api client must be not nil with enable gssapi-with-mic")
687 }
688 return &gssAPIWithMICCallback{gssAPIClient: gssAPIClient, target: target}
689}
690
691type gssAPIWithMICCallback struct {
692 gssAPIClient GSSAPIClient
693 target string
694}
695
696func (g *gssAPIWithMICCallback) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) {
697 m := &userAuthRequestMsg{
698 User: user,
699 Service: serviceSSH,
700 Method: g.method(),
701 }
702 // The GSS-API authentication method is initiated when the client sends an SSH_MSG_USERAUTH_REQUEST.
703 // See RFC 4462 section 3.2.
704 m.Payload = appendU32(m.Payload, 1)
705 m.Payload = appendString(m.Payload, string(krb5OID))
706 if err := c.writePacket(Marshal(m)); err != nil {
707 return authFailure, nil, err
708 }
709 // The server responds to the SSH_MSG_USERAUTH_REQUEST with either an
710 // SSH_MSG_USERAUTH_FAILURE if none of the mechanisms are supported or
711 // with an SSH_MSG_USERAUTH_GSSAPI_RESPONSE.
712 // See RFC 4462 section 3.3.
713 // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication,so I don't want to check
714 // selected mech if it is valid.
715 packet, err := c.readPacket()
716 if err != nil {
717 return authFailure, nil, err
718 }
719 userAuthGSSAPIResp := &userAuthGSSAPIResponse{}
720 if err := Unmarshal(packet, userAuthGSSAPIResp); err != nil {
721 return authFailure, nil, err
722 }
723 // Start the loop into the exchange token.
724 // See RFC 4462 section 3.4.
725 var token []byte
726 defer g.gssAPIClient.DeleteSecContext()
727 for {
728 // Initiates the establishment of a security context between the application and a remote peer.
729 nextToken, needContinue, err := g.gssAPIClient.InitSecContext("host@"+g.target, token, false)
730 if err != nil {
731 return authFailure, nil, err
732 }
733 if len(nextToken) > 0 {
734 if err := c.writePacket(Marshal(&userAuthGSSAPIToken{
735 Token: nextToken,
736 })); err != nil {
737 return authFailure, nil, err
738 }
739 }
740 if !needContinue {
741 break
742 }
743 packet, err = c.readPacket()
744 if err != nil {
745 return authFailure, nil, err
746 }
747 switch packet[0] {
748 case msgUserAuthFailure:
749 var msg userAuthFailureMsg
750 if err := Unmarshal(packet, &msg); err != nil {
751 return authFailure, nil, err
752 }
753 if msg.PartialSuccess {
754 return authPartialSuccess, msg.Methods, nil
755 }
756 return authFailure, msg.Methods, nil
757 case msgUserAuthGSSAPIError:
758 userAuthGSSAPIErrorResp := &userAuthGSSAPIError{}
759 if err := Unmarshal(packet, userAuthGSSAPIErrorResp); err != nil {
760 return authFailure, nil, err
761 }
762 return authFailure, nil, fmt.Errorf("GSS-API Error:\n"+
763 "Major Status: %d\n"+
764 "Minor Status: %d\n"+
765 "Error Message: %s\n", userAuthGSSAPIErrorResp.MajorStatus, userAuthGSSAPIErrorResp.MinorStatus,
766 userAuthGSSAPIErrorResp.Message)
767 case msgUserAuthGSSAPIToken:
768 userAuthGSSAPITokenReq := &userAuthGSSAPIToken{}
769 if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil {
770 return authFailure, nil, err
771 }
772 token = userAuthGSSAPITokenReq.Token
773 }
774 }
775 // Binding Encryption Keys.
776 // See RFC 4462 section 3.5.
777 micField := buildMIC(string(session), user, "ssh-connection", "gssapi-with-mic")
778 micToken, err := g.gssAPIClient.GetMIC(micField)
779 if err != nil {
780 return authFailure, nil, err
781 }
782 if err := c.writePacket(Marshal(&userAuthGSSAPIMIC{
783 MIC: micToken,
784 })); err != nil {
785 return authFailure, nil, err
786 }
787 return handleAuthResponse(c)
788}
789
790func (g *gssAPIWithMICCallback) method() string {
791 return "gssapi-with-mic"
792}