client.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. // Copyright 2011 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"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rand"
  10. "encoding/binary"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "math/big"
  15. "net"
  16. "sync"
  17. )
  18. // clientVersion is the default identification string that the client will use.
  19. var clientVersion = []byte("SSH-2.0-Go")
  20. // ClientConn represents the client side of an SSH connection.
  21. type ClientConn struct {
  22. *transport
  23. config *ClientConfig
  24. chanList // channels associated with this connection
  25. forwardList // forwarded tcpip connections from the remote side
  26. globalRequest
  27. // Address as passed to the Dial function.
  28. dialAddress string
  29. serverVersion string
  30. }
  31. type globalRequest struct {
  32. sync.Mutex
  33. response chan interface{}
  34. }
  35. // Client returns a new SSH client connection using c as the underlying transport.
  36. func Client(c net.Conn, config *ClientConfig) (*ClientConn, error) {
  37. return clientWithAddress(c, "", config)
  38. }
  39. func clientWithAddress(c net.Conn, addr string, config *ClientConfig) (*ClientConn, error) {
  40. conn := &ClientConn{
  41. transport: newTransport(c, config.rand()),
  42. config: config,
  43. globalRequest: globalRequest{response: make(chan interface{}, 1)},
  44. dialAddress: addr,
  45. }
  46. if err := conn.handshake(); err != nil {
  47. conn.Close()
  48. return nil, fmt.Errorf("handshake failed: %v", err)
  49. }
  50. go conn.mainLoop()
  51. return conn, nil
  52. }
  53. // handshake performs the client side key exchange. See RFC 4253 Section 7.
  54. func (c *ClientConn) handshake() error {
  55. var magics handshakeMagics
  56. var version []byte
  57. if len(c.config.ClientVersion) > 0 {
  58. version = []byte(c.config.ClientVersion)
  59. } else {
  60. version = clientVersion
  61. }
  62. magics.clientVersion = version
  63. version = append(version, '\r', '\n')
  64. if _, err := c.Write(version); err != nil {
  65. return err
  66. }
  67. if err := c.Flush(); err != nil {
  68. return err
  69. }
  70. // read remote server version
  71. version, err := readVersion(c)
  72. if err != nil {
  73. return err
  74. }
  75. magics.serverVersion = version
  76. c.serverVersion = string(version)
  77. clientKexInit := kexInitMsg{
  78. KexAlgos: c.config.Crypto.kexes(),
  79. ServerHostKeyAlgos: supportedHostKeyAlgos,
  80. CiphersClientServer: c.config.Crypto.ciphers(),
  81. CiphersServerClient: c.config.Crypto.ciphers(),
  82. MACsClientServer: c.config.Crypto.macs(),
  83. MACsServerClient: c.config.Crypto.macs(),
  84. CompressionClientServer: supportedCompressions,
  85. CompressionServerClient: supportedCompressions,
  86. }
  87. kexInitPacket := marshal(msgKexInit, clientKexInit)
  88. magics.clientKexInit = kexInitPacket
  89. if err := c.writePacket(kexInitPacket); err != nil {
  90. return err
  91. }
  92. packet, err := c.readPacket()
  93. if err != nil {
  94. return err
  95. }
  96. magics.serverKexInit = packet
  97. var serverKexInit kexInitMsg
  98. if err = unmarshal(&serverKexInit, packet, msgKexInit); err != nil {
  99. return err
  100. }
  101. kexAlgo, hostKeyAlgo, ok := findAgreedAlgorithms(c.transport, &clientKexInit, &serverKexInit)
  102. if !ok {
  103. return errors.New("ssh: no common algorithms")
  104. }
  105. if serverKexInit.FirstKexFollows && kexAlgo != serverKexInit.KexAlgos[0] {
  106. // The server sent a Kex message for the wrong algorithm,
  107. // which we have to ignore.
  108. if _, err := c.readPacket(); err != nil {
  109. return err
  110. }
  111. }
  112. var result *kexResult
  113. switch kexAlgo {
  114. case kexAlgoECDH256:
  115. result, err = c.kexECDH(elliptic.P256(), &magics, hostKeyAlgo)
  116. case kexAlgoECDH384:
  117. result, err = c.kexECDH(elliptic.P384(), &magics, hostKeyAlgo)
  118. case kexAlgoECDH521:
  119. result, err = c.kexECDH(elliptic.P521(), &magics, hostKeyAlgo)
  120. case kexAlgoDH14SHA1:
  121. dhGroup14Once.Do(initDHGroup14)
  122. result, err = c.kexDH(crypto.SHA1, dhGroup14, &magics, hostKeyAlgo)
  123. case kexAlgoDH1SHA1:
  124. dhGroup1Once.Do(initDHGroup1)
  125. result, err = c.kexDH(crypto.SHA1, dhGroup1, &magics, hostKeyAlgo)
  126. default:
  127. err = fmt.Errorf("ssh: unexpected key exchange algorithm %v", kexAlgo)
  128. }
  129. if err != nil {
  130. return err
  131. }
  132. err = verifyHostKeySignature(hostKeyAlgo, result.HostKey, result.H, result.Signature)
  133. if err != nil {
  134. return err
  135. }
  136. if checker := c.config.HostKeyChecker; checker != nil {
  137. err = checker.Check(c.dialAddress, c.RemoteAddr(), hostKeyAlgo, result.HostKey)
  138. if err != nil {
  139. return err
  140. }
  141. }
  142. if err = c.writePacket([]byte{msgNewKeys}); err != nil {
  143. return err
  144. }
  145. if err = c.transport.writer.setupKeys(clientKeys, result.K, result.H, result.H, result.Hash); err != nil {
  146. return err
  147. }
  148. if packet, err = c.readPacket(); err != nil {
  149. return err
  150. }
  151. if packet[0] != msgNewKeys {
  152. return UnexpectedMessageError{msgNewKeys, packet[0]}
  153. }
  154. if err := c.transport.reader.setupKeys(serverKeys, result.K, result.H, result.H, result.Hash); err != nil {
  155. return err
  156. }
  157. return c.authenticate(result.H)
  158. }
  159. // kexECDH performs Elliptic Curve Diffie-Hellman key exchange as
  160. // described in RFC 5656, section 4.
  161. func (c *ClientConn) kexECDH(curve elliptic.Curve, magics *handshakeMagics, hostKeyAlgo string) (*kexResult, error) {
  162. ephKey, err := ecdsa.GenerateKey(curve, c.config.rand())
  163. if err != nil {
  164. return nil, err
  165. }
  166. kexInit := kexECDHInitMsg{
  167. ClientPubKey: elliptic.Marshal(curve, ephKey.PublicKey.X, ephKey.PublicKey.Y),
  168. }
  169. serialized := marshal(msgKexECDHInit, kexInit)
  170. if err := c.writePacket(serialized); err != nil {
  171. return nil, err
  172. }
  173. packet, err := c.readPacket()
  174. if err != nil {
  175. return nil, err
  176. }
  177. var reply kexECDHReplyMsg
  178. if err = unmarshal(&reply, packet, msgKexECDHReply); err != nil {
  179. return nil, err
  180. }
  181. x, y := elliptic.Unmarshal(curve, reply.EphemeralPubKey)
  182. if x == nil {
  183. return nil, errors.New("ssh: elliptic.Unmarshal failure")
  184. }
  185. if !validateECPublicKey(curve, x, y) {
  186. return nil, errors.New("ssh: ephemeral server key not on curve")
  187. }
  188. // generate shared secret
  189. secret, _ := curve.ScalarMult(x, y, ephKey.D.Bytes())
  190. hashFunc := ecHash(curve)
  191. h := hashFunc.New()
  192. writeString(h, magics.clientVersion)
  193. writeString(h, magics.serverVersion)
  194. writeString(h, magics.clientKexInit)
  195. writeString(h, magics.serverKexInit)
  196. writeString(h, reply.HostKey)
  197. writeString(h, kexInit.ClientPubKey)
  198. writeString(h, reply.EphemeralPubKey)
  199. K := make([]byte, intLength(secret))
  200. marshalInt(K, secret)
  201. h.Write(K)
  202. return &kexResult{
  203. H: h.Sum(nil),
  204. K: K,
  205. HostKey: reply.HostKey,
  206. Signature: reply.Signature,
  207. Hash: hashFunc,
  208. }, nil
  209. }
  210. // Verify the host key obtained in the key exchange.
  211. func verifyHostKeySignature(hostKeyAlgo string, hostKeyBytes []byte, data []byte, signature []byte) error {
  212. hostKey, rest, ok := ParsePublicKey(hostKeyBytes)
  213. if len(rest) > 0 || !ok {
  214. return errors.New("ssh: could not parse hostkey")
  215. }
  216. sig, rest, ok := parseSignatureBody(signature)
  217. if len(rest) > 0 || !ok {
  218. return errors.New("ssh: signature parse error")
  219. }
  220. if sig.Format != hostKeyAlgo {
  221. return fmt.Errorf("ssh: unexpected signature type %q", sig.Format)
  222. }
  223. if !hostKey.Verify(data, sig.Blob) {
  224. return errors.New("ssh: host key signature error")
  225. }
  226. return nil
  227. }
  228. // kexResult captures the outcome of a key exchange.
  229. type kexResult struct {
  230. // Session hash. See also RFC 4253, section 8.
  231. H []byte
  232. // Shared secret. See also RFC 4253, section 8.
  233. K []byte
  234. // Host key as hashed into H
  235. HostKey []byte
  236. // Signature of H
  237. Signature []byte
  238. // Hash function that was used.
  239. Hash crypto.Hash
  240. }
  241. // kexDH performs Diffie-Hellman key agreement on a ClientConn.
  242. func (c *ClientConn) kexDH(hashFunc crypto.Hash, group *dhGroup, magics *handshakeMagics, hostKeyAlgo string) (*kexResult, error) {
  243. x, err := rand.Int(c.config.rand(), group.p)
  244. if err != nil {
  245. return nil, err
  246. }
  247. X := new(big.Int).Exp(group.g, x, group.p)
  248. kexDHInit := kexDHInitMsg{
  249. X: X,
  250. }
  251. if err := c.writePacket(marshal(msgKexDHInit, kexDHInit)); err != nil {
  252. return nil, err
  253. }
  254. packet, err := c.readPacket()
  255. if err != nil {
  256. return nil, err
  257. }
  258. var kexDHReply kexDHReplyMsg
  259. if err = unmarshal(&kexDHReply, packet, msgKexDHReply); err != nil {
  260. return nil, err
  261. }
  262. kInt, err := group.diffieHellman(kexDHReply.Y, x)
  263. if err != nil {
  264. return nil, err
  265. }
  266. h := hashFunc.New()
  267. writeString(h, magics.clientVersion)
  268. writeString(h, magics.serverVersion)
  269. writeString(h, magics.clientKexInit)
  270. writeString(h, magics.serverKexInit)
  271. writeString(h, kexDHReply.HostKey)
  272. writeInt(h, X)
  273. writeInt(h, kexDHReply.Y)
  274. K := make([]byte, intLength(kInt))
  275. marshalInt(K, kInt)
  276. h.Write(K)
  277. return &kexResult{
  278. H: h.Sum(nil),
  279. K: K,
  280. HostKey: kexDHReply.HostKey,
  281. Signature: kexDHReply.Signature,
  282. Hash: hashFunc,
  283. }, nil
  284. }
  285. // mainLoop reads incoming messages and routes channel messages
  286. // to their respective ClientChans.
  287. func (c *ClientConn) mainLoop() {
  288. defer func() {
  289. c.Close()
  290. c.chanList.closeAll()
  291. c.forwardList.closeAll()
  292. }()
  293. for {
  294. packet, err := c.readPacket()
  295. if err != nil {
  296. break
  297. }
  298. // TODO(dfc) A note on blocking channel use.
  299. // The msg, data and dataExt channels of a clientChan can
  300. // cause this loop to block indefinately if the consumer does
  301. // not service them.
  302. switch packet[0] {
  303. case msgChannelData:
  304. if len(packet) < 9 {
  305. // malformed data packet
  306. return
  307. }
  308. remoteId := binary.BigEndian.Uint32(packet[1:5])
  309. length := binary.BigEndian.Uint32(packet[5:9])
  310. packet = packet[9:]
  311. if length != uint32(len(packet)) {
  312. return
  313. }
  314. ch, ok := c.getChan(remoteId)
  315. if !ok {
  316. return
  317. }
  318. ch.stdout.write(packet)
  319. case msgChannelExtendedData:
  320. if len(packet) < 13 {
  321. // malformed data packet
  322. return
  323. }
  324. remoteId := binary.BigEndian.Uint32(packet[1:5])
  325. datatype := binary.BigEndian.Uint32(packet[5:9])
  326. length := binary.BigEndian.Uint32(packet[9:13])
  327. packet = packet[13:]
  328. if length != uint32(len(packet)) {
  329. return
  330. }
  331. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  332. // for stderr on interactive sessions. Other data types are
  333. // silently discarded.
  334. if datatype == 1 {
  335. ch, ok := c.getChan(remoteId)
  336. if !ok {
  337. return
  338. }
  339. ch.stderr.write(packet)
  340. }
  341. default:
  342. decoded, err := decode(packet)
  343. if err != nil {
  344. if _, ok := err.(UnexpectedMessageError); ok {
  345. fmt.Printf("mainLoop: unexpected message: %v\n", err)
  346. continue
  347. }
  348. return
  349. }
  350. switch msg := decoded.(type) {
  351. case *channelOpenMsg:
  352. c.handleChanOpen(msg)
  353. case *channelOpenConfirmMsg:
  354. ch, ok := c.getChan(msg.PeersId)
  355. if !ok {
  356. return
  357. }
  358. ch.msg <- msg
  359. case *channelOpenFailureMsg:
  360. ch, ok := c.getChan(msg.PeersId)
  361. if !ok {
  362. return
  363. }
  364. ch.msg <- msg
  365. case *channelCloseMsg:
  366. ch, ok := c.getChan(msg.PeersId)
  367. if !ok {
  368. return
  369. }
  370. ch.Close()
  371. close(ch.msg)
  372. c.chanList.remove(msg.PeersId)
  373. case *channelEOFMsg:
  374. ch, ok := c.getChan(msg.PeersId)
  375. if !ok {
  376. return
  377. }
  378. ch.stdout.eof()
  379. // RFC 4254 is mute on how EOF affects dataExt messages but
  380. // it is logical to signal EOF at the same time.
  381. ch.stderr.eof()
  382. case *channelRequestSuccessMsg:
  383. ch, ok := c.getChan(msg.PeersId)
  384. if !ok {
  385. return
  386. }
  387. ch.msg <- msg
  388. case *channelRequestFailureMsg:
  389. ch, ok := c.getChan(msg.PeersId)
  390. if !ok {
  391. return
  392. }
  393. ch.msg <- msg
  394. case *channelRequestMsg:
  395. ch, ok := c.getChan(msg.PeersId)
  396. if !ok {
  397. return
  398. }
  399. ch.msg <- msg
  400. case *windowAdjustMsg:
  401. ch, ok := c.getChan(msg.PeersId)
  402. if !ok {
  403. return
  404. }
  405. if !ch.remoteWin.add(msg.AdditionalBytes) {
  406. // invalid window update
  407. return
  408. }
  409. case *globalRequestMsg:
  410. // This handles keepalive messages and matches
  411. // the behaviour of OpenSSH.
  412. if msg.WantReply {
  413. c.writePacket(marshal(msgRequestFailure, globalRequestFailureMsg{}))
  414. }
  415. case *globalRequestSuccessMsg, *globalRequestFailureMsg:
  416. c.globalRequest.response <- msg
  417. case *disconnectMsg:
  418. return
  419. default:
  420. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  421. }
  422. }
  423. }
  424. }
  425. // Handle channel open messages from the remote side.
  426. func (c *ClientConn) handleChanOpen(msg *channelOpenMsg) {
  427. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  428. c.sendConnectionFailed(msg.PeersId)
  429. }
  430. switch msg.ChanType {
  431. case "forwarded-tcpip":
  432. laddr, rest, ok := parseTCPAddr(msg.TypeSpecificData)
  433. if !ok {
  434. // invalid request
  435. c.sendConnectionFailed(msg.PeersId)
  436. return
  437. }
  438. l, ok := c.forwardList.lookup(*laddr)
  439. if !ok {
  440. // TODO: print on a more structured log.
  441. fmt.Println("could not find forward list entry for", laddr)
  442. // Section 7.2, implementations MUST reject suprious incoming
  443. // connections.
  444. c.sendConnectionFailed(msg.PeersId)
  445. return
  446. }
  447. raddr, rest, ok := parseTCPAddr(rest)
  448. if !ok {
  449. // invalid request
  450. c.sendConnectionFailed(msg.PeersId)
  451. return
  452. }
  453. ch := c.newChan(c.transport)
  454. ch.remoteId = msg.PeersId
  455. ch.remoteWin.add(msg.PeersWindow)
  456. ch.maxPacket = msg.MaxPacketSize
  457. m := channelOpenConfirmMsg{
  458. PeersId: ch.remoteId,
  459. MyId: ch.localId,
  460. MyWindow: 1 << 14,
  461. // As per RFC 4253 6.1, 32k is also the minimum.
  462. MaxPacketSize: 1 << 15,
  463. }
  464. c.writePacket(marshal(msgChannelOpenConfirm, m))
  465. l <- forward{ch, raddr}
  466. default:
  467. // unknown channel type
  468. m := channelOpenFailureMsg{
  469. PeersId: msg.PeersId,
  470. Reason: UnknownChannelType,
  471. Message: fmt.Sprintf("unknown channel type: %v", msg.ChanType),
  472. Language: "en_US.UTF-8",
  473. }
  474. c.writePacket(marshal(msgChannelOpenFailure, m))
  475. }
  476. }
  477. // sendGlobalRequest sends a global request message as specified
  478. // in RFC4254 section 4. To correctly synchronise messages, a lock
  479. // is held internally until a response is returned.
  480. func (c *ClientConn) sendGlobalRequest(m interface{}) (*globalRequestSuccessMsg, error) {
  481. c.globalRequest.Lock()
  482. defer c.globalRequest.Unlock()
  483. if err := c.writePacket(marshal(msgGlobalRequest, m)); err != nil {
  484. return nil, err
  485. }
  486. r := <-c.globalRequest.response
  487. if r, ok := r.(*globalRequestSuccessMsg); ok {
  488. return r, nil
  489. }
  490. return nil, errors.New("request failed")
  491. }
  492. // sendConnectionFailed rejects an incoming channel identified
  493. // by remoteId.
  494. func (c *ClientConn) sendConnectionFailed(remoteId uint32) error {
  495. m := channelOpenFailureMsg{
  496. PeersId: remoteId,
  497. Reason: ConnectionFailed,
  498. Message: "invalid request",
  499. Language: "en_US.UTF-8",
  500. }
  501. return c.writePacket(marshal(msgChannelOpenFailure, m))
  502. }
  503. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  504. // RFC 4254 section 7.2 is mute on what to do if parsing fails but the forwardlist
  505. // requires a valid *net.TCPAddr to operate, so we enforce that restriction here.
  506. func parseTCPAddr(b []byte) (*net.TCPAddr, []byte, bool) {
  507. addr, b, ok := parseString(b)
  508. if !ok {
  509. return nil, b, false
  510. }
  511. port, b, ok := parseUint32(b)
  512. if !ok {
  513. return nil, b, false
  514. }
  515. ip := net.ParseIP(string(addr))
  516. if ip == nil {
  517. return nil, b, false
  518. }
  519. return &net.TCPAddr{IP: ip, Port: int(port)}, b, true
  520. }
  521. // Dial connects to the given network address using net.Dial and
  522. // then initiates a SSH handshake, returning the resulting client connection.
  523. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  524. conn, err := net.Dial(network, addr)
  525. if err != nil {
  526. return nil, err
  527. }
  528. return clientWithAddress(conn, addr, config)
  529. }
  530. // A ClientConfig structure is used to configure a ClientConn. After one has
  531. // been passed to an SSH function it must not be modified.
  532. type ClientConfig struct {
  533. // Rand provides the source of entropy for key exchange. If Rand is
  534. // nil, the cryptographic random reader in package crypto/rand will
  535. // be used.
  536. Rand io.Reader
  537. // The username to authenticate.
  538. User string
  539. // A slice of ClientAuth methods. Only the first instance
  540. // of a particular RFC 4252 method will be used during authentication.
  541. Auth []ClientAuth
  542. // HostKeyChecker, if not nil, is called during the cryptographic
  543. // handshake to validate the server's host key. A nil HostKeyChecker
  544. // implies that all host keys are accepted.
  545. HostKeyChecker HostKeyChecker
  546. // Cryptographic-related configuration.
  547. Crypto CryptoConfig
  548. // The identification string that will be used for the connection.
  549. // If empty, a reasonable default is used.
  550. ClientVersion string
  551. }
  552. func (c *ClientConfig) rand() io.Reader {
  553. if c.Rand == nil {
  554. return rand.Reader
  555. }
  556. return c.Rand
  557. }
  558. // Thread safe channel list.
  559. type chanList struct {
  560. // protects concurrent access to chans
  561. sync.Mutex
  562. // chans are indexed by the local id of the channel, clientChan.localId.
  563. // The PeersId value of messages received by ClientConn.mainLoop is
  564. // used to locate the right local clientChan in this slice.
  565. chans []*clientChan
  566. }
  567. // Allocate a new ClientChan with the next avail local id.
  568. func (c *chanList) newChan(t *transport) *clientChan {
  569. c.Lock()
  570. defer c.Unlock()
  571. for i := range c.chans {
  572. if c.chans[i] == nil {
  573. ch := newClientChan(t, uint32(i))
  574. c.chans[i] = ch
  575. return ch
  576. }
  577. }
  578. i := len(c.chans)
  579. ch := newClientChan(t, uint32(i))
  580. c.chans = append(c.chans, ch)
  581. return ch
  582. }
  583. func (c *chanList) getChan(id uint32) (*clientChan, bool) {
  584. c.Lock()
  585. defer c.Unlock()
  586. if id >= uint32(len(c.chans)) {
  587. return nil, false
  588. }
  589. return c.chans[id], true
  590. }
  591. func (c *chanList) remove(id uint32) {
  592. c.Lock()
  593. defer c.Unlock()
  594. c.chans[id] = nil
  595. }
  596. func (c *chanList) closeAll() {
  597. c.Lock()
  598. defer c.Unlock()
  599. for _, ch := range c.chans {
  600. if ch == nil {
  601. continue
  602. }
  603. ch.Close()
  604. close(ch.msg)
  605. }
  606. }