handshake.go 15 KB

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