client.go 15 KB

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