main
1// Copyright 2013 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 "errors"
9 "fmt"
10 "io"
11 "log"
12 "net"
13 "strings"
14 "sync"
15)
16
17// debugHandshake, if set, prints messages sent and received. Key
18// exchange messages are printed as if DH were used, so the debug
19// messages are wrong when using ECDH.
20const debugHandshake = false
21
22// chanSize sets the amount of buffering SSH connections. This is
23// primarily for testing: setting chanSize=0 uncovers deadlocks more
24// quickly.
25const chanSize = 16
26
27// maxPendingPackets sets the maximum number of packets to queue while waiting
28// for KEX to complete. This limits the total pending data to maxPendingPackets
29// * maxPacket bytes, which is ~16.8MB.
30const maxPendingPackets = 64
31
32// keyingTransport is a packet based transport that supports key
33// changes. It need not be thread-safe. It should pass through
34// msgNewKeys in both directions.
35type keyingTransport interface {
36 packetConn
37
38 // prepareKeyChange sets up a key change. The key change for a
39 // direction will be effected if a msgNewKeys message is sent
40 // or received.
41 prepareKeyChange(*algorithms, *kexResult) error
42
43 // setStrictMode sets the strict KEX mode, notably triggering
44 // sequence number resets on sending or receiving msgNewKeys.
45 // If the sequence number is already > 1 when setStrictMode
46 // is called, an error is returned.
47 setStrictMode() error
48
49 // setInitialKEXDone indicates to the transport that the initial key exchange
50 // was completed
51 setInitialKEXDone()
52}
53
54// handshakeTransport implements rekeying on top of a keyingTransport
55// and offers a thread-safe writePacket() interface.
56type handshakeTransport struct {
57 conn keyingTransport
58 config *Config
59
60 serverVersion []byte
61 clientVersion []byte
62
63 // hostKeys is non-empty if we are the server. In that case,
64 // it contains all host keys that can be used to sign the
65 // connection.
66 hostKeys []Signer
67
68 // publicKeyAuthAlgorithms is non-empty if we are the server. In that case,
69 // it contains the supported client public key authentication algorithms.
70 publicKeyAuthAlgorithms []string
71
72 // hostKeyAlgorithms is non-empty if we are the client. In that case,
73 // we accept these key types from the server as host key.
74 hostKeyAlgorithms []string
75
76 // On read error, incoming is closed, and readError is set.
77 incoming chan []byte
78 readError error
79
80 mu sync.Mutex
81 // Condition for the above mutex. It is used to notify a completed key
82 // exchange or a write failure. Writes can wait for this condition while a
83 // key exchange is in progress.
84 writeCond *sync.Cond
85 writeError error
86 sentInitPacket []byte
87 sentInitMsg *kexInitMsg
88 // Used to queue writes when a key exchange is in progress. The length is
89 // limited by pendingPacketsSize. Once full, writes will block until the key
90 // exchange is completed or an error occurs. If not empty, it is emptied
91 // all at once when the key exchange is completed in kexLoop.
92 pendingPackets [][]byte
93 writePacketsLeft uint32
94 writeBytesLeft int64
95 userAuthComplete bool // whether the user authentication phase is complete
96
97 // If the read loop wants to schedule a kex, it pings this
98 // channel, and the write loop will send out a kex
99 // message.
100 requestKex chan struct{}
101
102 // If the other side requests or confirms a kex, its kexInit
103 // packet is sent here for the write loop to find it.
104 startKex chan *pendingKex
105 kexLoopDone chan struct{} // closed (with writeError non-nil) when kexLoop exits
106
107 // data for host key checking
108 hostKeyCallback HostKeyCallback
109 dialAddress string
110 remoteAddr net.Addr
111
112 // bannerCallback is non-empty if we are the client and it has been set in
113 // ClientConfig. In that case it is called during the user authentication
114 // dance to handle a custom server's message.
115 bannerCallback BannerCallback
116
117 // Algorithms agreed in the last key exchange.
118 algorithms *algorithms
119
120 // Counters exclusively owned by readLoop.
121 readPacketsLeft uint32
122 readBytesLeft int64
123
124 // The session ID or nil if first kex did not complete yet.
125 sessionID []byte
126
127 // strictMode indicates if the other side of the handshake indicated
128 // that we should be following the strict KEX protocol restrictions.
129 strictMode bool
130}
131
132type pendingKex struct {
133 otherInit []byte
134 done chan error
135}
136
137func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
138 t := &handshakeTransport{
139 conn: conn,
140 serverVersion: serverVersion,
141 clientVersion: clientVersion,
142 incoming: make(chan []byte, chanSize),
143 requestKex: make(chan struct{}, 1),
144 startKex: make(chan *pendingKex),
145 kexLoopDone: make(chan struct{}),
146
147 config: config,
148 }
149 t.writeCond = sync.NewCond(&t.mu)
150 t.resetReadThresholds()
151 t.resetWriteThresholds()
152
153 // We always start with a mandatory key exchange.
154 t.requestKex <- struct{}{}
155 return t
156}
157
158func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
159 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
160 t.dialAddress = dialAddr
161 t.remoteAddr = addr
162 t.hostKeyCallback = config.HostKeyCallback
163 t.bannerCallback = config.BannerCallback
164 if config.HostKeyAlgorithms != nil {
165 t.hostKeyAlgorithms = config.HostKeyAlgorithms
166 } else {
167 t.hostKeyAlgorithms = supportedHostKeyAlgos
168 }
169 go t.readLoop()
170 go t.kexLoop()
171 return t
172}
173
174func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
175 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
176 t.hostKeys = config.hostKeys
177 t.publicKeyAuthAlgorithms = config.PublicKeyAuthAlgorithms
178 go t.readLoop()
179 go t.kexLoop()
180 return t
181}
182
183func (t *handshakeTransport) getSessionID() []byte {
184 return t.sessionID
185}
186
187// waitSession waits for the session to be established. This should be
188// the first thing to call after instantiating handshakeTransport.
189func (t *handshakeTransport) waitSession() error {
190 p, err := t.readPacket()
191 if err != nil {
192 return err
193 }
194 if p[0] != msgNewKeys {
195 return fmt.Errorf("ssh: first packet should be msgNewKeys")
196 }
197
198 return nil
199}
200
201func (t *handshakeTransport) id() string {
202 if len(t.hostKeys) > 0 {
203 return "server"
204 }
205 return "client"
206}
207
208func (t *handshakeTransport) printPacket(p []byte, write bool) {
209 action := "got"
210 if write {
211 action = "sent"
212 }
213
214 if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
215 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
216 } else {
217 msg, err := decode(p)
218 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
219 }
220}
221
222func (t *handshakeTransport) readPacket() ([]byte, error) {
223 p, ok := <-t.incoming
224 if !ok {
225 return nil, t.readError
226 }
227 return p, nil
228}
229
230func (t *handshakeTransport) readLoop() {
231 first := true
232 for {
233 p, err := t.readOnePacket(first)
234 first = false
235 if err != nil {
236 t.readError = err
237 close(t.incoming)
238 break
239 }
240 // If this is the first kex, and strict KEX mode is enabled,
241 // we don't ignore any messages, as they may be used to manipulate
242 // the packet sequence numbers.
243 if !(t.sessionID == nil && t.strictMode) && (p[0] == msgIgnore || p[0] == msgDebug) {
244 continue
245 }
246 t.incoming <- p
247 }
248
249 // Stop writers too.
250 t.recordWriteError(t.readError)
251
252 // Unblock the writer should it wait for this.
253 close(t.startKex)
254
255 // Don't close t.requestKex; it's also written to from writePacket.
256}
257
258func (t *handshakeTransport) pushPacket(p []byte) error {
259 if debugHandshake {
260 t.printPacket(p, true)
261 }
262 return t.conn.writePacket(p)
263}
264
265func (t *handshakeTransport) getWriteError() error {
266 t.mu.Lock()
267 defer t.mu.Unlock()
268 return t.writeError
269}
270
271func (t *handshakeTransport) recordWriteError(err error) {
272 t.mu.Lock()
273 defer t.mu.Unlock()
274 if t.writeError == nil && err != nil {
275 t.writeError = err
276 t.writeCond.Broadcast()
277 }
278}
279
280func (t *handshakeTransport) requestKeyExchange() {
281 select {
282 case t.requestKex <- struct{}{}:
283 default:
284 // something already requested a kex, so do nothing.
285 }
286}
287
288func (t *handshakeTransport) resetWriteThresholds() {
289 t.writePacketsLeft = packetRekeyThreshold
290 if t.config.RekeyThreshold > 0 {
291 t.writeBytesLeft = int64(t.config.RekeyThreshold)
292 } else if t.algorithms != nil {
293 t.writeBytesLeft = t.algorithms.w.rekeyBytes()
294 } else {
295 t.writeBytesLeft = 1 << 30
296 }
297}
298
299func (t *handshakeTransport) kexLoop() {
300
301write:
302 for t.getWriteError() == nil {
303 var request *pendingKex
304 var sent bool
305
306 for request == nil || !sent {
307 var ok bool
308 select {
309 case request, ok = <-t.startKex:
310 if !ok {
311 break write
312 }
313 case <-t.requestKex:
314 break
315 }
316
317 if !sent {
318 if err := t.sendKexInit(); err != nil {
319 t.recordWriteError(err)
320 break
321 }
322 sent = true
323 }
324 }
325
326 if err := t.getWriteError(); err != nil {
327 if request != nil {
328 request.done <- err
329 }
330 break
331 }
332
333 // We're not servicing t.requestKex, but that is OK:
334 // we never block on sending to t.requestKex.
335
336 // We're not servicing t.startKex, but the remote end
337 // has just sent us a kexInitMsg, so it can't send
338 // another key change request, until we close the done
339 // channel on the pendingKex request.
340
341 err := t.enterKeyExchange(request.otherInit)
342
343 t.mu.Lock()
344 t.writeError = err
345 t.sentInitPacket = nil
346 t.sentInitMsg = nil
347
348 t.resetWriteThresholds()
349
350 // we have completed the key exchange. Since the
351 // reader is still blocked, it is safe to clear out
352 // the requestKex channel. This avoids the situation
353 // where: 1) we consumed our own request for the
354 // initial kex, and 2) the kex from the remote side
355 // caused another send on the requestKex channel,
356 clear:
357 for {
358 select {
359 case <-t.requestKex:
360 //
361 default:
362 break clear
363 }
364 }
365
366 request.done <- t.writeError
367
368 // kex finished. Push packets that we received while
369 // the kex was in progress. Don't look at t.startKex
370 // and don't increment writtenSinceKex: if we trigger
371 // another kex while we are still busy with the last
372 // one, things will become very confusing.
373 for _, p := range t.pendingPackets {
374 t.writeError = t.pushPacket(p)
375 if t.writeError != nil {
376 break
377 }
378 }
379 t.pendingPackets = t.pendingPackets[:0]
380 // Unblock writePacket if waiting for KEX.
381 t.writeCond.Broadcast()
382 t.mu.Unlock()
383 }
384
385 // Unblock reader.
386 t.conn.Close()
387
388 // drain startKex channel. We don't service t.requestKex
389 // because nobody does blocking sends there.
390 for request := range t.startKex {
391 request.done <- t.getWriteError()
392 }
393
394 // Mark that the loop is done so that Close can return.
395 close(t.kexLoopDone)
396}
397
398// The protocol uses uint32 for packet counters, so we can't let them
399// reach 1<<32. We will actually read and write more packets than
400// this, though: the other side may send more packets, and after we
401// hit this limit on writing we will send a few more packets for the
402// key exchange itself.
403const packetRekeyThreshold = (1 << 31)
404
405func (t *handshakeTransport) resetReadThresholds() {
406 t.readPacketsLeft = packetRekeyThreshold
407 if t.config.RekeyThreshold > 0 {
408 t.readBytesLeft = int64(t.config.RekeyThreshold)
409 } else if t.algorithms != nil {
410 t.readBytesLeft = t.algorithms.r.rekeyBytes()
411 } else {
412 t.readBytesLeft = 1 << 30
413 }
414}
415
416func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
417 p, err := t.conn.readPacket()
418 if err != nil {
419 return nil, err
420 }
421
422 if t.readPacketsLeft > 0 {
423 t.readPacketsLeft--
424 } else {
425 t.requestKeyExchange()
426 }
427
428 if t.readBytesLeft > 0 {
429 t.readBytesLeft -= int64(len(p))
430 } else {
431 t.requestKeyExchange()
432 }
433
434 if debugHandshake {
435 t.printPacket(p, false)
436 }
437
438 if first && p[0] != msgKexInit {
439 return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
440 }
441
442 if p[0] != msgKexInit {
443 return p, nil
444 }
445
446 firstKex := t.sessionID == nil
447
448 kex := pendingKex{
449 done: make(chan error, 1),
450 otherInit: p,
451 }
452 t.startKex <- &kex
453 err = <-kex.done
454
455 if debugHandshake {
456 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
457 }
458
459 if err != nil {
460 return nil, err
461 }
462
463 t.resetReadThresholds()
464
465 // By default, a key exchange is hidden from higher layers by
466 // translating it into msgIgnore.
467 successPacket := []byte{msgIgnore}
468 if firstKex {
469 // sendKexInit() for the first kex waits for
470 // msgNewKeys so the authentication process is
471 // guaranteed to happen over an encrypted transport.
472 successPacket = []byte{msgNewKeys}
473 }
474
475 return successPacket, nil
476}
477
478const (
479 kexStrictClient = "kex-strict-c-v00@openssh.com"
480 kexStrictServer = "kex-strict-s-v00@openssh.com"
481)
482
483// sendKexInit sends a key change message.
484func (t *handshakeTransport) sendKexInit() error {
485 t.mu.Lock()
486 defer t.mu.Unlock()
487 if t.sentInitMsg != nil {
488 // kexInits may be sent either in response to the other side,
489 // or because our side wants to initiate a key change, so we
490 // may have already sent a kexInit. In that case, don't send a
491 // second kexInit.
492 return nil
493 }
494
495 msg := &kexInitMsg{
496 CiphersClientServer: t.config.Ciphers,
497 CiphersServerClient: t.config.Ciphers,
498 MACsClientServer: t.config.MACs,
499 MACsServerClient: t.config.MACs,
500 CompressionClientServer: supportedCompressions,
501 CompressionServerClient: supportedCompressions,
502 }
503 io.ReadFull(t.config.Rand, msg.Cookie[:])
504
505 // We mutate the KexAlgos slice, in order to add the kex-strict extension algorithm,
506 // and possibly to add the ext-info extension algorithm. Since the slice may be the
507 // user owned KeyExchanges, we create our own slice in order to avoid using user
508 // owned memory by mistake.
509 msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+2) // room for kex-strict and ext-info
510 msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...)
511
512 isServer := len(t.hostKeys) > 0
513 if isServer {
514 for _, k := range t.hostKeys {
515 // If k is a MultiAlgorithmSigner, we restrict the signature
516 // algorithms. If k is a AlgorithmSigner, presume it supports all
517 // signature algorithms associated with the key format. If k is not
518 // an AlgorithmSigner, we can only assume it only supports the
519 // algorithms that matches the key format. (This means that Sign
520 // can't pick a different default).
521 keyFormat := k.PublicKey().Type()
522
523 switch s := k.(type) {
524 case MultiAlgorithmSigner:
525 for _, algo := range algorithmsForKeyFormat(keyFormat) {
526 if contains(s.Algorithms(), underlyingAlgo(algo)) {
527 msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algo)
528 }
529 }
530 case AlgorithmSigner:
531 msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algorithmsForKeyFormat(keyFormat)...)
532 default:
533 msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, keyFormat)
534 }
535 }
536
537 if t.sessionID == nil {
538 msg.KexAlgos = append(msg.KexAlgos, kexStrictServer)
539 }
540 } else {
541 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
542
543 // As a client we opt in to receiving SSH_MSG_EXT_INFO so we know what
544 // algorithms the server supports for public key authentication. See RFC
545 // 8308, Section 2.1.
546 //
547 // We also send the strict KEX mode extension algorithm, in order to opt
548 // into the strict KEX mode.
549 if firstKeyExchange := t.sessionID == nil; firstKeyExchange {
550 msg.KexAlgos = append(msg.KexAlgos, "ext-info-c")
551 msg.KexAlgos = append(msg.KexAlgos, kexStrictClient)
552 }
553
554 }
555
556 packet := Marshal(msg)
557
558 // writePacket destroys the contents, so save a copy.
559 packetCopy := make([]byte, len(packet))
560 copy(packetCopy, packet)
561
562 if err := t.pushPacket(packetCopy); err != nil {
563 return err
564 }
565
566 t.sentInitMsg = msg
567 t.sentInitPacket = packet
568
569 return nil
570}
571
572var errSendBannerPhase = errors.New("ssh: SendAuthBanner outside of authentication phase")
573
574func (t *handshakeTransport) writePacket(p []byte) error {
575 t.mu.Lock()
576 defer t.mu.Unlock()
577
578 switch p[0] {
579 case msgKexInit:
580 return errors.New("ssh: only handshakeTransport can send kexInit")
581 case msgNewKeys:
582 return errors.New("ssh: only handshakeTransport can send newKeys")
583 case msgUserAuthBanner:
584 if t.userAuthComplete {
585 return errSendBannerPhase
586 }
587 case msgUserAuthSuccess:
588 t.userAuthComplete = true
589 }
590
591 if t.writeError != nil {
592 return t.writeError
593 }
594
595 if t.sentInitMsg != nil {
596 if len(t.pendingPackets) < maxPendingPackets {
597 // Copy the packet so the writer can reuse the buffer.
598 cp := make([]byte, len(p))
599 copy(cp, p)
600 t.pendingPackets = append(t.pendingPackets, cp)
601 return nil
602 }
603 for t.sentInitMsg != nil {
604 // Block and wait for KEX to complete or an error.
605 t.writeCond.Wait()
606 if t.writeError != nil {
607 return t.writeError
608 }
609 }
610 }
611
612 if t.writeBytesLeft > 0 {
613 t.writeBytesLeft -= int64(len(p))
614 } else {
615 t.requestKeyExchange()
616 }
617
618 if t.writePacketsLeft > 0 {
619 t.writePacketsLeft--
620 } else {
621 t.requestKeyExchange()
622 }
623
624 if err := t.pushPacket(p); err != nil {
625 t.writeError = err
626 t.writeCond.Broadcast()
627 }
628
629 return nil
630}
631
632func (t *handshakeTransport) Close() error {
633 // Close the connection. This should cause the readLoop goroutine to wake up
634 // and close t.startKex, which will shut down kexLoop if running.
635 err := t.conn.Close()
636
637 // Wait for the kexLoop goroutine to complete.
638 // At that point we know that the readLoop goroutine is complete too,
639 // because kexLoop itself waits for readLoop to close the startKex channel.
640 <-t.kexLoopDone
641
642 return err
643}
644
645func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
646 if debugHandshake {
647 log.Printf("%s entered key exchange", t.id())
648 }
649
650 otherInit := &kexInitMsg{}
651 if err := Unmarshal(otherInitPacket, otherInit); err != nil {
652 return err
653 }
654
655 magics := handshakeMagics{
656 clientVersion: t.clientVersion,
657 serverVersion: t.serverVersion,
658 clientKexInit: otherInitPacket,
659 serverKexInit: t.sentInitPacket,
660 }
661
662 clientInit := otherInit
663 serverInit := t.sentInitMsg
664 isClient := len(t.hostKeys) == 0
665 if isClient {
666 clientInit, serverInit = serverInit, clientInit
667
668 magics.clientKexInit = t.sentInitPacket
669 magics.serverKexInit = otherInitPacket
670 }
671
672 var err error
673 t.algorithms, err = findAgreedAlgorithms(isClient, clientInit, serverInit)
674 if err != nil {
675 return err
676 }
677
678 if t.sessionID == nil && ((isClient && contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && contains(clientInit.KexAlgos, kexStrictClient))) {
679 t.strictMode = true
680 if err := t.conn.setStrictMode(); err != nil {
681 return err
682 }
683 }
684
685 // We don't send FirstKexFollows, but we handle receiving it.
686 //
687 // RFC 4253 section 7 defines the kex and the agreement method for
688 // first_kex_packet_follows. It states that the guessed packet
689 // should be ignored if the "kex algorithm and/or the host
690 // key algorithm is guessed wrong (server and client have
691 // different preferred algorithm), or if any of the other
692 // algorithms cannot be agreed upon". The other algorithms have
693 // already been checked above so the kex algorithm and host key
694 // algorithm are checked here.
695 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
696 // other side sent a kex message for the wrong algorithm,
697 // which we have to ignore.
698 if _, err := t.conn.readPacket(); err != nil {
699 return err
700 }
701 }
702
703 kex, ok := kexAlgoMap[t.algorithms.kex]
704 if !ok {
705 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
706 }
707
708 var result *kexResult
709 if len(t.hostKeys) > 0 {
710 result, err = t.server(kex, &magics)
711 } else {
712 result, err = t.client(kex, &magics)
713 }
714
715 if err != nil {
716 return err
717 }
718
719 firstKeyExchange := t.sessionID == nil
720 if firstKeyExchange {
721 t.sessionID = result.H
722 }
723 result.SessionID = t.sessionID
724
725 if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil {
726 return err
727 }
728 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
729 return err
730 }
731
732 // On the server side, after the first SSH_MSG_NEWKEYS, send a SSH_MSG_EXT_INFO
733 // message with the server-sig-algs extension if the client supports it. See
734 // RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9.
735 if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") {
736 supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",")
737 extInfo := &extInfoMsg{
738 NumExtensions: 2,
739 Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)+4+16+4+1),
740 }
741 extInfo.Payload = appendInt(extInfo.Payload, len("server-sig-algs"))
742 extInfo.Payload = append(extInfo.Payload, "server-sig-algs"...)
743 extInfo.Payload = appendInt(extInfo.Payload, len(supportedPubKeyAuthAlgosList))
744 extInfo.Payload = append(extInfo.Payload, supportedPubKeyAuthAlgosList...)
745 extInfo.Payload = appendInt(extInfo.Payload, len("ping@openssh.com"))
746 extInfo.Payload = append(extInfo.Payload, "ping@openssh.com"...)
747 extInfo.Payload = appendInt(extInfo.Payload, 1)
748 extInfo.Payload = append(extInfo.Payload, "0"...)
749 if err := t.conn.writePacket(Marshal(extInfo)); err != nil {
750 return err
751 }
752 }
753
754 if packet, err := t.conn.readPacket(); err != nil {
755 return err
756 } else if packet[0] != msgNewKeys {
757 return unexpectedMessageError(msgNewKeys, packet[0])
758 }
759
760 if firstKeyExchange {
761 // Indicates to the transport that the first key exchange is completed
762 // after receiving SSH_MSG_NEWKEYS.
763 t.conn.setInitialKEXDone()
764 }
765
766 return nil
767}
768
769// algorithmSignerWrapper is an AlgorithmSigner that only supports the default
770// key format algorithm.
771//
772// This is technically a violation of the AlgorithmSigner interface, but it
773// should be unreachable given where we use this. Anyway, at least it returns an
774// error instead of panicing or producing an incorrect signature.
775type algorithmSignerWrapper struct {
776 Signer
777}
778
779func (a algorithmSignerWrapper) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
780 if algorithm != underlyingAlgo(a.PublicKey().Type()) {
781 return nil, errors.New("ssh: internal error: algorithmSignerWrapper invoked with non-default algorithm")
782 }
783 return a.Sign(rand, data)
784}
785
786func pickHostKey(hostKeys []Signer, algo string) AlgorithmSigner {
787 for _, k := range hostKeys {
788 if s, ok := k.(MultiAlgorithmSigner); ok {
789 if !contains(s.Algorithms(), underlyingAlgo(algo)) {
790 continue
791 }
792 }
793
794 if algo == k.PublicKey().Type() {
795 return algorithmSignerWrapper{k}
796 }
797
798 k, ok := k.(AlgorithmSigner)
799 if !ok {
800 continue
801 }
802 for _, a := range algorithmsForKeyFormat(k.PublicKey().Type()) {
803 if algo == a {
804 return k
805 }
806 }
807 }
808 return nil
809}
810
811func (t *handshakeTransport) server(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
812 hostKey := pickHostKey(t.hostKeys, t.algorithms.hostKey)
813 if hostKey == nil {
814 return nil, errors.New("ssh: internal error: negotiated unsupported signature type")
815 }
816
817 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey, t.algorithms.hostKey)
818 return r, err
819}
820
821func (t *handshakeTransport) client(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
822 result, err := kex.Client(t.conn, t.config.Rand, magics)
823 if err != nil {
824 return nil, err
825 }
826
827 hostKey, err := ParsePublicKey(result.HostKey)
828 if err != nil {
829 return nil, err
830 }
831
832 if err := verifyHostKeySignature(hostKey, t.algorithms.hostKey, result); err != nil {
833 return nil, err
834 }
835
836 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
837 if err != nil {
838 return nil, err
839 }
840
841 return result, nil
842}