handshake.go 18 KB

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