handshake.go 36 KB

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