client.go 15 KB

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