handshake.go 34 KB

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