handshake.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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. "errors"
  7. "fmt"
  8. "io"
  9. "log"
  10. "net"
  11. "strings"
  12. "sync"
  13. )
  14. // debugHandshake, if set, prints messages sent and received. Key
  15. // exchange messages are printed as if DH were used, so the debug
  16. // messages are wrong when using ECDH.
  17. const debugHandshake = false
  18. // chanSize sets the amount of buffering SSH connections. This is
  19. // primarily for testing: setting chanSize=0 uncovers deadlocks more
  20. // quickly.
  21. const chanSize = 16
  22. // maxPendingPackets sets the maximum number of packets to queue while waiting
  23. // for KEX to complete. This limits the total pending data to maxPendingPackets
  24. // * maxPacket bytes, which is ~16.8MB.
  25. const maxPendingPackets = 64
  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(*NegotiatedAlgorithms, *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. // Condition for the above mutex. It is used to notify a completed key
  66. // exchange or a write failure. Writes can wait for this condition while a
  67. // key exchange is in progress.
  68. writeCond *sync.Cond
  69. writeError error
  70. sentInitPacket []byte
  71. sentInitMsg *kexInitMsg
  72. // Used to queue writes when a key exchange is in progress. The length is
  73. // limited by pendingPacketsSize. Once full, writes will block until the key
  74. // exchange is completed or an error occurs. If not empty, it is emptied
  75. // all at once when the key exchange is completed in kexLoop.
  76. pendingPackets [][]byte
  77. writePacketsLeft uint32
  78. writeBytesLeft int64
  79. userAuthComplete bool // whether the user authentication phase is complete
  80. // If the read loop wants to schedule a kex, it pings this
  81. // channel, and the write loop will send out a kex
  82. // message.
  83. requestKex chan struct{}
  84. // If the other side requests or confirms a kex, its kexInit
  85. // packet is sent here for the write loop to find it.
  86. startKex chan *pendingKex
  87. kexLoopDone chan struct{} // closed (with writeError non-nil) when kexLoop exits
  88. // data for host key checking
  89. hostKeyCallback HostKeyCallback
  90. dialAddress string
  91. remoteAddr net.Addr
  92. // bannerCallback is non-empty if we are the client and it has been set in
  93. // ClientConfig. In that case it is called during the user authentication
  94. // dance to handle a custom server's message.
  95. bannerCallback BannerCallback
  96. // Algorithms agreed in the last key exchange.
  97. algorithms *NegotiatedAlgorithms
  98. // Counters exclusively owned by readLoop.
  99. readPacketsLeft uint32
  100. readBytesLeft int64
  101. // The session ID or nil if first kex did not complete yet.
  102. sessionID []byte
  103. // strictMode indicates if the other side of the handshake indicated
  104. // that we should be following the strict KEX protocol restrictions.
  105. strictMode bool
  106. }
  107. type pendingKex struct {
  108. otherInit []byte
  109. done chan error
  110. }
  111. func newHandshakeTransport(conn keyingTransport, config *Config, clientVersion, serverVersion []byte) *handshakeTransport {
  112. t := &handshakeTransport{
  113. conn: conn,
  114. serverVersion: serverVersion,
  115. clientVersion: clientVersion,
  116. incoming: make(chan []byte, chanSize),
  117. requestKex: make(chan struct{}, 1),
  118. startKex: make(chan *pendingKex),
  119. kexLoopDone: make(chan struct{}),
  120. config: config,
  121. }
  122. t.writeCond = sync.NewCond(&t.mu)
  123. t.resetReadThresholds()
  124. t.resetWriteThresholds()
  125. // We always start with a mandatory key exchange.
  126. t.requestKex <- struct{}{}
  127. return t
  128. }
  129. func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ClientConfig, dialAddr string, addr net.Addr) *handshakeTransport {
  130. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  131. t.dialAddress = dialAddr
  132. t.remoteAddr = addr
  133. t.hostKeyCallback = config.HostKeyCallback
  134. t.bannerCallback = config.BannerCallback
  135. if config.HostKeyAlgorithms != nil {
  136. t.hostKeyAlgorithms = config.HostKeyAlgorithms
  137. } else {
  138. t.hostKeyAlgorithms = defaultHostKeyAlgos
  139. }
  140. go t.readLoop()
  141. go t.kexLoop()
  142. return t
  143. }
  144. func newServerTransport(conn keyingTransport, clientVersion, serverVersion []byte, config *ServerConfig) *handshakeTransport {
  145. t := newHandshakeTransport(conn, &config.Config, clientVersion, serverVersion)
  146. t.hostKeys = config.hostKeys
  147. t.publicKeyAuthAlgorithms = config.PublicKeyAuthAlgorithms
  148. go t.readLoop()
  149. go t.kexLoop()
  150. return t
  151. }
  152. func (t *handshakeTransport) getSessionID() []byte {
  153. return t.sessionID
  154. }
  155. func (t *handshakeTransport) getAlgorithms() NegotiatedAlgorithms {
  156. return *t.algorithms
  157. }
  158. // waitSession waits for the session to be established. This should be
  159. // the first thing to call after instantiating handshakeTransport.
  160. func (t *handshakeTransport) waitSession() error {
  161. p, err := t.readPacket()
  162. if err != nil {
  163. return err
  164. }
  165. if p[0] != msgNewKeys {
  166. return fmt.Errorf("ssh: first packet should be msgNewKeys")
  167. }
  168. return nil
  169. }
  170. func (t *handshakeTransport) id() string {
  171. if len(t.hostKeys) > 0 {
  172. return "server"
  173. }
  174. return "client"
  175. }
  176. func (t *handshakeTransport) printPacket(p []byte, write bool) {
  177. action := "got"
  178. if write {
  179. action = "sent"
  180. }
  181. if p[0] == msgChannelData || p[0] == msgChannelExtendedData {
  182. log.Printf("%s %s data (packet %d bytes)", t.id(), action, len(p))
  183. } else {
  184. msg, err := decode(p)
  185. log.Printf("%s %s %T %v (%v)", t.id(), action, msg, msg, err)
  186. }
  187. }
  188. func (t *handshakeTransport) readPacket() ([]byte, error) {
  189. p, ok := <-t.incoming
  190. if !ok {
  191. return nil, t.readError
  192. }
  193. return p, nil
  194. }
  195. func (t *handshakeTransport) readLoop() {
  196. first := true
  197. for {
  198. p, err := t.readOnePacket(first)
  199. first = false
  200. if err != nil {
  201. t.readError = err
  202. close(t.incoming)
  203. break
  204. }
  205. // If this is the first kex, and strict KEX mode is enabled,
  206. // we don't ignore any messages, as they may be used to manipulate
  207. // the packet sequence numbers.
  208. if !(t.sessionID == nil && t.strictMode) && (p[0] == msgIgnore || p[0] == msgDebug) {
  209. continue
  210. }
  211. t.incoming <- p
  212. }
  213. // Stop writers too.
  214. t.recordWriteError(t.readError)
  215. // Unblock the writer should it wait for this.
  216. close(t.startKex)
  217. // Don't close t.requestKex; it's also written to from writePacket.
  218. }
  219. func (t *handshakeTransport) pushPacket(p []byte) error {
  220. if debugHandshake {
  221. t.printPacket(p, true)
  222. }
  223. return t.conn.writePacket(p)
  224. }
  225. func (t *handshakeTransport) getWriteError() error {
  226. t.mu.Lock()
  227. defer t.mu.Unlock()
  228. return t.writeError
  229. }
  230. func (t *handshakeTransport) recordWriteError(err error) {
  231. t.mu.Lock()
  232. defer t.mu.Unlock()
  233. if t.writeError == nil && err != nil {
  234. t.writeError = err
  235. t.writeCond.Broadcast()
  236. }
  237. }
  238. func (t *handshakeTransport) requestKeyExchange() {
  239. select {
  240. case t.requestKex <- struct{}{}:
  241. default:
  242. // something already requested a kex, so do nothing.
  243. }
  244. }
  245. func (t *handshakeTransport) resetWriteThresholds() {
  246. t.writePacketsLeft = packetRekeyThreshold
  247. if t.config.RekeyThreshold > 0 {
  248. t.writeBytesLeft = int64(t.config.RekeyThreshold)
  249. } else if t.algorithms != nil {
  250. t.writeBytesLeft = t.algorithms.Write.rekeyBytes()
  251. } else {
  252. t.writeBytesLeft = 1 << 30
  253. }
  254. }
  255. func (t *handshakeTransport) kexLoop() {
  256. write:
  257. for t.getWriteError() == nil {
  258. var request *pendingKex
  259. var sent bool
  260. for request == nil || !sent {
  261. var ok bool
  262. select {
  263. case request, ok = <-t.startKex:
  264. if !ok {
  265. break write
  266. }
  267. case <-t.requestKex:
  268. break
  269. }
  270. if !sent {
  271. if err := t.sendKexInit(); err != nil {
  272. t.recordWriteError(err)
  273. break
  274. }
  275. sent = true
  276. }
  277. }
  278. if err := t.getWriteError(); err != nil {
  279. if request != nil {
  280. request.done <- err
  281. }
  282. break
  283. }
  284. // We're not servicing t.requestKex, but that is OK:
  285. // we never block on sending to t.requestKex.
  286. // We're not servicing t.startKex, but the remote end
  287. // has just sent us a kexInitMsg, so it can't send
  288. // another key change request, until we close the done
  289. // channel on the pendingKex request.
  290. err := t.enterKeyExchange(request.otherInit)
  291. t.mu.Lock()
  292. t.writeError = err
  293. t.sentInitPacket = nil
  294. t.sentInitMsg = nil
  295. t.resetWriteThresholds()
  296. // we have completed the key exchange. Since the
  297. // reader is still blocked, it is safe to clear out
  298. // the requestKex channel. This avoids the situation
  299. // where: 1) we consumed our own request for the
  300. // initial kex, and 2) the kex from the remote side
  301. // caused another send on the requestKex channel,
  302. clear:
  303. for {
  304. select {
  305. case <-t.requestKex:
  306. //
  307. default:
  308. break clear
  309. }
  310. }
  311. request.done <- t.writeError
  312. // kex finished. Push packets that we received while
  313. // the kex was in progress. Don't look at t.startKex
  314. // and don't increment writtenSinceKex: if we trigger
  315. // another kex while we are still busy with the last
  316. // one, things will become very confusing.
  317. for _, p := range t.pendingPackets {
  318. t.writeError = t.pushPacket(p)
  319. if t.writeError != nil {
  320. break
  321. }
  322. }
  323. t.pendingPackets = t.pendingPackets[:0]
  324. // Unblock writePacket if waiting for KEX.
  325. t.writeCond.Broadcast()
  326. t.mu.Unlock()
  327. }
  328. // Unblock reader.
  329. t.conn.Close()
  330. // drain startKex channel. We don't service t.requestKex
  331. // because nobody does blocking sends there.
  332. for request := range t.startKex {
  333. request.done <- t.getWriteError()
  334. }
  335. // Mark that the loop is done so that Close can return.
  336. close(t.kexLoopDone)
  337. }
  338. // The protocol uses uint32 for packet counters, so we can't let them
  339. // reach 1<<32. We will actually read and write more packets than
  340. // this, though: the other side may send more packets, and after we
  341. // hit this limit on writing we will send a few more packets for the
  342. // key exchange itself.
  343. const packetRekeyThreshold = (1 << 31)
  344. func (t *handshakeTransport) resetReadThresholds() {
  345. t.readPacketsLeft = packetRekeyThreshold
  346. if t.config.RekeyThreshold > 0 {
  347. t.readBytesLeft = int64(t.config.RekeyThreshold)
  348. } else if t.algorithms != nil {
  349. t.readBytesLeft = t.algorithms.Read.rekeyBytes()
  350. } else {
  351. t.readBytesLeft = 1 << 30
  352. }
  353. }
  354. func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
  355. p, err := t.conn.readPacket()
  356. if err != nil {
  357. return nil, err
  358. }
  359. if t.readPacketsLeft > 0 {
  360. t.readPacketsLeft--
  361. } else {
  362. t.requestKeyExchange()
  363. }
  364. if t.readBytesLeft > 0 {
  365. t.readBytesLeft -= int64(len(p))
  366. } else {
  367. t.requestKeyExchange()
  368. }
  369. if debugHandshake {
  370. t.printPacket(p, false)
  371. }
  372. if first && p[0] != msgKexInit {
  373. return nil, fmt.Errorf("ssh: first packet should be msgKexInit")
  374. }
  375. if p[0] != msgKexInit {
  376. return p, nil
  377. }
  378. firstKex := t.sessionID == nil
  379. kex := pendingKex{
  380. done: make(chan error, 1),
  381. otherInit: p,
  382. }
  383. t.startKex <- &kex
  384. err = <-kex.done
  385. if debugHandshake {
  386. log.Printf("%s exited key exchange (first %v), err %v", t.id(), firstKex, err)
  387. }
  388. if err != nil {
  389. return nil, err
  390. }
  391. t.resetReadThresholds()
  392. // By default, a key exchange is hidden from higher layers by
  393. // translating it into msgIgnore.
  394. successPacket := []byte{msgIgnore}
  395. if firstKex {
  396. // sendKexInit() for the first kex waits for
  397. // msgNewKeys so the authentication process is
  398. // guaranteed to happen over an encrypted transport.
  399. successPacket = []byte{msgNewKeys}
  400. }
  401. return successPacket, nil
  402. }
  403. const (
  404. kexStrictClient = "kex-strict-c-v00@openssh.com"
  405. kexStrictServer = "kex-strict-s-v00@openssh.com"
  406. )
  407. // sendKexInit sends a key change message.
  408. func (t *handshakeTransport) sendKexInit() error {
  409. t.mu.Lock()
  410. defer t.mu.Unlock()
  411. if t.sentInitMsg != nil {
  412. // kexInits may be sent either in response to the other side,
  413. // or because our side wants to initiate a key change, so we
  414. // may have already sent a kexInit. In that case, don't send a
  415. // second kexInit.
  416. return nil
  417. }
  418. msg := &kexInitMsg{
  419. CiphersClientServer: t.config.Ciphers,
  420. CiphersServerClient: t.config.Ciphers,
  421. MACsClientServer: t.config.MACs,
  422. MACsServerClient: t.config.MACs,
  423. CompressionClientServer: supportedCompressions,
  424. CompressionServerClient: supportedCompressions,
  425. }
  426. io.ReadFull(t.config.Rand, msg.Cookie[:])
  427. // We mutate the KexAlgos slice, in order to add the kex-strict extension algorithm,
  428. // and possibly to add the ext-info extension algorithm. Since the slice may be the
  429. // user owned KeyExchanges, we create our own slice in order to avoid using user
  430. // owned memory by mistake.
  431. msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+2) // room for kex-strict and ext-info
  432. msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...)
  433. isServer := len(t.hostKeys) > 0
  434. if isServer {
  435. for _, k := range t.hostKeys {
  436. // If k is a MultiAlgorithmSigner, we restrict the signature
  437. // algorithms. If k is a AlgorithmSigner, presume it supports all
  438. // signature algorithms associated with the key format. If k is not
  439. // an AlgorithmSigner, we can only assume it only supports the
  440. // algorithms that matches the key format. (This means that Sign
  441. // can't pick a different default).
  442. keyFormat := k.PublicKey().Type()
  443. switch s := k.(type) {
  444. case MultiAlgorithmSigner:
  445. for _, algo := range algorithmsForKeyFormat(keyFormat) {
  446. if contains(s.Algorithms(), underlyingAlgo(algo)) {
  447. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algo)
  448. }
  449. }
  450. case AlgorithmSigner:
  451. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, algorithmsForKeyFormat(keyFormat)...)
  452. default:
  453. msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, keyFormat)
  454. }
  455. }
  456. if t.sessionID == nil {
  457. msg.KexAlgos = append(msg.KexAlgos, kexStrictServer)
  458. }
  459. } else {
  460. msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
  461. // As a client we opt in to receiving SSH_MSG_EXT_INFO so we know what
  462. // algorithms the server supports for public key authentication. See RFC
  463. // 8308, Section 2.1.
  464. //
  465. // We also send the strict KEX mode extension algorithm, in order to opt
  466. // into the strict KEX mode.
  467. if firstKeyExchange := t.sessionID == nil; firstKeyExchange {
  468. msg.KexAlgos = append(msg.KexAlgos, "ext-info-c")
  469. msg.KexAlgos = append(msg.KexAlgos, kexStrictClient)
  470. }
  471. }
  472. packet := Marshal(msg)
  473. // writePacket destroys the contents, so save a copy.
  474. packetCopy := make([]byte, len(packet))
  475. copy(packetCopy, packet)
  476. if err := t.pushPacket(packetCopy); err != nil {
  477. return err
  478. }
  479. t.sentInitMsg = msg
  480. t.sentInitPacket = packet
  481. return nil
  482. }
  483. var errSendBannerPhase = errors.New("ssh: SendAuthBanner outside of authentication phase")
  484. func (t *handshakeTransport) writePacket(p []byte) error {
  485. t.mu.Lock()
  486. defer t.mu.Unlock()
  487. switch p[0] {
  488. case msgKexInit:
  489. return errors.New("ssh: only handshakeTransport can send kexInit")
  490. case msgNewKeys:
  491. return errors.New("ssh: only handshakeTransport can send newKeys")
  492. case msgUserAuthBanner:
  493. if t.userAuthComplete {
  494. return errSendBannerPhase
  495. }
  496. case msgUserAuthSuccess:
  497. t.userAuthComplete = true
  498. }
  499. if t.writeError != nil {
  500. return t.writeError
  501. }
  502. if t.sentInitMsg != nil {
  503. if len(t.pendingPackets) < maxPendingPackets {
  504. // Copy the packet so the writer can reuse the buffer.
  505. cp := make([]byte, len(p))
  506. copy(cp, p)
  507. t.pendingPackets = append(t.pendingPackets, cp)
  508. return nil
  509. }
  510. for t.sentInitMsg != nil {
  511. // Block and wait for KEX to complete or an error.
  512. t.writeCond.Wait()
  513. if t.writeError != nil {
  514. return t.writeError
  515. }
  516. }
  517. }
  518. if t.writeBytesLeft > 0 {
  519. t.writeBytesLeft -= int64(len(p))
  520. } else {
  521. t.requestKeyExchange()
  522. }
  523. if t.writePacketsLeft > 0 {
  524. t.writePacketsLeft--
  525. } else {
  526. t.requestKeyExchange()
  527. }
  528. if err := t.pushPacket(p); err != nil {
  529. t.writeError = err
  530. t.writeCond.Broadcast()
  531. }
  532. return nil
  533. }
  534. func (t *handshakeTransport) Close() error {
  535. // Close the connection. This should cause the readLoop goroutine to wake up
  536. // and close t.startKex, which will shut down kexLoop if running.
  537. err := t.conn.Close()
  538. // Wait for the kexLoop goroutine to complete.
  539. // At that point we know that the readLoop goroutine is complete too,
  540. // because kexLoop itself waits for readLoop to close the startKex channel.
  541. <-t.kexLoopDone
  542. return err
  543. }
  544. func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
  545. if debugHandshake {
  546. log.Printf("%s entered key exchange", t.id())
  547. }
  548. otherInit := &kexInitMsg{}
  549. if err := Unmarshal(otherInitPacket, otherInit); err != nil {
  550. return err
  551. }
  552. magics := handshakeMagics{
  553. clientVersion: t.clientVersion,
  554. serverVersion: t.serverVersion,
  555. clientKexInit: otherInitPacket,
  556. serverKexInit: t.sentInitPacket,
  557. }
  558. clientInit := otherInit
  559. serverInit := t.sentInitMsg
  560. isClient := len(t.hostKeys) == 0
  561. if isClient {
  562. clientInit, serverInit = serverInit, clientInit
  563. magics.clientKexInit = t.sentInitPacket
  564. magics.serverKexInit = otherInitPacket
  565. }
  566. var err error
  567. t.algorithms, err = findAgreedAlgorithms(isClient, clientInit, serverInit)
  568. if err != nil {
  569. return err
  570. }
  571. if t.sessionID == nil && ((isClient && contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && contains(clientInit.KexAlgos, kexStrictClient))) {
  572. t.strictMode = true
  573. if err := t.conn.setStrictMode(); err != nil {
  574. return err
  575. }
  576. }
  577. // We don't send FirstKexFollows, but we handle receiving it.
  578. //
  579. // RFC 4253 section 7 defines the kex and the agreement method for
  580. // first_kex_packet_follows. It states that the guessed packet
  581. // should be ignored if the "kex algorithm and/or the host
  582. // key algorithm is guessed wrong (server and client have
  583. // different preferred algorithm), or if any of the other
  584. // algorithms cannot be agreed upon". The other algorithms have
  585. // already been checked above so the kex algorithm and host key
  586. // algorithm are checked here.
  587. if otherInit.FirstKexFollows && (clientInit.KexAlgos[0] != serverInit.KexAlgos[0] || clientInit.ServerHostKeyAlgos[0] != serverInit.ServerHostKeyAlgos[0]) {
  588. // other side sent a kex message for the wrong algorithm,
  589. // which we have to ignore.
  590. if _, err := t.conn.readPacket(); err != nil {
  591. return err
  592. }
  593. }
  594. kex, ok := kexAlgoMap[t.algorithms.KeyExchange]
  595. if !ok {
  596. return fmt.Errorf("ssh: unexpected key exchange algorithm %v", t.algorithms.KeyExchange)
  597. }
  598. var result *kexResult
  599. if len(t.hostKeys) > 0 {
  600. result, err = t.server(kex, &magics)
  601. } else {
  602. result, err = t.client(kex, &magics)
  603. }
  604. if err != nil {
  605. return err
  606. }
  607. firstKeyExchange := t.sessionID == nil
  608. if firstKeyExchange {
  609. t.sessionID = result.H
  610. }
  611. result.SessionID = t.sessionID
  612. if err := t.conn.prepareKeyChange(t.algorithms, result); err != nil {
  613. return err
  614. }
  615. if err = t.conn.writePacket([]byte{msgNewKeys}); err != nil {
  616. return err
  617. }
  618. // On the server side, after the first SSH_MSG_NEWKEYS, send a SSH_MSG_EXT_INFO
  619. // message with the server-sig-algs extension if the client supports it. See
  620. // RFC 8308, Sections 2.4 and 3.1, and [PROTOCOL], Section 1.9.
  621. if !isClient && firstKeyExchange && contains(clientInit.KexAlgos, "ext-info-c") {
  622. supportedPubKeyAuthAlgosList := strings.Join(t.publicKeyAuthAlgorithms, ",")
  623. extInfo := &extInfoMsg{
  624. NumExtensions: 2,
  625. Payload: make([]byte, 0, 4+15+4+len(supportedPubKeyAuthAlgosList)+4+16+4+1),
  626. }
  627. extInfo.Payload = appendInt(extInfo.Payload, len("server-sig-algs"))
  628. extInfo.Payload = append(extInfo.Payload, "server-sig-algs"...)
  629. extInfo.Payload = appendInt(extInfo.Payload, len(supportedPubKeyAuthAlgosList))
  630. extInfo.Payload = append(extInfo.Payload, supportedPubKeyAuthAlgosList...)
  631. extInfo.Payload = appendInt(extInfo.Payload, len("ping@openssh.com"))
  632. extInfo.Payload = append(extInfo.Payload, "ping@openssh.com"...)
  633. extInfo.Payload = appendInt(extInfo.Payload, 1)
  634. extInfo.Payload = append(extInfo.Payload, "0"...)
  635. if err := t.conn.writePacket(Marshal(extInfo)); err != nil {
  636. return err
  637. }
  638. }
  639. if packet, err := t.conn.readPacket(); err != nil {
  640. return err
  641. } else if packet[0] != msgNewKeys {
  642. return unexpectedMessageError(msgNewKeys, packet[0])
  643. }
  644. if firstKeyExchange {
  645. // Indicates to the transport that the first key exchange is completed
  646. // after receiving SSH_MSG_NEWKEYS.
  647. t.conn.setInitialKEXDone()
  648. }
  649. return nil
  650. }
  651. // algorithmSignerWrapper is an AlgorithmSigner that only supports the default
  652. // key format algorithm.
  653. //
  654. // This is technically a violation of the AlgorithmSigner interface, but it
  655. // should be unreachable given where we use this. Anyway, at least it returns an
  656. // error instead of panicing or producing an incorrect signature.
  657. type algorithmSignerWrapper struct {
  658. Signer
  659. }
  660. func (a algorithmSignerWrapper) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  661. if algorithm != underlyingAlgo(a.PublicKey().Type()) {
  662. return nil, errors.New("ssh: internal error: algorithmSignerWrapper invoked with non-default algorithm")
  663. }
  664. return a.Sign(rand, data)
  665. }
  666. func pickHostKey(hostKeys []Signer, algo string) AlgorithmSigner {
  667. for _, k := range hostKeys {
  668. if s, ok := k.(MultiAlgorithmSigner); ok {
  669. if !contains(s.Algorithms(), underlyingAlgo(algo)) {
  670. continue
  671. }
  672. }
  673. if algo == k.PublicKey().Type() {
  674. return algorithmSignerWrapper{k}
  675. }
  676. k, ok := k.(AlgorithmSigner)
  677. if !ok {
  678. continue
  679. }
  680. for _, a := range algorithmsForKeyFormat(k.PublicKey().Type()) {
  681. if algo == a {
  682. return k
  683. }
  684. }
  685. }
  686. return nil
  687. }
  688. func (t *handshakeTransport) server(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
  689. hostKey := pickHostKey(t.hostKeys, t.algorithms.HostKey)
  690. if hostKey == nil {
  691. return nil, errors.New("ssh: internal error: negotiated unsupported signature type")
  692. }
  693. r, err := kex.Server(t.conn, t.config.Rand, magics, hostKey, t.algorithms.HostKey)
  694. return r, err
  695. }
  696. func (t *handshakeTransport) client(kex kexAlgorithm, magics *handshakeMagics) (*kexResult, error) {
  697. result, err := kex.Client(t.conn, t.config.Rand, magics)
  698. if err != nil {
  699. return nil, err
  700. }
  701. hostKey, err := ParsePublicKey(result.HostKey)
  702. if err != nil {
  703. return nil, err
  704. }
  705. if err := verifyHostKeySignature(hostKey, t.algorithms.HostKey, result); err != nil {
  706. return nil, err
  707. }
  708. err = t.hostKeyCallback(t.dialAddress, t.remoteAddr, hostKey)
  709. if err != nil {
  710. return nil, err
  711. }
  712. return result, nil
  713. }