handshake.go 17 KB

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