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 // bannerCallback is non-empty if we are the client and it has been set in
82 // ClientConfig. In that case it is called during the user authentication
83 // dance to handle a custom server's message.
84 bannerCallback BannerCallback
86 // Algorithms agreed in the last key exchange.
87 algorithms *algorithms
89 readPacketsLeft uint32
92 writePacketsLeft uint32
95 // The session ID or nil if first kex did not complete yet.
99 type pendingKex struct {
104 func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
105 t := &handshakeTransport{
107 serverVersion: serverVersion,
108 clientVersion: clientVersion,
109 incoming: make(chan []byte, chanSize),
110 requestKex: make(chan struct{}, 1),
111 startKex: make(chan *pendingKex, 1),
115 t.resetReadThresholds()
116 t.resetWriteThresholds()
118 // We always start with a mandatory key exchange.
119 t.requestKex <- struct{}{}
123 func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
124 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
125 t.dialAddress = dialAddr
127 t.hostKeyCallback = config.HostKeyCallback
128 t.bannerCallback = config.BannerCallback
129 if config.HostKeyAlgorithms != nil {
130 t.hostKeyAlgorithms = config.HostKeyAlgorithms
132 t.hostKeyAlgorithms = supportedHostKeyAlgos
139 func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
140 t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
141 t.hostKeys = config.hostKeys
147 func (t *handshakeTransport) getSessionID() []byte {
151 // waitSession waits for the session to be established. This should be
152 // the first thing to call after instantiating handshakeTransport.
153 func (t *handshakeTransport) waitSession() error {
154 p, err := t.readPacket()
158 if p[0] != msgNewKeys {
159 return fmt.Errorf("ssh: first packet should be msgNewKeys")
165 func (t *handshakeTransport) id() string {
166 if len(t.hostKeys) > 0 {
172 func (t *handshakeTransport) printPacket(p []byte, write bool) {
178 if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
179 log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
181 msg, err := decode(p)
182 log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
186 func (t *handshakeTransport) readPacket() ([]byte, error) {
187 p, ok := <-t.incoming
189 return nil, t.readError
194 func (t *handshakeTransport) readLoop() {
197 p, err := t.readOnePacket(first)
204 if p[0] == msgIgnore || p[0] == msgDebug {
211 t.recordWriteError(t.readError)
213 // Unblock the writer should it wait for this.
216 // Don't close t.requestKex; it's also written to from writePacket.
219 func (t *handshakeTransport) pushPacket(p []byte) error {
221 t.printPacket(p, true)
223 return t.conn.writePacket(p)
226 func (t *handshakeTransport) getWriteError() error {
232 func (t *handshakeTransport) recordWriteError(err error) {
235 if t.writeError == nil && err != nil {
240 func (t *handshakeTransport) requestKeyExchange() {
242 case t.requestKex <- struct{}{}:
244 // something already requested a kex, so do nothing.
248 func (t *handshakeTransport) resetWriteThresholds() {
249 t.writePacketsLeft = packetRekeyThreshold
250 if t.config.RekeyThreshold > 0 {
251 t.writeBytesLeft = int64(t.config.RekeyThreshold)
252 } else if t.algorithms != nil {
253 t.writeBytesLeft = t.algorithms.w.rekeyBytes()
255 t.writeBytesLeft = 1 << 30
259 func (t *handshakeTransport) kexLoop() {
262 for t.getWriteError() == nil {
263 var request *pendingKex
266 for request == nil || !sent {
269 case request, ok = <-t.startKex:
278 if err := t.sendKexInit(); err != nil {
279 t.recordWriteError(err)
286 if err := t.getWriteError(); err != nil {
293 // We're not servicing t.requestKex, but that is OK:
294 // we never block on sending to t.requestKex.
296 // We're not servicing t.startKex, but the remote end
297 // has just sent us a kexInitMsg, so it can't send
298 // another key change request, until we close the done
299 // channel on the pendingKex request.
301 err := t.enterKeyExchange(request.otherInit)
305 t.sentInitPacket = nil
308 t.resetWriteThresholds()
310 // we have completed the key exchange. Since the
311 // reader is still blocked, it is safe to clear out
312 // the requestKex channel. This avoids the situation
313 // where: 1) we consumed our own request for the
314 // initial kex, and 2) the kex from the remote side
315 // caused another send on the requestKex channel,
326 request.done <- t.writeError
328 // kex finished. Push packets that we received while
329 // the kex was in progress. Don't look at t.startKex
330 // and don't increment writtenSinceKex: if we trigger
331 // another kex while we are still busy with the last
332 // one, things will become very confusing.
333 for _, p := range t.pendingPackets {
334 t.writeError = t.pushPacket(p)
335 if t.writeError != nil {
339 t.pendingPackets = t.pendingPackets[:0]
343 // drain startKex channel. We don't service t.requestKex
344 // because nobody does blocking sends there.
346 for init := range t.startKex {
347 init.done <- t.writeError
355 // The protocol uses uint32 for packet counters, so we can't let them
356 // reach 1<<32. We will actually read and write more packets than
357 // this, though: the other side may send more packets, and after we
358 // hit this limit on writing we will send a few more packets for the
359 // key exchange itself.
360 const packetRekeyThreshold = (1 << 31)
362 func (t *handshakeTransport) resetReadThresholds() {
363 t.readPacketsLeft = packetRekeyThreshold
364 if t.config.RekeyThreshold > 0 {
365 t.readBytesLeft = int64(t.config.RekeyThreshold)
366 } else if t.algorithms != nil {
367 t.readBytesLeft = t.algorithms.r.rekeyBytes()
369 t.readBytesLeft = 1 << 30
373 func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
374 p, err := t.conn.readPacket()
379 if t.readPacketsLeft > 0 {
382 t.requestKeyExchange()
385 if t.readBytesLeft > 0 {
386 t.readBytesLeft -= int64(len(p))
388 t.requestKeyExchange()
392 t.printPacket(p, false)
395 if first && p[0] != msgKexInit {
396 return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
399 if p[0] != msgKexInit {
403 firstKex := t.sessionID == nil
406 done: make(chan error, 1),
413 log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
420 t.resetReadThresholds()
422 // By default, a key exchange is hidden from higher layers by
423 // translating it into msgIgnore.
424 successPacket := []byte{msgIgnore}
426 // sendKexInit() for the first kex waits for
427 // msgNewKeys so the authentication process is
428 // guaranteed to happen over an encrypted transport.
429 successPacket = []byte{msgNewKeys}
432 return successPacket, nil
435 // sendKexInit sends a key change message.
436 func (t *handshakeTransport) sendKexInit() error {
439 if t.sentInitMsg != nil {
440 // kexInits may be sent either in response to the other side,
441 // or because our side wants to initiate a key change, so we
442 // may have already sent a kexInit. In that case, don't send a
448 KexAlgos: t.config.KeyExchanges,
449 CiphersClientServer: t.config.Ciphers,
450 CiphersServerClient: t.config.Ciphers,
451 MACsClientServer: t.config.MACs,
452 MACsServerClient: t.config.MACs,
453 CompressionClientServer: supportedCompressions,
454 CompressionServerClient: supportedCompressions,
456 io.ReadFull(rand.Reader, msg.Cookie[:])
458 if len(t.hostKeys) > 0 {
459 for _, k := range t.hostKeys {
460 msg.ServerHostKeyAlgos = append(
461 msg.ServerHostKeyAlgos, k.PublicKey().Type())
464 msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
466 packet := Marshal(msg)
468 // writePacket destroys the contents, so save a copy.
469 packetCopy := make([]byte, len(packet))
470 copy(packetCopy, packet)
472 if err := t.pushPacket(packetCopy); err != nil {
477 t.sentInitPacket = packet
482 func (t *handshakeTransport) writePacket(p []byte) error {
485 return errors.New("ssh: only handshakeTransport can send kexInit")
487 return errors.New("ssh: only handshakeTransport can send newKeys")
492 if t.writeError != nil {
496 if t.sentInitMsg != nil {
497 // Copy the packet so the writer can reuse the buffer.
498 cp := make([]byte, len(p))
500 t.pendingPackets = append(t.pendingPackets, cp)
504 if t.writeBytesLeft > 0 {
505 t.writeBytesLeft -= int64(len(p))
507 t.requestKeyExchange()
510 if t.writePacketsLeft > 0 {
513 t.requestKeyExchange()
516 if err := t.pushPacket(p); err != nil {
523 func (t *handshakeTransport) Close() error {
524 return t.conn.Close()
527 func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
529 log.Printf("%s entered key exchange", t.id())
532 otherInit := &kexInitMsg{}
533 if err := Unmarshal(otherInitPacket, otherInit); err != nil {
537 magics := handshakeMagics{
538 clientVersion: t.clientVersion,
539 serverVersion: t.serverVersion,
540 clientKexInit: otherInitPacket,
541 serverKexInit: t.sentInitPacket,
544 clientInit := otherInit
545 serverInit := t.sentInitMsg
546 if len(t.hostKeys) == 0 {
547 clientInit, serverInit = serverInit, clientInit
549 magics.clientKexInit = t.sentInitPacket
550 magics.serverKexInit = otherInitPacket
554 t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit)
559 // We don't send FirstKexFollows, but we handle receiving it.
561 // RFC 4253 section 7 defines the kex and the agreement method for
562 // first_kex_packet_follows. It states that the guessed packet
563 // should be ignored if the "kex algorithm and/or the host
564 // key algorithm is guessed wrong (server and client have
565 // different preferred algorithm), or if any of the other
566 // algorithms cannot be agreed upon". The other algorithms have
567 // already been checked above so the kex algorithm and host key
568 // algorithm are checked here.
569 if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
570 // other side sent a kex message for the wrong algorithm,
571 // which we have to ignore.
572 if _, err := t.conn.readPacket(); err != nil {
577 kex, ok := kexAlgoMap[t.algorithms.kex]
579 return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
582 var result *kexResult
583 if len(t.hostKeys) > 0 {
584 result, err = t.server(kex, t.algorithms, &magics)
586 result, err = t.client(kex, t.algorithms, &magics)
593 if t.sessionID == nil {
594 t.sessionID = result.H
596 result.SessionID = t.sessionID
598 if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil {
601 if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
604 if packet, err := t.conn.readPacket(); err != nil {
606 } else if packet[0] != msgNewKeys {
607 return unexpectedMessageError(msgNewKeys, packet[0])
613 func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
615 for _, k := range t.hostKeys {
616 if algs.hostKey == k.PublicKey().Type() {
621 r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
625 func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
626 result, err := kex.Client(t.conn, t.config.Rand, magics)
631 hostKey, err := ParsePublicKey(result.HostKey)
636 if err := verifyHostKeySignature(hostKey, result); err != nil {
640 err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)