handshake.go 14 KB

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