client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. // TODO(dfc) signal the underlying close to all channels
  165. defer c.Close()
  166. for {
  167. packet, err := c.readPacket()
  168. if err != nil {
  169. break
  170. }
  171. // TODO(dfc) A note on blocking channel use.
  172. // The msg, data and dataExt channels of a clientChan can
  173. // cause this loop to block indefinately if the consumer does
  174. // not service them.
  175. switch packet[0] {
  176. case msgChannelData:
  177. if len(packet) < 9 {
  178. // malformed data packet
  179. break
  180. }
  181. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  182. if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 {
  183. packet = packet[9:]
  184. c.getChan(peersId).stdout.handleData(packet[:length])
  185. }
  186. case msgChannelExtendedData:
  187. if len(packet) < 13 {
  188. // malformed data packet
  189. break
  190. }
  191. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  192. datatype := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  193. if length := int(packet[9])<<24 | int(packet[10])<<16 | int(packet[11])<<8 | int(packet[12]); length > 0 {
  194. packet = packet[13:]
  195. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  196. // for stderr on interactive sessions. Other data types are
  197. // silently discarded.
  198. if datatype == 1 {
  199. c.getChan(peersId).stderr.handleData(packet[:length])
  200. }
  201. }
  202. default:
  203. switch msg := decode(packet).(type) {
  204. case *channelOpenMsg:
  205. c.getChan(msg.PeersId).msg <- msg
  206. case *channelOpenConfirmMsg:
  207. c.getChan(msg.PeersId).msg <- msg
  208. case *channelOpenFailureMsg:
  209. c.getChan(msg.PeersId).msg <- msg
  210. case *channelCloseMsg:
  211. ch := c.getChan(msg.PeersId)
  212. ch.theyClosed = true
  213. ch.stdout.eof()
  214. ch.stderr.eof()
  215. close(ch.msg)
  216. if !ch.weClosed {
  217. ch.weClosed = true
  218. ch.sendClose()
  219. }
  220. c.chanlist.remove(msg.PeersId)
  221. case *channelEOFMsg:
  222. ch := c.getChan(msg.PeersId)
  223. ch.stdout.eof()
  224. // RFC 4254 is mute on how EOF affects dataExt messages but
  225. // it is logical to signal EOF at the same time.
  226. ch.stderr.eof()
  227. case *channelRequestSuccessMsg:
  228. c.getChan(msg.PeersId).msg <- msg
  229. case *channelRequestFailureMsg:
  230. c.getChan(msg.PeersId).msg <- msg
  231. case *channelRequestMsg:
  232. c.getChan(msg.PeersId).msg <- msg
  233. case *windowAdjustMsg:
  234. if !c.getChan(msg.PeersId).stdin.win.add(msg.AdditionalBytes) {
  235. // invalid window update
  236. break
  237. }
  238. case *disconnectMsg:
  239. break
  240. default:
  241. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  242. }
  243. }
  244. }
  245. }
  246. // Dial connects to the given network address using net.Dial and
  247. // then initiates a SSH handshake, returning the resulting client connection.
  248. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  249. conn, err := net.Dial(network, addr)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return Client(conn, config)
  254. }
  255. // A ClientConfig structure is used to configure a ClientConn. After one has
  256. // been passed to an SSH function it must not be modified.
  257. type ClientConfig struct {
  258. // Rand provides the source of entropy for key exchange. If Rand is
  259. // nil, the cryptographic random reader in package crypto/rand will
  260. // be used.
  261. Rand io.Reader
  262. // The username to authenticate.
  263. User string
  264. // A slice of ClientAuth methods. Only the first instance
  265. // of a particular RFC 4252 method will be used during authentication.
  266. Auth []ClientAuth
  267. // Cryptographic-related configuration.
  268. Crypto CryptoConfig
  269. }
  270. func (c *ClientConfig) rand() io.Reader {
  271. if c.Rand == nil {
  272. return rand.Reader
  273. }
  274. return c.Rand
  275. }
  276. // A clientChan represents a single RFC 4254 channel that is multiplexed
  277. // over a single SSH connection.
  278. type clientChan struct {
  279. packetWriter
  280. id, peersId uint32
  281. stdin *chanWriter // receives window adjustments
  282. stdout *chanReader // receives the payload of channelData messages
  283. stderr *chanReader // receives the payload of channelExtendedData messages
  284. msg chan interface{} // incoming messages
  285. theyClosed bool // indicates the close msg has been received from the remote side
  286. weClosed bool // incidates the close msg has been sent from our side
  287. }
  288. // newClientChan returns a partially constructed *clientChan
  289. // using the local id provided. To be usable clientChan.peersId
  290. // needs to be assigned once known.
  291. func newClientChan(t *transport, id uint32) *clientChan {
  292. c := &clientChan{
  293. packetWriter: t,
  294. id: id,
  295. msg: make(chan interface{}, 16),
  296. }
  297. c.stdin = &chanWriter{
  298. win: &window{Cond: sync.NewCond(new(sync.Mutex))},
  299. clientChan: c,
  300. }
  301. c.stdout = &chanReader{
  302. data: make(chan []byte, 16),
  303. clientChan: c,
  304. }
  305. c.stderr = &chanReader{
  306. data: make(chan []byte, 16),
  307. clientChan: c,
  308. }
  309. return c
  310. }
  311. // waitForChannelOpenResponse, if successful, fills out
  312. // the peerId and records any initial window advertisement.
  313. func (c *clientChan) waitForChannelOpenResponse() error {
  314. switch msg := (<-c.msg).(type) {
  315. case *channelOpenConfirmMsg:
  316. // fixup peersId field
  317. c.peersId = msg.MyId
  318. c.stdin.win.add(msg.MyWindow)
  319. return nil
  320. case *channelOpenFailureMsg:
  321. return errors.New(safeString(msg.Message))
  322. }
  323. return errors.New("ssh: unexpected packet")
  324. }
  325. // sendEOF sends EOF to the server. RFC 4254 Section 5.3
  326. func (c *clientChan) sendEOF() error {
  327. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  328. PeersId: c.peersId,
  329. }))
  330. }
  331. // sendClose signals the intent to close the channel.
  332. func (c *clientChan) sendClose() error {
  333. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  334. PeersId: c.peersId,
  335. }))
  336. }
  337. // Close closes the channel. This does not close the underlying connection.
  338. func (c *clientChan) Close() error {
  339. if !c.weClosed {
  340. c.weClosed = true
  341. return c.sendClose()
  342. }
  343. return nil
  344. }
  345. // Thread safe channel list.
  346. type chanlist struct {
  347. // protects concurrent access to chans
  348. sync.Mutex
  349. // chans are indexed by the local id of the channel, clientChan.id.
  350. // The PeersId value of messages received by ClientConn.mainLoop is
  351. // used to locate the right local clientChan in this slice.
  352. chans []*clientChan
  353. }
  354. // Allocate a new ClientChan with the next avail local id.
  355. func (c *chanlist) newChan(t *transport) *clientChan {
  356. c.Lock()
  357. defer c.Unlock()
  358. for i := range c.chans {
  359. if c.chans[i] == nil {
  360. ch := newClientChan(t, uint32(i))
  361. c.chans[i] = ch
  362. return ch
  363. }
  364. }
  365. i := len(c.chans)
  366. ch := newClientChan(t, uint32(i))
  367. c.chans = append(c.chans, ch)
  368. return ch
  369. }
  370. func (c *chanlist) getChan(id uint32) *clientChan {
  371. c.Lock()
  372. defer c.Unlock()
  373. return c.chans[int(id)]
  374. }
  375. func (c *chanlist) remove(id uint32) {
  376. c.Lock()
  377. defer c.Unlock()
  378. c.chans[int(id)] = nil
  379. }
  380. // A chanWriter represents the stdin of a remote process.
  381. type chanWriter struct {
  382. win *window
  383. clientChan *clientChan // the channel backing this writer
  384. }
  385. // Write writes data to the remote process's standard input.
  386. func (w *chanWriter) Write(data []byte) (written int, err error) {
  387. for len(data) > 0 {
  388. // n cannot be larger than 2^31 as len(data) cannot
  389. // be larger than 2^31
  390. n := int(w.win.reserve(uint32(len(data))))
  391. peersId := w.clientChan.peersId
  392. packet := []byte{
  393. msgChannelData,
  394. byte(peersId >> 24), byte(peersId >> 16), byte(peersId >> 8), byte(peersId),
  395. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  396. }
  397. if err = w.clientChan.writePacket(append(packet, data[:n]...)); err != nil {
  398. break
  399. }
  400. data = data[n:]
  401. written += n
  402. }
  403. return
  404. }
  405. func min(a, b int) int {
  406. if a < b {
  407. return a
  408. }
  409. return b
  410. }
  411. func (w *chanWriter) Close() error {
  412. return w.clientChan.sendEOF()
  413. }
  414. // A chanReader represents stdout or stderr of a remote process.
  415. type chanReader struct {
  416. // TODO(dfc) a fixed size channel may not be the right data structure.
  417. // If writes to this channel block, they will block mainLoop, making
  418. // it unable to receive new messages from the remote side.
  419. data chan []byte // receives data from remote
  420. dataClosed bool // protects data from being closed twice
  421. clientChan *clientChan // the channel backing this reader
  422. buf []byte
  423. }
  424. // eof signals to the consumer that there is no more data to be received.
  425. func (r *chanReader) eof() {
  426. if !r.dataClosed {
  427. r.dataClosed = true
  428. close(r.data)
  429. }
  430. }
  431. // handleData sends buf to the reader's consumer. If r.data is closed
  432. // the data will be silently discarded
  433. func (r *chanReader) handleData(buf []byte) {
  434. if !r.dataClosed {
  435. r.data <- buf
  436. }
  437. }
  438. // Read reads data from the remote process's stdout or stderr.
  439. func (r *chanReader) Read(data []byte) (int, error) {
  440. var ok bool
  441. for {
  442. if len(r.buf) > 0 {
  443. n := copy(data, r.buf)
  444. r.buf = r.buf[n:]
  445. msg := windowAdjustMsg{
  446. PeersId: r.clientChan.peersId,
  447. AdditionalBytes: uint32(n),
  448. }
  449. return n, r.clientChan.writePacket(marshal(msgChannelWindowAdjust, msg))
  450. }
  451. r.buf, ok = <-r.data
  452. if !ok {
  453. return 0, io.EOF
  454. }
  455. }
  456. panic("unreachable")
  457. }
  458. // window represents the buffer available to clients
  459. // wishing to write to a channel.
  460. type window struct {
  461. *sync.Cond
  462. win uint32 // RFC 4254 5.2 says the window size can grow to 2^32-1
  463. }
  464. // add adds win to the amount of window available
  465. // for consumers.
  466. func (w *window) add(win uint32) bool {
  467. if win == 0 {
  468. return false
  469. }
  470. w.L.Lock()
  471. if w.win+win < win {
  472. w.L.Unlock()
  473. return false
  474. }
  475. w.win += win
  476. // It is unusual that multiple goroutines would be attempting to reserve
  477. // window space, but not guaranteed. Use broadcast to notify all waiters
  478. // that additional window is available.
  479. w.Broadcast()
  480. w.L.Unlock()
  481. return true
  482. }
  483. // reserve reserves win from the available window capacity.
  484. // If no capacity remains, reserve will block. reserve may
  485. // return less than requested.
  486. func (w *window) reserve(win uint32) uint32 {
  487. w.L.Lock()
  488. for w.win == 0 {
  489. w.Wait()
  490. }
  491. if w.win < win {
  492. win = w.win
  493. }
  494. w.win -= win
  495. w.L.Unlock()
  496. return win
  497. }