You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handshake.go 16KB

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