client.go 16 KB

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