handshake.go 15 KB

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