handshake.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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. "strings"
  13. "sync"
  14. // [Psiphon]
  15. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  16. )
  17. // debugHandshake, if set, prints messages sent and received. Key
  18. // exchange messages are printed as if DH were used, so the debug
  19. // messages are wrong when using ECDH.
  20. const debugHandshake = false
  21. // chanSize sets the amount of buffering SSH connections. This is
  22. // primarily for testing: setting chanSize=0 uncovers deadlocks more
  23. // quickly.
  24. const chanSize = 16
  25. // keyingTransport is a packet based transport that supports key
  26. // changes. It need not be thread-safe. It should pass through
  27. // msgNewKeys in both directions.
  28. type keyingTransport interface {
  29. packetConn
  30. // prepareKeyChange sets up a key change. The key change for a
  31. // direction will be effected if a msgNewKeys message is sent
  32. // or received.
  33. prepareKeyChange(*algorithms, *kexResult) error
  34. // setStrictMode sets the strict KEX mode, notably triggering
  35. // sequence number resets on sending or receiving msgNewKeys.
  36. // If the sequence number is already > 1 when setStrictMode
  37. // is called, an error is returned.
  38. setStrictMode() error
  39. // setInitialKEXDone indicates to the transport that the initial key exchange
  40. // was completed
  41. setInitialKEXDone()
  42. }
  43. // handshakeTransport implements rekeying on top of a keyingTransport
  44. // and offers a thread-safe writePacket() interface.
  45. type handshakeTransport struct {
  46. conn keyingTransport
  47. config *Config
  48. serverVersion []byte
  49. clientVersion []byte
  50. // hostKeys is non-empty if we are the server. In that case,
  51. // it contains all host keys that can be used to sign the
  52. // connection.
  53. hostKeys []Signer
  54. // publicKeyAuthAlgorithms is non-empty if we are the server. In that case,
  55. // it contains the supported client public key authentication algorithms.
  56. publicKeyAuthAlgorithms []string
  57. // hostKeyAlgorithms is non-empty if we are the client. In that case,
  58. // we accept these key types from the server as host key.
  59. hostKeyAlgorithms []string
  60. // On read error, incoming is closed, and readError is set.
  61. incoming chan []byte
  62. readError error
  63. mu sync.Mutex
  64. writeError error
  65. sentInitPacket []byte
  66. sentInitMsg *kexInitMsg
  67. pendingPackets [][]byte // Used when a key exchange is in progress.
  68. writePacketsLeft uint32
  69. writeBytesLeft int64
  70. // If the read loop wants to schedule a kex, it pings this
  71. // channel, and the write loop will send out a kex
  72. // message.
  73. requestKex chan struct{}
  74. // If the other side requests or confirms a kex, its kexInit
  75. // packet is sent here for the write loop to find it.
  76. startKex chan *pendingKex
  77. kexLoopDone chan struct{} // closed (with writeError non-nil) when kexLoop exits
  78. // data for host key checking
  79. hostKeyCallback HostKeyCallback
  80. dialAddress string
  81. remoteAddr net.Addr
  82. // bannerCallback is non-empty if we are the client and it has been set in
  83. // ClientConfig. In that case it is called during the user authentication
  84. // dance to handle a custom server's message.
  85. bannerCallback BannerCallback
  86. // Algorithms agreed in the last key exchange.
  87. algorithms *algorithms
  88. // Counters exclusively owned by readLoop.
  89. readPacketsLeft uint32
  90. readBytesLeft int64
  91. // The session ID or nil if first kex did not complete yet.
  92. sessionID []byte
  93. // strictMode indicates if the other side of the handshake indicated
  94. // that we should be following the strict KEX protocol restrictions.
  95. strictMode bool
  96. }
  97. type pendingKex struct {
  98. otherInit []byte
  99. done chan error
  100. }
  101. func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
  102. t := &handshakeTransport{
  103. conn: conn,
  104. serverVersion: serverVersion,
  105. clientVersion: clientVersion,
  106. incoming: make(chan []byte, chanSize),
  107. requestKex: make(chan struct{}, 1),
  108. startKex: make(chan *pendingKex),
  109. kexLoopDone: make(chan struct{}),
  110. config: config,
  111. }
  112. t.resetReadThresholds()
  113. t.resetWriteThresholds()
  114. // We always start with a mandatory key exchange.
  115. t.requestKex <- struct{}{}
  116. return t
  117. }
  118. func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
  119. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  120. t.dialAddress = dialAddr
  121. t.remoteAddr = addr
  122. t.hostKeyCallback = config.HostKeyCallback
  123. t.bannerCallback = config.BannerCallback
  124. if config.HostKeyAlgorithms != nil {
  125. t.hostKeyAlgorithms = config.HostKeyAlgorithms
  126. } else {
  127. t.hostKeyAlgorithms = supportedHostKeyAlgos
  128. }
  129. go t.readLoop()
  130. go t.kexLoop()
  131. return t
  132. }
  133. func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
  134. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  135. t.hostKeys = config.hostKeys
  136. t.publicKeyAuthAlgorithms = config.PublicKeyAuthAlgorithms
  137. go t.readLoop()
  138. go t.kexLoop()
  139. return t
  140. }
  141. func (t *handshakeTransport) getSessionID() []byte {
  142. return t.sessionID
  143. }
  144. // waitSession waits for the session to be established. This should be
  145. // the first thing to call after instantiating handshakeTransport.
  146. func (t *handshakeTransport) waitSession() error {
  147. p, err := t.readPacket()
  148. if err != nil {
  149. return err
  150. }
  151. if p[0] != msgNewKeys {
  152. return fmt.Errorf("ssh: first packet should be msgNewKeys")
  153. }
  154. return nil
  155. }
  156. func (t *handshakeTransport) id() string {
  157. if len(t.hostKeys) > 0 {
  158. return "server"
  159. }
  160. return "client"
  161. }
  162. func (t *handshakeTransport) printPacket(p []byte, write bool) {
  163. action := "got"
  164. if write {
  165. action = "sent"
  166. }
  167. if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
  168. log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
  169. } else {
  170. msg, err := decode(p)
  171. log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
  172. }
  173. }
  174. func (t *handshakeTransport) readPacket() ([]byte, error) {
  175. p, ok := <-t.incoming
  176. if !ok {
  177. return nil, t.readError
  178. }
  179. return p, nil
  180. }
  181. func (t *handshakeTransport) readLoop() {
  182. first := true
  183. for {
  184. p, err := t.readOnePacket(first)
  185. first = false
  186. if err != nil {
  187. t.readError = err
  188. close(t.incoming)
  189. break
  190. }
  191. // If this is the first kex, and strict KEX mode is enabled,
  192. // we don't ignore any messages, as they may be used to manipulate
  193. // the packet sequence numbers.
  194. if !(t.sessionID == nil && t.strictMode) && (p[0] == msgIgnore || p[0] == msgDebug) {
  195. continue
  196. }
  197. t.incoming <- p
  198. }
  199. // Stop writers too.
  200. t.recordWriteError(t.readError)
  201. // Unblock the writer should it wait for this.
  202. close(t.startKex)
  203. // Don't close t.requestKex; it's also written to from writePacket.
  204. }
  205. func (t *handshakeTransport) pushPacket(p []byte) error {
  206. if debugHandshake {
  207. t.printPacket(p, true)
  208. }
  209. return t.conn.writePacket(p)
  210. }
  211. func (t *handshakeTransport) getWriteError() error {
  212. t.mu.Lock()
  213. defer t.mu.Unlock()
  214. return t.writeError
  215. }
  216. func (t *handshakeTransport) recordWriteError(err error) {
  217. t.mu.Lock()
  218. defer t.mu.Unlock()
  219. if t.writeError == nil && err != nil {
  220. t.writeError = err
  221. }
  222. }
  223. func (t *handshakeTransport) requestKeyExchange() {
  224. select {
  225. case t.requestKex <- struct{}{}:
  226. default:
  227. // something already requested a kex, so do nothing.
  228. }
  229. }
  230. func (t *handshakeTransport) resetWriteThresholds() {
  231. t.writePacketsLeft = packetRekeyThreshold
  232. if t.config.RekeyThreshold > 0 {
  233. t.writeBytesLeft = int64(t.config.RekeyThreshold)
  234. } else if t.algorithms != nil {
  235. t.writeBytesLeft = t.algorithms.w.rekeyBytes()
  236. } else {
  237. t.writeBytesLeft = 1 << 30
  238. }
  239. }
  240. func (t *handshakeTransport) kexLoop() {
  241. write:
  242. for t.getWriteError() == nil {
  243. var request *pendingKex
  244. var sent bool
  245. for request == nil || !sent {
  246. var ok bool
  247. select {
  248. case request, ok = <-t.startKex:
  249. if !ok {
  250. break write
  251. }
  252. case <-t.requestKex:
  253. break
  254. }
  255. if !sent {
  256. if err := t.sendKexInit(); err != nil {
  257. t.recordWriteError(err)
  258. break
  259. }
  260. sent = true
  261. }
  262. }
  263. if err := t.getWriteError(); err != nil {
  264. if request != nil {
  265. request.done <- err
  266. }
  267. break
  268. }
  269. // We're not servicing t.requestKex, but that is OK:
  270. // we never block on sending to t.requestKex.
  271. // We're not servicing t.startKex, but the remote end
  272. // has just sent us a kexInitMsg, so it can't send
  273. // another key change request, until we close the done
  274. // channel on the pendingKex request.
  275. err := t.enterKeyExchange(request.otherInit)
  276. t.mu.Lock()
  277. t.writeError = err
  278. t.sentInitPacket = nil
  279. t.sentInitMsg = nil
  280. t.resetWriteThresholds()
  281. // we have completed the key exchange. Since the
  282. // reader is still blocked, it is safe to clear out
  283. // the requestKex channel. This avoids the situation
  284. // where: 1) we consumed our own request for the
  285. // initial kex, and 2) the kex from the remote side
  286. // caused another send on the requestKex channel,
  287. clear:
  288. for {
  289. select {
  290. case <-t.requestKex:
  291. //
  292. default:
  293. break clear
  294. }
  295. }
  296. request.done <- t.writeError
  297. // kex finished. Push packets that we received while
  298. // the kex was in progress. Don't look at t.startKex
  299. // and don't increment writtenSinceKex: if we trigger
  300. // another kex while we are still busy with the last
  301. // one, things will become very confusing.
  302. for _, p := range t.pendingPackets {
  303. t.writeError = t.pushPacket(p)
  304. if t.writeError != nil {
  305. break
  306. }
  307. }
  308. t.pendingPackets = t.pendingPackets[:0]
  309. t.mu.Unlock()
  310. }
  311. // Unblock reader.
  312. t.conn.Close()
  313. // drain startKex channel. We don't service t.requestKex
  314. // because nobody does blocking sends there.
  315. for request := range t.startKex {
  316. request.done <- t.getWriteError()
  317. }
  318. // Mark that the loop is done so that Close can return.
  319. close(t.kexLoopDone)
  320. }
  321. // The protocol uses uint32 for packet counters, so we can't let them
  322. // reach 1<<32. We will actually read and write more packets than
  323. // this, though: the other side may send more packets, and after we
  324. // hit this limit on writing we will send a few more packets for the
  325. // key exchange itself.
  326. const packetRekeyThreshold = (1 << 31)
  327. func (t *handshakeTransport) resetReadThresholds() {
  328. t.readPacketsLeft = packetRekeyThreshold
  329. if t.config.RekeyThreshold > 0 {
  330. t.readBytesLeft = int64(t.config.RekeyThreshold)
  331. } else if t.algorithms != nil {
  332. t.readBytesLeft = t.algorithms.r.rekeyBytes()
  333. } else {
  334. t.readBytesLeft = 1 << 30
  335. }
  336. }
  337. func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
  338. p, err := t.conn.readPacket()
  339. if err != nil {
  340. return nil, err
  341. }
  342. if t.readPacketsLeft > 0 {
  343. t.readPacketsLeft--
  344. } else {
  345. t.requestKeyExchange()
  346. }
  347. if t.readBytesLeft > 0 {
  348. t.readBytesLeft -= int64(len(p))
  349. } else {
  350. t.requestKeyExchange()
  351. }
  352. if debugHandshake {
  353. t.printPacket(p, false)
  354. }
  355. if first && p[0] != msgKexInit {
  356. return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
  357. }
  358. if p[0] != msgKexInit {
  359. return p, nil
  360. }
  361. firstKex := t.sessionID == nil
  362. kex := pendingKex{
  363. done: make(chan error, 1),
  364. otherInit: p,
  365. }
  366. t.startKex <- &kex
  367. err = <-kex.done
  368. if debugHandshake {
  369. log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
  370. }
  371. if err != nil {
  372. return nil, err
  373. }
  374. t.resetReadThresholds()
  375. // By default, a key exchange is hidden from higher layers by
  376. // translating it into msgIgnore.
  377. successPacket := []byte{msgIgnore}
  378. if firstKex {
  379. // sendKexInit() for the first kex waits for
  380. // msgNewKeys so the authentication process is
  381. // guaranteed to happen over an encrypted transport.
  382. successPacket = []byte{msgNewKeys}
  383. }
  384. return successPacket, nil
  385. }
  386. const (
  387. kexStrictClient = "kex-strict-c-v00@openssh.com"
  388. kexStrictServer = "kex-strict-s-v00@openssh.com"
  389. )
  390. // sendKexInit sends a key change message.
  391. func (t *handshakeTransport) sendKexInit() error {
  392. t.mu.Lock()
  393. defer t.mu.Unlock()
  394. if t.sentInitMsg != nil {
  395. // kexInits may be sent either in response to the other side,
  396. // or because our side wants to initiate a key change, so we
  397. // may have already sent a kexInit. In that case, don't send a
  398. // second kexInit.
  399. return nil
  400. }
  401. msg := &kexInitMsg{
  402. CiphersClientServer: t.config.Ciphers,
  403. CiphersServerClient: t.config.Ciphers,
  404. MACsClientServer: t.config.MACs,
  405. MACsServerClient: t.config.MACs,
  406. CompressionClientServer: supportedCompressions,
  407. CompressionServerClient: supportedCompressions,
  408. }
  409. io.ReadFull(rand.Reader, msg.Cookie[:])
  410. // We mutate the KexAlgos slice, in order to add the kex-strict extension algorithm,
  411. // and possibly to add the ext-info extension algorithm. Since the slice may be the
  412. // user owned KeyExchanges, we create our own slice in order to avoid using user
  413. // owned memory by mistake.
  414. msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+2) // room for kex-strict and ext-info
  415. msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...)
  416. isServer := len(t.hostKeys) > 0
  417. if isServer {
  418. for _, k := range t.hostKeys {
  419. // If k is a MultiAlgorithmSigner, we restrict the signature
  420. // algorithms. If k is a AlgorithmSigner, presume it supports all
  421. // signature algorithms associated with the key format. If k is not
  422. // an AlgorithmSigner, we can only assume it only supports the
  423. // algorithms that matches the key format. (This means that Sign
  424. // can't pick a different default).
  425. keyFormat := k.PublicKey().Type()
  426. switch s := k.(type) {
  427. case MultiAlgorithmSigner:
  428. for _, algo := range algorithmsForKeyFormat(keyFormat) {
  429. if contains(s.Algorithms(), underlyingAlgo(algo)) {
  430. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algo)
  431. }
  432. }
  433. case AlgorithmSigner:
  434. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algorithmsForKeyFormat(keyFormat)...)
  435. default:
  436. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, keyFormat)
  437. }
  438. }
  439. if t.sessionID == nil {
  440. msg.KexAlgos = append(msg.KexAlgos, kexStrictServer)
  441. }
  442. } else {
  443. msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
  444. // As a client we opt in to receiving SSH_MSG_EXT_INFO so we know what
  445. // algorithms the server supports for public key authentication. See RFC
  446. // 8308, Section 2.1.
  447. //
  448. // We also send the strict KEX mode extension algorithm, in order to opt
  449. // into the strict KEX mode.
  450. if firstKeyExchange := t.sessionID == nil; firstKeyExchange {
  451. msg.KexAlgos = append(msg.KexAlgos, "ext-info-c")
  452. msg.KexAlgos = append(msg.KexAlgos, kexStrictClient)
  453. }
  454. }
  455. // [Psiphon]
  456. //
  457. // When KEXPRNGSeed is specified, randomize the KEX. The offered
  458. // algorithms are shuffled and truncated. Longer lists are selected with
  459. // higher probability.
  460. //
  461. // When PeerKEXPRNGSeed is specified, the peer is expected to randomize
  462. // its KEX using the specified seed; deterministically adjust own
  463. // randomized KEX to ensure negotiation succeeds.
  464. //
  465. // When NoEncryptThenMACHash is specified, do not use Encrypt-then-MAC has
  466. // algorithms.
  467. //
  468. // Limitations:
  469. //
  470. // - "ext-info-c" and "kex-strict-c/s-v00@openssh.com" extensions included
  471. // in KexAlgos may be truncated; Psiphon's usage of SSH does not
  472. // request SSH_MSG_EXT_INFO for client authentication and should not
  473. // be vulnerable to downgrade attacks related to stripping
  474. // SSH_MSG_EXT_INFO.
  475. //
  476. // - KEX algorithms are not synchronized with the version identification
  477. // string.
  478. equal := func(list1, list2 []string) bool {
  479. if len(list1) != len(list2) {
  480. return false
  481. }
  482. for i, entry := range list1 {
  483. if list2[i] != entry {
  484. return false
  485. }
  486. }
  487. return true
  488. }
  489. // Psiphon transforms assume that default algorithms are configured.
  490. if (t.config.NoEncryptThenMACHash || t.config.KEXPRNGSeed != nil) &&
  491. (!equal(t.config.KeyExchanges, preferredKexAlgos) ||
  492. !equal(t.config.Ciphers, preferredCiphers) ||
  493. !equal(t.config.MACs, supportedMACs)) {
  494. return errors.New("ssh: custom algorithm preferences not supported")
  495. }
  496. // This is the list of supported non-Encrypt-then-MAC algorithms from
  497. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/blob/3ef11effe6acd9
  498. // 2c3aefd140ee09c42a1f15630b/psiphon/common/crypto/ssh/common.go#L60
  499. //
  500. // With Encrypt-then-MAC hash algorithms, packet length is transmitted in
  501. // plaintext, which aids in traffic analysis.
  502. //
  503. // When using obfuscated SSH, where only the initial, unencrypted
  504. // packets are obfuscated, NoEncryptThenMACHash should be set.
  505. noEncryptThenMACs := []string{"hmac-sha2-256", "hmac-sha2-512", "hmac-sha1", "hmac-sha1-96"}
  506. if t.config.NoEncryptThenMACHash {
  507. msg.MACsClientServer = noEncryptThenMACs
  508. msg.MACsServerClient = noEncryptThenMACs
  509. }
  510. if t.config.KEXPRNGSeed != nil {
  511. permute := func(PRNG *prng.PRNG, list []string) []string {
  512. newList := make([]string, len(list))
  513. perm := PRNG.Perm(len(list))
  514. for i, j := range perm {
  515. newList[j] = list[i]
  516. }
  517. return newList
  518. }
  519. truncate := func(PRNG *prng.PRNG, list []string) []string {
  520. cut := len(list)
  521. for ; cut > 1; cut-- {
  522. if !PRNG.FlipCoin() {
  523. break
  524. }
  525. }
  526. return list[:cut]
  527. }
  528. retain := func(PRNG *prng.PRNG, list []string, item string) []string {
  529. for _, entry := range list {
  530. if entry == item {
  531. return list
  532. }
  533. }
  534. replace := PRNG.Intn(len(list))
  535. list[replace] = item
  536. return list
  537. }
  538. firstKexAlgo := func(kexAlgos []string) (string, bool) {
  539. for _, kexAlgo := range kexAlgos {
  540. switch kexAlgo {
  541. case "ext-info-c",
  542. "kex-strict-c-v00@openssh.com",
  543. "kex-strict-s-v00@openssh.com":
  544. // These extensions are not KEX algorithms
  545. default:
  546. return kexAlgo, true
  547. }
  548. }
  549. return "", false
  550. }
  551. selectKexAlgos := func(PRNG *prng.PRNG, kexAlgos []string) []string {
  552. kexAlgos = truncate(PRNG, permute(PRNG, kexAlgos))
  553. // Ensure an actual KEX algorithm is always selected
  554. if _, ok := firstKexAlgo(kexAlgos); ok {
  555. return kexAlgos
  556. }
  557. return retain(PRNG, kexAlgos, permute(PRNG, preferredKexAlgos)[0])
  558. }
  559. // Downgrade servers to use the algorithm lists used previously in
  560. // commits before 435a6a3f. This ensures that (a) the PeerKEXPRNGSeed
  561. // mechanism used in all existing clients correctly predicts the
  562. // server's algorithms; (b) random truncation by the server doesn't
  563. // select only new algorithms unknown to existing clients.
  564. //
  565. // TODO: add a versioning mechanism, such as a SSHv2 capability, to
  566. // allow for servers with new algorithm lists, where older clients
  567. // won't try to connect to these servers, and new clients know to use
  568. // non-legacy lists in the PeerKEXPRNGSeed mechanism.
  569. legacyServerKexAlgos := []string{
  570. kexAlgoCurve25519SHA256LibSSH,
  571. kexAlgoECDH256, kexAlgoECDH384, kexAlgoECDH521,
  572. kexAlgoDH14SHA256, kexAlgoDH14SHA1,
  573. }
  574. legacyServerCiphers := []string{
  575. "aes128-gcm@openssh.com",
  576. chacha20Poly1305ID,
  577. "aes128-ctr", "aes192-ctr", "aes256-ctr",
  578. }
  579. legacyServerMACs := []string{
  580. "hmac-sha2-256-etm@openssh.com",
  581. "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96",
  582. }
  583. legacyServerNoEncryptThenMACs := []string{
  584. "hmac-sha2-256", "hmac-sha1", "hmac-sha1-96"}
  585. isServer := len(t.hostKeys) > 0
  586. PRNG := prng.NewPRNGWithSeed(t.config.KEXPRNGSeed)
  587. startingKexAlgos := msg.KexAlgos
  588. startingCiphers := msg.CiphersClientServer
  589. startingMACs := msg.MACsClientServer
  590. if isServer {
  591. startingKexAlgos = legacyServerKexAlgos
  592. startingCiphers = legacyServerCiphers
  593. startingMACs = legacyServerMACs
  594. }
  595. msg.KexAlgos = selectKexAlgos(PRNG, startingKexAlgos)
  596. ciphers := truncate(PRNG, permute(PRNG, startingCiphers))
  597. msg.CiphersClientServer = ciphers
  598. msg.CiphersServerClient = ciphers
  599. MACs := truncate(PRNG, permute(PRNG, startingMACs))
  600. msg.MACsClientServer = MACs
  601. msg.MACsServerClient = MACs
  602. if isServer {
  603. msg.ServerHostKeyAlgos = permute(PRNG, msg.ServerHostKeyAlgos)
  604. } else {
  605. // Must offer KeyAlgoRSA to Psiphon server.
  606. msg.ServerHostKeyAlgos = retain(
  607. PRNG,
  608. truncate(PRNG, permute(PRNG, msg.ServerHostKeyAlgos)),
  609. KeyAlgoRSA)
  610. }
  611. if !isServer && t.config.PeerKEXPRNGSeed != nil {
  612. // Generate the peer KEX and make adjustments if negotiation would
  613. // fail. This assumes that PeerKEXPRNGSeed remains static (in
  614. // Psiphon, the peer is the server and PeerKEXPRNGSeed is derived
  615. // from the server entry); and that the PRNG is invoked in the
  616. // exact same order on the peer (i.e., the code block immediately
  617. // above is what the peer runs); and that the peer sets
  618. // NoEncryptThenMACHash in the same cases.
  619. PeerPRNG := prng.NewPRNGWithSeed(t.config.PeerKEXPRNGSeed)
  620. // Note that only the client sends "ext-info-c"
  621. // and "kex-strict-c-v00@openssh.com" and only the server
  622. // sends "kex-strict-s-v00@openssh.com", so these will never
  623. // match and do not need to be filtered out before findCommon.
  624. //
  625. // The following assumes that the server always starts with the
  626. // default preferredKexAlgos along with
  627. // "kex-strict-s-v00@openssh.com" appended before randomizing.
  628. serverKexAlgos := append(
  629. append([]string(nil), preferredKexAlgos...),
  630. "kex-strict-s-v00@openssh.com")
  631. serverCiphers := preferredCiphers
  632. serverMACS := supportedMACs
  633. serverNoEncryptThenMACs := noEncryptThenMACs
  634. // Switch to using the legacy algorithms that the server currently
  635. // downgrades to (see comment above).
  636. //
  637. // TODO: for servers without legacy backwards compatibility
  638. // concerns, skip the following lines.
  639. serverKexAlgos = legacyServerKexAlgos
  640. serverCiphers = legacyServerCiphers
  641. serverMACS = legacyServerMACs
  642. serverNoEncryptThenMACs = legacyServerNoEncryptThenMACs
  643. serverKexAlgos = selectKexAlgos(PeerPRNG, serverKexAlgos)
  644. if _, err := findCommon("", msg.KexAlgos, serverKexAlgos); err != nil {
  645. if kexAlgo, ok := firstKexAlgo(serverKexAlgos); ok {
  646. msg.KexAlgos = retain(PRNG, msg.KexAlgos, kexAlgo)
  647. }
  648. }
  649. serverCiphers = truncate(PeerPRNG, permute(PeerPRNG, serverCiphers))
  650. if _, err := findCommon("", ciphers, serverCiphers); err != nil {
  651. ciphers = retain(PRNG, ciphers, serverCiphers[0])
  652. msg.CiphersClientServer = ciphers
  653. msg.CiphersServerClient = ciphers
  654. }
  655. if t.config.NoEncryptThenMACHash {
  656. serverMACS = serverNoEncryptThenMACs
  657. }
  658. serverMACS = truncate(PeerPRNG, permute(PeerPRNG, serverMACS))
  659. if _, err := findCommon("", MACs, serverMACS); err != nil {
  660. MACs = retain(PRNG, MACs, serverMACS[0])
  661. msg.MACsClientServer = MACs
  662. msg.MACsServerClient = MACs
  663. }
  664. }
  665. // Offer "zlib@openssh.com", which is offered by OpenSSH. Compression
  666. // is not actually implemented, but since "zlib@openssh.com"
  667. // compression is delayed until after authentication
  668. // (https://www.openssh.com/txt/draft-miller-secsh-compression-
  669. // delayed-00.txt), an unauthenticated probe of the SSH server will
  670. // not detect this. "none" is always included to ensure negotiation
  671. // succeeds.
  672. if PRNG.FlipCoin() {
  673. compressions := permute(PRNG, []string{"none", "zlib@openssh.com"})
  674. msg.CompressionClientServer = compressions
  675. msg.CompressionServerClient = compressions
  676. }
  677. }
  678. packet := Marshal(msg)
  679. // writePacket destroys the contents, so save a copy.
  680. packetCopy := make([]byte, len(packet))
  681. copy(packetCopy, packet)
  682. if err := t.pushPacket(packetCopy); err != nil {
  683. return err
  684. }
  685. t.sentInitMsg = msg
  686. t.sentInitPacket = packet
  687. return nil
  688. }
  689. func (t *handshakeTransport) writePacket(p []byte) error {
  690. switch p[0] {
  691. case msgKexInit:
  692. return errors.New("ssh: only handshakeTransport can send kexInit")
  693. case msgNewKeys:
  694. return errors.New("ssh: only handshakeTransport can send newKeys")
  695. }
  696. t.mu.Lock()
  697. defer t.mu.Unlock()
  698. if t.writeError != nil {
  699. return t.writeError
  700. }
  701. if t.sentInitMsg != nil {
  702. // Copy the packet so the writer can reuse the buffer.
  703. cp := make([]byte, len(p))
  704. copy(cp, p)
  705. t.pendingPackets = append(t.pendingPackets, cp)
  706. return nil
  707. }
  708. if t.writeBytesLeft > 0 {
  709. t.writeBytesLeft -= int64(len(p))
  710. } else {
  711. t.requestKeyExchange()
  712. }
  713. if t.writePacketsLeft > 0 {
  714. t.writePacketsLeft--
  715. } else {
  716. t.requestKeyExchange()
  717. }
  718. if err := t.pushPacket(p); err != nil {
  719. t.writeError = err
  720. }
  721. return nil
  722. }
  723. func (t *handshakeTransport) Close() error {
  724. // Close the connection. This should cause the readLoop goroutine to wake up
  725. // and close t.startKex, which will shut down kexLoop if running.
  726. err := t.conn.Close()
  727. // Wait for the kexLoop goroutine to complete.
  728. // At that point we know that the readLoop goroutine is complete too,
  729. // because kexLoop itself waits for readLoop to close the startKex channel.
  730. <-t.kexLoopDone
  731. return err
  732. }
  733. func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
  734. if debugHandshake {
  735. log.Printf("%s entered key exchange", t.id())
  736. }
  737. otherInit := &kexInitMsg{}
  738. if err := Unmarshal(otherInitPacket, otherInit); err != nil {
  739. return err
  740. }
  741. magics := handshakeMagics{
  742. clientVersion: t.clientVersion,
  743. serverVersion: t.serverVersion,
  744. clientKexInit: otherInitPacket,
  745. serverKexInit: t.sentInitPacket,
  746. }
  747. clientInit := otherInit
  748. serverInit := t.sentInitMsg
  749. isClient := len(t.hostKeys) == 0
  750. if isClient {
  751. clientInit, serverInit = serverInit, clientInit
  752. magics.clientKexInit = t.sentInitPacket
  753. magics.serverKexInit = otherInitPacket
  754. }
  755. var err error
  756. t.algorithms, err = findAgreedAlgorithms(isClient, clientInit, serverInit)
  757. if err != nil {
  758. return err
  759. }
  760. if t.sessionID == nil && ((isClient && contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && contains(clientInit.KexAlgos, kexStrictClient))) &&
  761. // [Psiphon]
  762. // When KEX randomization omits "kex-strict-c/s-v00@openssh.com"
  763. // (see comment in sendKexInit), do not enable strict mode.
  764. ((isClient && contains(t.sentInitMsg.KexAlgos, kexStrictClient)) || (!isClient && contains(t.sentInitMsg.KexAlgos, kexStrictServer))) {
  765. t.strictMode = true
  766. if err := t.conn.setStrictMode(); err != nil {
  767. return err
  768. }
  769. }
  770. // We don't send FirstKexFollows, but we handle receiving it.
  771. //
  772. // RFC 4253 section 7 defines the kex and the agreement method for
  773. // first_kex_packet_follows. It states that the guessed packet
  774. // should be ignored if the "kex algorithm and/or the host
  775. // key algorithm is guessed wrong (server and client have
  776. // different preferred algorithm), or if any of the other
  777. // algorithms cannot be agreed upon". The other algorithms have
  778. // already been checked above so the kex algorithm and host key
  779. // algorithm are checked here.
  780. if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
  781. // other side sent a kex message for the wrong algorithm,
  782. // which we have to ignore.
  783. if _, err := t.conn.readPacket(); err != nil {
  784. return err
  785. }
  786. }
  787. kex, ok := kexAlgoMap[t.algorithms.kex]
  788. if !ok {
  789. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.kex)
  790. }
  791. var result *kexResult
  792. if len(t.hostKeys) > 0 {
  793. result, err = t.server(kex, &magics)
  794. } else {
  795. result, err = t.client(kex, &magics)
  796. }
  797. if err != nil {
  798. return err
  799. }
  800. firstKeyExchange := t.sessionID == nil
  801. if firstKeyExchange {
  802. t.sessionID = result.H
  803. }
  804. result.SessionID = t.sessionID
  805. if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil {
  806. return err
  807. }
  808. if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
  809. return err
  810. }
  811. // On the server side, after the first SSH_MSG_NEWKEYS, send a SSH_MSG_EXT_INFO
  812. // message with the server-sig-algs extension if the client supports it. See
  813. // RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9.
  814. if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") {
  815. supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",")
  816. extInfo := &extInfoMsg{
  817. NumExtensions: 2,
  818. Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)+4+16+4+1),
  819. }
  820. extInfo.Payload = appendInt(extInfo.Payload, len("server-sig-algs"))
  821. extInfo.Payload = append(extInfo.Payload, "server-sig-algs"...)
  822. extInfo.Payload = appendInt(extInfo.Payload, len(supportedPubKeyAuthAlgosList))
  823. extInfo.Payload = append(extInfo.Payload, supportedPubKeyAuthAlgosList...)
  824. extInfo.Payload = appendInt(extInfo.Payload, len("ping@openssh.com"))
  825. extInfo.Payload = append(extInfo.Payload, "ping@openssh.com"...)
  826. extInfo.Payload = appendInt(extInfo.Payload, 1)
  827. extInfo.Payload = append(extInfo.Payload, "0"...)
  828. if err := t.conn.writePacket(Marshal(extInfo)); err != nil {
  829. return err
  830. }
  831. }
  832. if packet, err := t.conn.readPacket(); err != nil {
  833. return err
  834. } else if packet[0] != msgNewKeys {
  835. return unexpectedMessageError(msgNewKeys, packet[0])
  836. }
  837. if firstKeyExchange {
  838. // Indicates to the transport that the first key exchange is completed
  839. // after receiving SSH_MSG_NEWKEYS.
  840. t.conn.setInitialKEXDone()
  841. }
  842. return nil
  843. }
  844. // algorithmSignerWrapper is an AlgorithmSigner that only supports the default
  845. // key format algorithm.
  846. //
  847. // This is technically a violation of the AlgorithmSigner interface, but it
  848. // should be unreachable given where we use this. Anyway, at least it returns an
  849. // error instead of panicing or producing an incorrect signature.
  850. type algorithmSignerWrapper struct {
  851. Signer
  852. }
  853. func (a algorithmSignerWrapper) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  854. if algorithm != underlyingAlgo(a.PublicKey().Type()) {
  855. return nil, errors.New("ssh: internal error: algorithmSignerWrapper invoked with non-default algorithm")
  856. }
  857. return a.Sign(rand, data)
  858. }
  859. func pickHostKey(hostKeys []Signer, algo string) AlgorithmSigner {
  860. for _, k := range hostKeys {
  861. if s, ok := k.(MultiAlgorithmSigner); ok {
  862. if !contains(s.Algorithms(), underlyingAlgo(algo)) {
  863. continue
  864. }
  865. }
  866. if algo == k.PublicKey().Type() {
  867. return algorithmSignerWrapper{k}
  868. }
  869. k, ok := k.(AlgorithmSigner)
  870. if !ok {
  871. continue
  872. }
  873. for _, a := range algorithmsForKeyFormat(k.PublicKey().Type()) {
  874. if algo == a {
  875. return k
  876. }
  877. }
  878. }
  879. return nil
  880. }
  881. func (t *handshakeTransport) server(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
  882. hostKey := pickHostKey(t.hostKeys, t.algorithms.hostKey)
  883. if hostKey == nil {
  884. return nil, errors.New("ssh: internal error: negotiated unsupported signature type")
  885. }
  886. r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey, t.algorithms.hostKey)
  887. return r, err
  888. }
  889. func (t *handshakeTransport) client(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
  890. result, err := kex.Client(t.conn, t.config.Rand, magics)
  891. if err != nil {
  892. return nil, err
  893. }
  894. hostKey, err := ParsePublicKey(result.HostKey)
  895. if err != nil {
  896. return nil, err
  897. }
  898. if err := verifyHostKeySignature(hostKey, t.algorithms.hostKey, result); err != nil {
  899. return nil, err
  900. }
  901. err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
  902. if err != nil {
  903. return nil, err
  904. }
  905. return result, nil
  906. }