handshake.go 20 KB

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