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.
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.
20 const debugHandshake = false
22 // chanSize sets the amount of buffering SSH connections. This is
23 // primarily for testing: setting chanSize=0 uncovers deadlocks more
27 // keyingTransport is a packet based transport that supports key
28 // changes. It need not be thread-safe. It should pass through
29 // msgNewKeys in both directions.
30 type keyingTransport interface {
33 // prepareKeyChange sets up a key change. The key change for a
34 // direction will be effected if a msgNewKeys message is sent
36 prepareKeyChange(*algorithms, *kexResult) error
39 // handshakeTransport implements rekeying on top of a keyingTransport
40 // and offers a thread-safe writePacket() interface.
41 type handshakeTransport struct {
48 // hostKeys is non-empty if we are the server. In that case,
49 // it contains all host keys that can be used to sign the
53 // hostKeyAlgorithms is non-empty if we are the client. In that case,
54 // we accept these key types from the server as host key.
55 hostKeyAlgorithms []string
57 // On read error, incoming is closed, and readError is set.
64 sentInitMsg *kexInitMsg
65 pendingPackets [][]byte // Used when a key exchange is in progress.
67 // If the read loop wants to schedule a kex, it pings this
68 // channel, and the write loop will send out a kex
70 requestKex chan struct{}
72 // If the other side requests or confirms a kex, its kexInit
73 // packet is sent here for the write loop to find it.
74 startKex chan *pendingKex
76 // data for host key checking
77 hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
81 // Algorithms agreed in the last key exchange.
82 algorithms *algorithms
84 readPacketsLeft uint32
87 writePacketsLeft uint32
90 // The session ID or nil if first kex did not complete yet.
94 type pendingKex struct {
99 func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
100 t := &handshakeTransport{
102 serverVersion: serverVersion,
103 clientVersion: clientVersion,
104 incoming: make(chan []byte, chanSize),
105 requestKex: make(chan struct{}, 1),
106 startKex: make(chan *pendingKex, 1),
111 // We always start with a mandatory key exchange.
112 t.requestKex <- struct{}{}
116 func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
117 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
118 t.dialAddress = dialAddr
120 t.hostKeyCallback = config.HostKeyCallback
121 if config.HostKeyAlgorithms != nil {
122 t.hostKeyAlgorithms = config.HostKeyAlgorithms
124 t.hostKeyAlgorithms = supportedHostKeyAlgos
131 func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
132 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
133 t.hostKeys = config.hostKeys
139 func (t *handshakeTransport) getSessionID() []byte {
143 // waitSession waits for the session to be established. This should be
144 // the first thing to call after instantiating handshakeTransport.
145 func (t *handshakeTransport) waitSession() error {
146 p, err := t.readPacket()
150 if p[0] != msgNewKeys {
151 return fmt.Errorf("ssh: first packet should be msgNewKeys")
157 func (t *handshakeTransport) id() string {
158 if len(t.hostKeys) > 0 {
164 func (t *handshakeTransport) printPacket(p []byte, write bool) {
170 if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
171 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
173 msg, err := decode(p)
174 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
178 func (t *handshakeTransport) readPacket() ([]byte, error) {
179 p, ok := <-t.incoming
181 return nil, t.readError
186 func (t *handshakeTransport) readLoop() {
189 p, err := t.readOnePacket(first)
196 if p[0] == msgIgnore || p[0] == msgDebug {
203 t.recordWriteError(t.readError)
205 // Unblock the writer should it wait for this.
208 // Don't close t.requestKex; it's also written to from writePacket.
211 func (t *handshakeTransport) pushPacket(p []byte) error {
213 t.printPacket(p, true)
215 return t.conn.writePacket(p)
218 func (t *handshakeTransport) getWriteError() error {
224 func (t *handshakeTransport) recordWriteError(err error) {
227 if t.writeError == nil && err != nil {
232 func (t *handshakeTransport) requestKeyExchange() {
234 case t.requestKex <- struct{}{}:
236 // something already requested a kex, so do nothing.
240 func (t *handshakeTransport) kexLoop() {
243 for t.getWriteError() == nil {
244 var request *pendingKex
247 for request == nil || !sent {
250 case request, ok = <-t.startKex:
259 if err := t.sendKexInit(); err != nil {
260 t.recordWriteError(err)
267 if err := t.getWriteError(); err != nil {
274 // We're not servicing t.requestKex, but that is OK:
275 // we never block on sending to t.requestKex.
277 // We're not servicing t.startKex, but the remote end
278 // has just sent us a kexInitMsg, so it can't send
279 // another key change request, until we close the done
280 // channel on the pendingKex request.
282 err := t.enterKeyExchange(request.otherInit)
286 t.sentInitPacket = nil
288 t.writePacketsLeft = packetRekeyThreshold
289 if t.config.RekeyThreshold > 0 {
290 t.writeBytesLeft = int64(t.config.RekeyThreshold)
291 } else if t.algorithms != nil {
292 t.writeBytesLeft = t.algorithms.w.rekeyBytes()
295 // we have completed the key exchange. Since the
296 // reader is still blocked, it is safe to clear out
297 // the requestKex channel. This avoids the situation
298 // where: 1) we consumed our own request for the
299 // initial kex, and 2) the kex from the remote side
300 // caused another send on the requestKex channel,
311 request.done <- t.writeError
313 // kex finished. Push packets that we received while
314 // the kex was in progress. Don't look at t.startKex
315 // and don't increment writtenSinceKex: if we trigger
316 // another kex while we are still busy with the last
317 // one, things will become very confusing.
318 for _, p := range t.pendingPackets {
319 t.writeError = t.pushPacket(p)
320 if t.writeError != nil {
324 t.pendingPackets = t.pendingPackets[:0]
328 // drain startKex channel. We don't service t.requestKex
329 // because nobody does blocking sends there.
331 for init := range t.startKex {
332 init.done <- t.writeError
340 // The protocol uses uint32 for packet counters, so we can't let them
341 // reach 1<<32. We will actually read and write more packets than
342 // this, though: the other side may send more packets, and after we
343 // hit this limit on writing we will send a few more packets for the
344 // key exchange itself.
345 const packetRekeyThreshold = (1 << 31)
347 func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
348 p, err := t.conn.readPacket()
353 if t.readPacketsLeft > 0 {
356 t.requestKeyExchange()
359 if t.readBytesLeft > 0 {
360 t.readBytesLeft -= int64(len(p))
362 t.requestKeyExchange()
366 t.printPacket(p, false)
369 if first && p[0] != msgKexInit {
370 return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
373 if p[0] != msgKexInit {
377 firstKex := t.sessionID == nil
380 done: make(chan error, 1),
387 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
394 t.readPacketsLeft = packetRekeyThreshold
395 if t.config.RekeyThreshold > 0 {
396 t.readBytesLeft = int64(t.config.RekeyThreshold)
398 t.readBytesLeft = t.algorithms.r.rekeyBytes()
401 // By default, a key exchange is hidden from higher layers by
402 // translating it into msgIgnore.
403 successPacket := []byte{msgIgnore}
405 // sendKexInit() for the first kex waits for
406 // msgNewKeys so the authentication process is
407 // guaranteed to happen over an encrypted transport.
408 successPacket = []byte{msgNewKeys}
411 return successPacket, nil
414 // sendKexInit sends a key change message.
415 func (t *handshakeTransport) sendKexInit() error {
418 if t.sentInitMsg != nil {
419 // kexInits may be sent either in response to the other side,
420 // or because our side wants to initiate a key change, so we
421 // may have already sent a kexInit. In that case, don't send a
427 KexAlgos: t.config.KeyExchanges,
428 CiphersClientServer: t.config.Ciphers,
429 CiphersServerClient: t.config.Ciphers,
430 MACsClientServer: t.config.MACs,
431 MACsServerClient: t.config.MACs,
432 CompressionClientServer: supportedCompressions,
433 CompressionServerClient: supportedCompressions,
435 io.ReadFull(rand.Reader, msg.Cookie[:])
437 if len(t.hostKeys) > 0 {
438 for _, k := range t.hostKeys {
439 msg.ServerHostKeyAlgos = append(
440 msg.ServerHostKeyAlgos, k.PublicKey().Type())
443 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
445 packet := Marshal(msg)
447 // writePacket destroys the contents, so save a copy.
448 packetCopy := make([]byte, len(packet))
449 copy(packetCopy, packet)
451 if err := t.pushPacket(packetCopy); err != nil {
456 t.sentInitPacket = packet
461 func (t *handshakeTransport) writePacket(p []byte) error {
464 return errors.New("ssh: only handshakeTransport can send kexInit")
466 return errors.New("ssh: only handshakeTransport can send newKeys")
471 if t.writeError != nil {
475 if t.sentInitMsg != nil {
476 // Copy the packet so the writer can reuse the buffer.
477 cp := make([]byte, len(p))
479 t.pendingPackets = append(t.pendingPackets, cp)
483 if t.writeBytesLeft > 0 {
484 t.writeBytesLeft -= int64(len(p))
486 t.requestKeyExchange()
489 if t.writePacketsLeft > 0 {
492 t.requestKeyExchange()
495 if err := t.pushPacket(p); err != nil {
502 func (t *handshakeTransport) Close() error {
503 return t.conn.Close()
506 func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
508 log.Printf("%s entered key exchange", t.id())
511 otherInit := &kexInitMsg{}
512 if err := Unmarshal(otherInitPacket, otherInit); err != nil {
516 magics := handshakeMagics{
517 clientVersion: t.clientVersion,
518 serverVersion: t.serverVersion,
519 clientKexInit: otherInitPacket,
520 serverKexInit: t.sentInitPacket,
523 clientInit := otherInit
524 serverInit := t.sentInitMsg
525 if len(t.hostKeys) == 0 {
526 clientInit, serverInit = serverInit, clientInit
528 magics.clientKexInit = t.sentInitPacket
529 magics.serverKexInit = otherInitPacket
533 t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit)
538 // We don't send FirstKexFollows, but we handle receiving it.
540 // RFC 4253 section 7 defines the kex and the agreement method for
541 // first_kex_packet_follows. It states that the guessed packet
542 // should be ignored if the "kex algorithm and/or the host
543 // key algorithm is guessed wrong (server and client have
544 // different preferred algorithm), or if any of the other
545 // algorithms cannot be agreed upon". The other algorithms have
546 // already been checked above so the kex algorithm and host key
547 // algorithm are checked here.
548 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
549 // other side sent a kex message for the wrong algorithm,
550 // which we have to ignore.
551 if _, err := t.conn.readPacket(); err != nil {
556 kex, ok := kexAlgoMap[t.algorithms.kex]
558 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
561 var result *kexResult
562 if len(t.hostKeys) > 0 {
563 result, err = t.server(kex, t.algorithms, &magics)
565 result, err = t.client(kex, t.algorithms, &magics)
572 if t.sessionID == nil {
573 t.sessionID = result.H
575 result.SessionID = t.sessionID
577 t.conn.prepareKeyChange(t.algorithms, result)
578 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
581 if packet, err := t.conn.readPacket(); err != nil {
583 } else if packet[0] != msgNewKeys {
584 return unexpectedMessageError(msgNewKeys, packet[0])
590 func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
592 for _, k := range t.hostKeys {
593 if algs.hostKey == k.PublicKey().Type() {
598 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
602 func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
603 result, err := kex.Client(t.conn, t.config.Rand, magics)
608 hostKey, err := ParsePublicKey(result.HostKey)
613 if err := verifyHostKeySignature(hostKey, result); err != nil {
617 if t.hostKeyCallback != nil {
618 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)