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 HostKeyCallback
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),
110 t.resetReadThresholds()
111 t.resetWriteThresholds()
113 // We always start with a mandatory key exchange.
114 t.requestKex <- struct{}{}
118 func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
119 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
120 t.dialAddress = dialAddr
122 t.hostKeyCallback = config.HostKeyCallback
123 if config.HostKeyAlgorithms != nil {
124 t.hostKeyAlgorithms = config.HostKeyAlgorithms
126 t.hostKeyAlgorithms = supportedHostKeyAlgos
133 func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
134 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
135 t.hostKeys = config.hostKeys
141 func (t *handshakeTransport) getSessionID() []byte {
145 // waitSession waits for the session to be established. This should be
146 // the first thing to call after instantiating handshakeTransport.
147 func (t *handshakeTransport) waitSession() error {
148 p, err := t.readPacket()
152 if p[0] != msgNewKeys {
153 return fmt.Errorf("ssh: first packet should be msgNewKeys")
159 func (t *handshakeTransport) id() string {
160 if len(t.hostKeys) > 0 {
166 func (t *handshakeTransport) printPacket(p []byte, write bool) {
172 if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
173 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
175 msg, err := decode(p)
176 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
180 func (t *handshakeTransport) readPacket() ([]byte, error) {
181 p, ok := <-t.incoming
183 return nil, t.readError
188 func (t *handshakeTransport) readLoop() {
191 p, err := t.readOnePacket(first)
198 if p[0] == msgIgnore || p[0] == msgDebug {
205 t.recordWriteError(t.readError)
207 // Unblock the writer should it wait for this.
210 // Don't close t.requestKex; it's also written to from writePacket.
213 func (t *handshakeTransport) pushPacket(p []byte) error {
215 t.printPacket(p, true)
217 return t.conn.writePacket(p)
220 func (t *handshakeTransport) getWriteError() error {
226 func (t *handshakeTransport) recordWriteError(err error) {
229 if t.writeError == nil && err != nil {
234 func (t *handshakeTransport) requestKeyExchange() {
236 case t.requestKex <- struct{}{}:
238 // something already requested a kex, so do nothing.
242 func (t *handshakeTransport) resetWriteThresholds() {
243 t.writePacketsLeft = packetRekeyThreshold
244 if t.config.RekeyThreshold > 0 {
245 t.writeBytesLeft = int64(t.config.RekeyThreshold)
246 } else if t.algorithms != nil {
247 t.writeBytesLeft = t.algorithms.w.rekeyBytes()
249 t.writeBytesLeft = 1 << 30
253 func (t *handshakeTransport) kexLoop() {
256 for t.getWriteError() == nil {
257 var request *pendingKex
260 for request == nil || !sent {
263 case request, ok = <-t.startKex:
272 if err := t.sendKexInit(); err != nil {
273 t.recordWriteError(err)
280 if err := t.getWriteError(); err != nil {
287 // We're not servicing t.requestKex, but that is OK:
288 // we never block on sending to t.requestKex.
290 // We're not servicing t.startKex, but the remote end
291 // has just sent us a kexInitMsg, so it can't send
292 // another key change request, until we close the done
293 // channel on the pendingKex request.
295 err := t.enterKeyExchange(request.otherInit)
299 t.sentInitPacket = nil
302 t.resetWriteThresholds()
304 // we have completed the key exchange. Since the
305 // reader is still blocked, it is safe to clear out
306 // the requestKex channel. This avoids the situation
307 // where: 1) we consumed our own request for the
308 // initial kex, and 2) the kex from the remote side
309 // caused another send on the requestKex channel,
320 request.done <- t.writeError
322 // kex finished. Push packets that we received while
323 // the kex was in progress. Don't look at t.startKex
324 // and don't increment writtenSinceKex: if we trigger
325 // another kex while we are still busy with the last
326 // one, things will become very confusing.
327 for _, p := range t.pendingPackets {
328 t.writeError = t.pushPacket(p)
329 if t.writeError != nil {
333 t.pendingPackets = t.pendingPackets[:0]
337 // drain startKex channel. We don't service t.requestKex
338 // because nobody does blocking sends there.
340 for init := range t.startKex {
341 init.done <- t.writeError
349 // The protocol uses uint32 for packet counters, so we can't let them
350 // reach 1<<32. We will actually read and write more packets than
351 // this, though: the other side may send more packets, and after we
352 // hit this limit on writing we will send a few more packets for the
353 // key exchange itself.
354 const packetRekeyThreshold = (1 << 31)
356 func (t *handshakeTransport) resetReadThresholds() {
357 t.readPacketsLeft = packetRekeyThreshold
358 if t.config.RekeyThreshold > 0 {
359 t.readBytesLeft = int64(t.config.RekeyThreshold)
360 } else if t.algorithms != nil {
361 t.readBytesLeft = t.algorithms.r.rekeyBytes()
363 t.readBytesLeft = 1 << 30
367 func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
368 p, err := t.conn.readPacket()
373 if t.readPacketsLeft > 0 {
376 t.requestKeyExchange()
379 if t.readBytesLeft > 0 {
380 t.readBytesLeft -= int64(len(p))
382 t.requestKeyExchange()
386 t.printPacket(p, false)
389 if first && p[0] != msgKexInit {
390 return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
393 if p[0] != msgKexInit {
397 firstKex := t.sessionID == nil
400 done: make(chan error, 1),
407 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
414 t.resetReadThresholds()
416 // By default, a key exchange is hidden from higher layers by
417 // translating it into msgIgnore.
418 successPacket := []byte{msgIgnore}
420 // sendKexInit() for the first kex waits for
421 // msgNewKeys so the authentication process is
422 // guaranteed to happen over an encrypted transport.
423 successPacket = []byte{msgNewKeys}
426 return successPacket, nil
429 // sendKexInit sends a key change message.
430 func (t *handshakeTransport) sendKexInit() error {
433 if t.sentInitMsg != nil {
434 // kexInits may be sent either in response to the other side,
435 // or because our side wants to initiate a key change, so we
436 // may have already sent a kexInit. In that case, don't send a
442 KexAlgos: t.config.KeyExchanges,
443 CiphersClientServer: t.config.Ciphers,
444 CiphersServerClient: t.config.Ciphers,
445 MACsClientServer: t.config.MACs,
446 MACsServerClient: t.config.MACs,
447 CompressionClientServer: supportedCompressions,
448 CompressionServerClient: supportedCompressions,
450 io.ReadFull(rand.Reader, msg.Cookie[:])
452 if len(t.hostKeys) > 0 {
453 for _, k := range t.hostKeys {
454 msg.ServerHostKeyAlgos = append(
455 msg.ServerHostKeyAlgos, k.PublicKey().Type())
458 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
460 packet := Marshal(msg)
462 // writePacket destroys the contents, so save a copy.
463 packetCopy := make([]byte, len(packet))
464 copy(packetCopy, packet)
466 if err := t.pushPacket(packetCopy); err != nil {
471 t.sentInitPacket = packet
476 func (t *handshakeTransport) writePacket(p []byte) error {
479 return errors.New("ssh: only handshakeTransport can send kexInit")
481 return errors.New("ssh: only handshakeTransport can send newKeys")
486 if t.writeError != nil {
490 if t.sentInitMsg != nil {
491 // Copy the packet so the writer can reuse the buffer.
492 cp := make([]byte, len(p))
494 t.pendingPackets = append(t.pendingPackets, cp)
498 if t.writeBytesLeft > 0 {
499 t.writeBytesLeft -= int64(len(p))
501 t.requestKeyExchange()
504 if t.writePacketsLeft > 0 {
507 t.requestKeyExchange()
510 if err := t.pushPacket(p); err != nil {
517 func (t *handshakeTransport) Close() error {
518 return t.conn.Close()
521 func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
523 log.Printf("%s entered key exchange", t.id())
526 otherInit := &kexInitMsg{}
527 if err := Unmarshal(otherInitPacket, otherInit); err != nil {
531 magics := handshakeMagics{
532 clientVersion: t.clientVersion,
533 serverVersion: t.serverVersion,
534 clientKexInit: otherInitPacket,
535 serverKexInit: t.sentInitPacket,
538 clientInit := otherInit
539 serverInit := t.sentInitMsg
540 if len(t.hostKeys) == 0 {
541 clientInit, serverInit = serverInit, clientInit
543 magics.clientKexInit = t.sentInitPacket
544 magics.serverKexInit = otherInitPacket
548 t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit)
553 // We don't send FirstKexFollows, but we handle receiving it.
555 // RFC 4253 section 7 defines the kex and the agreement method for
556 // first_kex_packet_follows. It states that the guessed packet
557 // should be ignored if the "kex algorithm and/or the host
558 // key algorithm is guessed wrong (server and client have
559 // different preferred algorithm), or if any of the other
560 // algorithms cannot be agreed upon". The other algorithms have
561 // already been checked above so the kex algorithm and host key
562 // algorithm are checked here.
563 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
564 // other side sent a kex message for the wrong algorithm,
565 // which we have to ignore.
566 if _, err := t.conn.readPacket(); err != nil {
571 kex, ok := kexAlgoMap[t.algorithms.kex]
573 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
576 var result *kexResult
577 if len(t.hostKeys) > 0 {
578 result, err = t.server(kex, t.algorithms, &magics)
580 result, err = t.client(kex, t.algorithms, &magics)
587 if t.sessionID == nil {
588 t.sessionID = result.H
590 result.SessionID = t.sessionID
592 if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil {
595 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
598 if packet, err := t.conn.readPacket(); err != nil {
600 } else if packet[0] != msgNewKeys {
601 return unexpectedMessageError(msgNewKeys, packet[0])
607 func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
609 for _, k := range t.hostKeys {
610 if algs.hostKey == k.PublicKey().Type() {
615 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
619 func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
620 result, err := kex.Client(t.conn, t.config.Rand, magics)
625 hostKey, err := ParsePublicKey(result.HostKey)
630 if err := verifyHostKeySignature(hostKey, result); err != nil {
634 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)