handshake.go 20 KB

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