handshake.go 22 KB

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