handshake.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. package ssh
  5. import (
  6. "crypto/rand"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "sync"
  13. )
  14. // debugHandshake, if set, prints messages sent and received. Key
  15. // exchange messages are printed as if DH were used, so the debug
  16. // messages are wrong when using ECDH.
  17. const debugHandshake = false
  18. // chanSize sets the amount of buffering SSH connections. This is
  19. // primarily for testing: setting chanSize=0 uncovers deadlocks more
  20. // quickly.
  21. const chanSize = 16
  22. // keyingTransport is a packet based transport that supports key
  23. // changes. It need not be thread-safe. It should pass through
  24. // msgNewKeys in both directions.
  25. type keyingTransport interface {
  26. packetConn
  27. // prepareKeyChange sets up a key change. The key change for a
  28. // direction will be effected if a msgNewKeys message is sent
  29. // or received.
  30. prepareKeyChange(*algorithms, *kexResult) error
  31. }
  32. // handshakeTransport implements rekeying on top of a keyingTransport
  33. // and offers a thread-safe writePacket() interface.
  34. type handshakeTransport struct {
  35. conn keyingTransport
  36. config *Config
  37. serverVersion []byte
  38. clientVersion []byte
  39. // hostKeys is non-empty if we are the server. In that case,
  40. // it contains all host keys that can be used to sign the
  41. // connection.
  42. hostKeys []Signer
  43. // hostKeyAlgorithms is non-empty if we are the client. In that case,
  44. // we accept these key types from the server as host key.
  45. hostKeyAlgorithms []string
  46. // On read error, incoming is closed, and readError is set.
  47. incoming chan []byte
  48. readError error
  49. mu sync.Mutex
  50. writeError error
  51. sentInitPacket []byte
  52. sentInitMsg *kexInitMsg
  53. pendingPackets [][]byte // Used when a key exchange is in progress.
  54. // If the read loop wants to schedule a kex, it pings this
  55. // channel, and the write loop will send out a kex
  56. // message. The boolean is whether this is the first request or not.
  57. requestKex chan bool
  58. // If the other side requests or confirms a kex, its kexInit
  59. // packet is sent here for the write loop to find it.
  60. startKex chan *pendingKex
  61. // data for host key checking
  62. hostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error
  63. dialAddress string
  64. remoteAddr net.Addr
  65. // Algorithms agreed in the last key exchange.
  66. algorithms *algorithms
  67. readPacketsLeft uint32
  68. readBytesLeft int64
  69. writePacketsLeft uint32
  70. writeBytesLeft int64
  71. // The session ID or nil if first kex did not complete yet.
  72. sessionID []byte
  73. }
  74. type pendingKex struct {
  75. otherInit []byte
  76. done chan error
  77. }
  78. func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
  79. t := &handshakeTransport{
  80. conn: conn,
  81. serverVersion: serverVersion,
  82. clientVersion: clientVersion,
  83. incoming: make(chan []byte, chanSize),
  84. requestKex: make(chan bool, 1),
  85. startKex: make(chan *pendingKex, 1),
  86. config: config,
  87. }
  88. // We always start with a mandatory key exchange.
  89. t.requestKex <- true
  90. return t
  91. }
  92. func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
  93. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  94. t.dialAddress = dialAddr
  95. t.remoteAddr = addr
  96. t.hostKeyCallback = config.HostKeyCallback
  97. if config.HostKeyAlgorithms != nil {
  98. t.hostKeyAlgorithms = config.HostKeyAlgorithms
  99. } else {
  100. t.hostKeyAlgorithms = supportedHostKeyAlgos
  101. }
  102. go t.readLoop()
  103. go t.kexLoop()
  104. return t
  105. }
  106. func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
  107. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  108. t.hostKeys = config.hostKeys
  109. go t.readLoop()
  110. go t.kexLoop()
  111. return t
  112. }
  113. func (t *handshakeTransport) getSessionID() []byte {
  114. return t.sessionID
  115. }
  116. // waitSession waits for the session to be established. This should be
  117. // the first thing to call after instantiating handshakeTransport.
  118. func (t *handshakeTransport) waitSession() error {
  119. p, err := t.readPacket()
  120. if err != nil {
  121. return err
  122. }
  123. if p[0] != msgNewKeys {
  124. return fmt.Errorf("ssh: first packet should be msgNewKeys")
  125. }
  126. return nil
  127. }
  128. func (t *handshakeTransport) id() string {
  129. if len(t.hostKeys) > 0 {
  130. return "server"
  131. }
  132. return "client"
  133. }
  134. func (t *handshakeTransport) printPacket(p []byte, write bool) {
  135. action := "got"
  136. if write {
  137. action = "sent"
  138. }
  139. if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
  140. log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
  141. } else {
  142. msg, err := decode(p)
  143. log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
  144. }
  145. }
  146. func (t *handshakeTransport) readPacket() ([]byte, error) {
  147. p, ok := <-t.incoming
  148. if !ok {
  149. return nil, t.readError
  150. }
  151. return p, nil
  152. }
  153. func (t *handshakeTransport) readLoop() {
  154. first := true
  155. for {
  156. p, err := t.readOnePacket(first)
  157. first = false
  158. if err != nil {
  159. t.readError = err
  160. close(t.incoming)
  161. break
  162. }
  163. if p[0] == msgIgnore || p[0] == msgDebug {
  164. continue
  165. }
  166. t.incoming <- p
  167. }
  168. // Stop writers too.
  169. t.recordWriteError(t.readError)
  170. // Unblock the writer should it wait for this.
  171. close(t.startKex)
  172. // Don't close t.requestKex; it's also written to from writePacket.
  173. }
  174. func (t *handshakeTransport) pushPacket(p []byte) error {
  175. if debugHandshake {
  176. t.printPacket(p, true)
  177. }
  178. return t.conn.writePacket(p)
  179. }
  180. func (t *handshakeTransport) getWriteError() error {
  181. t.mu.Lock()
  182. defer t.mu.Unlock()
  183. return t.writeError
  184. }
  185. func (t *handshakeTransport) recordWriteError(err error) {
  186. t.mu.Lock()
  187. defer t.mu.Unlock()
  188. if t.writeError == nil && err != nil {
  189. t.writeError = err
  190. }
  191. }
  192. func (t *handshakeTransport) requestKeyExchange() {
  193. select {
  194. case t.requestKex <- false:
  195. default:
  196. // something already requested a kex, so do nothing.
  197. }
  198. }
  199. func (t *handshakeTransport) kexLoop() {
  200. firstSent := false
  201. write:
  202. for t.getWriteError() == nil {
  203. var request *pendingKex
  204. var sent bool
  205. for request == nil || !sent {
  206. var ok bool
  207. select {
  208. case request, ok = <-t.startKex:
  209. if !ok {
  210. break write
  211. }
  212. case requestFirst := <-t.requestKex:
  213. // For the first key exchange, both
  214. // sides will initiate a key exchange,
  215. // and both channels will fire. To
  216. // avoid doing two key exchanges in a
  217. // row, ignore our own request for an
  218. // initial kex if we have already sent
  219. // it out.
  220. if firstSent && requestFirst {
  221. continue
  222. }
  223. }
  224. if !sent {
  225. if err := t.sendKexInit(); err != nil {
  226. t.recordWriteError(err)
  227. break
  228. }
  229. firstSent = true
  230. sent = true
  231. }
  232. }
  233. if err := t.getWriteError(); err != nil {
  234. if request != nil {
  235. request.done <- err
  236. }
  237. break
  238. }
  239. // We're not servicing t.requestKex, but that is OK:
  240. // we never block on sending to t.requestKex.
  241. // We're not servicing t.startKex, but the remote end
  242. // has just sent us a kexInitMsg, so it can't send
  243. // another key change request.
  244. err := t.enterKeyExchange(request.otherInit)
  245. t.mu.Lock()
  246. t.writeError = err
  247. t.sentInitPacket = nil
  248. t.sentInitMsg = nil
  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()
  254. }
  255. request.done <- t.writeError
  256. // kex finished. Push packets that we received while
  257. // the kex was in progress. Don't look at t.startKex
  258. // and don't increment writtenSinceKex: if we trigger
  259. // another kex while we are still busy with the last
  260. // one, things will become very confusing.
  261. for _, p := range t.pendingPackets {
  262. t.writeError = t.pushPacket(p)
  263. if t.writeError != nil {
  264. break
  265. }
  266. }
  267. t.pendingPackets = t.pendingPackets[0:]
  268. t.mu.Unlock()
  269. }
  270. // drain startKex channel. We don't service t.requestKex
  271. // because nobody does blocking sends there.
  272. go func() {
  273. for init := range t.startKex {
  274. init.done <- t.writeError
  275. }
  276. }()
  277. // Unblock reader.
  278. t.conn.Close()
  279. }
  280. // The protocol uses uint32 for packet counters, so we can't let them
  281. // reach 1<<32. We will actually read and write more packets than
  282. // this, though: the other side may send more packets, and after we
  283. // hit this limit on writing we will send a few more packets for the
  284. // key exchange itself.
  285. const packetRekeyThreshold = (1 << 31)
  286. func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
  287. p, err := t.conn.readPacket()
  288. if err != nil {
  289. return nil, err
  290. }
  291. if t.readPacketsLeft > 0 {
  292. t.readPacketsLeft--
  293. } else {
  294. t.requestKeyExchange()
  295. }
  296. if t.readBytesLeft > 0 {
  297. t.readBytesLeft -= int64(len(p))
  298. } else {
  299. t.requestKeyExchange()
  300. }
  301. if debugHandshake {
  302. t.printPacket(p, false)
  303. }
  304. if first && p[0] != msgKexInit {
  305. return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
  306. }
  307. if p[0] != msgKexInit {
  308. return p, nil
  309. }
  310. firstKex := t.sessionID == nil
  311. kex := pendingKex{
  312. done: make(chan error, 1),
  313. otherInit: p,
  314. }
  315. t.startKex <- &kex
  316. err = <-kex.done
  317. if debugHandshake {
  318. log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
  319. }
  320. if err != nil {
  321. return nil, err
  322. }
  323. t.readPacketsLeft = packetRekeyThreshold
  324. if t.config.RekeyThreshold > 0 {
  325. t.readBytesLeft = int64(t.config.RekeyThreshold)
  326. } else {
  327. t.readBytesLeft = t.algorithms.r.rekeyBytes()
  328. }
  329. // By default, a key exchange is hidden from higher layers by
  330. // translating it into msgIgnore.
  331. successPacket := []byte{msgIgnore}
  332. if firstKex {
  333. // sendKexInit() for the first kex waits for
  334. // msgNewKeys so the authentication process is
  335. // guaranteed to happen over an encrypted transport.
  336. successPacket = []byte{msgNewKeys}
  337. }
  338. return successPacket, nil
  339. }
  340. // sendKexInit sends a key change message.
  341. func (t *handshakeTransport) sendKexInit() error {
  342. t.mu.Lock()
  343. defer t.mu.Unlock()
  344. if t.sentInitMsg != nil {
  345. // kexInits may be sent either in response to the other side,
  346. // or because our side wants to initiate a key change, so we
  347. // may have already sent a kexInit. In that case, don't send a
  348. // second kexInit.
  349. return nil
  350. }
  351. msg := &kexInitMsg{
  352. KexAlgos: t.config.KeyExchanges,
  353. CiphersClientServer: t.config.Ciphers,
  354. CiphersServerClient: t.config.Ciphers,
  355. MACsClientServer: t.config.MACs,
  356. MACsServerClient: t.config.MACs,
  357. CompressionClientServer: supportedCompressions,
  358. CompressionServerClient: supportedCompressions,
  359. }
  360. io.ReadFull(rand.Reader, msg.Cookie[:])
  361. if len(t.hostKeys) > 0 {
  362. for _, k := range t.hostKeys {
  363. msg.ServerHostKeyAlgos = append(
  364. msg.ServerHostKeyAlgos, k.PublicKey().Type())
  365. }
  366. } else {
  367. msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
  368. }
  369. packet := Marshal(msg)
  370. // writePacket destroys the contents, so save a copy.
  371. packetCopy := make([]byte, len(packet))
  372. copy(packetCopy, packet)
  373. if err := t.pushPacket(packetCopy); err != nil {
  374. return err
  375. }
  376. t.sentInitMsg = msg
  377. t.sentInitPacket = packet
  378. return nil
  379. }
  380. func (t *handshakeTransport) writePacket(p []byte) error {
  381. switch p[0] {
  382. case msgKexInit:
  383. return errors.New("ssh: only handshakeTransport can send kexInit")
  384. case msgNewKeys:
  385. return errors.New("ssh: only handshakeTransport can send newKeys")
  386. }
  387. t.mu.Lock()
  388. defer t.mu.Unlock()
  389. if t.writeError != nil {
  390. return t.writeError
  391. }
  392. if t.sentInitMsg != nil {
  393. // Copy the packet so the writer can reuse the buffer.
  394. cp := make([]byte, len(p))
  395. copy(cp, p)
  396. t.pendingPackets = append(t.pendingPackets, cp)
  397. return nil
  398. }
  399. if t.writeBytesLeft > 0 {
  400. t.writeBytesLeft -= int64(len(p))
  401. } else {
  402. t.requestKeyExchange()
  403. }
  404. if t.writePacketsLeft > 0 {
  405. t.writePacketsLeft--
  406. } else {
  407. t.requestKeyExchange()
  408. }
  409. if err := t.pushPacket(p); err != nil {
  410. t.writeError = err
  411. }
  412. return nil
  413. }
  414. func (t *handshakeTransport) Close() error {
  415. return t.conn.Close()
  416. }
  417. func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
  418. if debugHandshake {
  419. log.Printf("%s entered key exchange", t.id())
  420. }
  421. otherInit := &kexInitMsg{}
  422. if err := Unmarshal(otherInitPacket, otherInit); err != nil {
  423. return err
  424. }
  425. magics := handshakeMagics{
  426. clientVersion: t.clientVersion,
  427. serverVersion: t.serverVersion,
  428. clientKexInit: otherInitPacket,
  429. serverKexInit: t.sentInitPacket,
  430. }
  431. clientInit := otherInit
  432. serverInit := t.sentInitMsg
  433. if len(t.hostKeys) == 0 {
  434. clientInit, serverInit = serverInit, clientInit
  435. magics.clientKexInit = t.sentInitPacket
  436. magics.serverKexInit = otherInitPacket
  437. }
  438. var err error
  439. t.algorithms, err = findAgreedAlgorithms(clientInit, serverInit)
  440. if err != nil {
  441. return err
  442. }
  443. // We don't send FirstKexFollows, but we handle receiving it.
  444. //
  445. // RFC 4253 section 7 defines the kex and the agreement method for
  446. // first_kex_packet_follows. It states that the guessed packet
  447. // should be ignored if the "kex algorithm and/or the host
  448. // key algorithm is guessed wrong (server and client have
  449. // different preferred algorithm), or if any of the other
  450. // algorithms cannot be agreed upon". The other algorithms have
  451. // already been checked above so the kex algorithm and host key
  452. // algorithm are checked here.
  453. if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
  454. // other side sent a kex message for the wrong algorithm,
  455. // which we have to ignore.
  456. if _, err := t.conn.readPacket(); err != nil {
  457. return err
  458. }
  459. }
  460. kex, ok := kexAlgoMap[t.algorithms.kex]
  461. if !ok {
  462. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
  463. }
  464. var result *kexResult
  465. if len(t.hostKeys) > 0 {
  466. result, err = t.server(kex, t.algorithms, &magics)
  467. } else {
  468. result, err = t.client(kex, t.algorithms, &magics)
  469. }
  470. if err != nil {
  471. return err
  472. }
  473. if t.sessionID == nil {
  474. t.sessionID = result.H
  475. }
  476. result.SessionID = t.sessionID
  477. t.conn.prepareKeyChange(t.algorithms, result)
  478. if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
  479. return err
  480. }
  481. if packet, err := t.conn.readPacket(); err != nil {
  482. return err
  483. } else if packet[0] != msgNewKeys {
  484. return unexpectedMessageError(msgNewKeys, packet[0])
  485. }
  486. return nil
  487. }
  488. func (t *handshakeTransport) server(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  489. var hostKey Signer
  490. for _, k := range t.hostKeys {
  491. if algs.hostKey == k.PublicKey().Type() {
  492. hostKey = k
  493. }
  494. }
  495. r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey)
  496. return r, err
  497. }
  498. func (t *handshakeTransport) client(kex kexAlgorithm, algs *algorithms, magics *handshakeMagics) (*kexResult, error) {
  499. result, err := kex.Client(t.conn, t.config.Rand, magics)
  500. if err != nil {
  501. return nil, err
  502. }
  503. hostKey, err := ParsePublicKey(result.HostKey)
  504. if err != nil {
  505. return nil, err
  506. }
  507. if err := verifyHostKeySignature(hostKey, result); err != nil {
  508. return nil, err
  509. }
  510. if t.hostKeyCallback != nil {
  511. err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
  512. if err != nil {
  513. return nil, err
  514. }
  515. }
  516. return result, nil
  517. }