handshake.go 14 KB

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