client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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: supportedMACs,
  58. MACsServerClient: supportedMACs,
  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. default:
  95. err = fmt.Errorf("ssh: unexpected key exchange algorithm %v", kexAlgo)
  96. }
  97. if err != nil {
  98. return err
  99. }
  100. if err = c.writePacket([]byte{msgNewKeys}); err != nil {
  101. return err
  102. }
  103. if err = c.transport.writer.setupKeys(clientKeys, K, H, H, hashFunc); err != nil {
  104. return err
  105. }
  106. if packet, err = c.readPacket(); err != nil {
  107. return err
  108. }
  109. if packet[0] != msgNewKeys {
  110. return UnexpectedMessageError{msgNewKeys, packet[0]}
  111. }
  112. if err := c.transport.reader.setupKeys(serverKeys, K, H, H, hashFunc); err != nil {
  113. return err
  114. }
  115. return c.authenticate(H)
  116. }
  117. // kexDH performs Diffie-Hellman key agreement on a ClientConn. The
  118. // returned values are given the same names as in RFC 4253, section 8.
  119. func (c *ClientConn) kexDH(group *dhGroup, hashFunc crypto.Hash, magics *handshakeMagics, hostKeyAlgo string) ([]byte, []byte, error) {
  120. x, err := rand.Int(c.config.rand(), group.p)
  121. if err != nil {
  122. return nil, nil, err
  123. }
  124. X := new(big.Int).Exp(group.g, x, group.p)
  125. kexDHInit := kexDHInitMsg{
  126. X: X,
  127. }
  128. if err := c.writePacket(marshal(msgKexDHInit, kexDHInit)); err != nil {
  129. return nil, nil, err
  130. }
  131. packet, err := c.readPacket()
  132. if err != nil {
  133. return nil, nil, err
  134. }
  135. var kexDHReply = new(kexDHReplyMsg)
  136. if err = unmarshal(kexDHReply, packet, msgKexDHReply); err != nil {
  137. return nil, nil, err
  138. }
  139. if kexDHReply.Y.Sign() == 0 || kexDHReply.Y.Cmp(group.p) >= 0 {
  140. return nil, nil, errors.New("server DH parameter out of bounds")
  141. }
  142. kInt := new(big.Int).Exp(kexDHReply.Y, x, group.p)
  143. h := hashFunc.New()
  144. writeString(h, magics.clientVersion)
  145. writeString(h, magics.serverVersion)
  146. writeString(h, magics.clientKexInit)
  147. writeString(h, magics.serverKexInit)
  148. writeString(h, kexDHReply.HostKey)
  149. writeInt(h, X)
  150. writeInt(h, kexDHReply.Y)
  151. K := make([]byte, intLength(kInt))
  152. marshalInt(K, kInt)
  153. h.Write(K)
  154. H := h.Sum(nil)
  155. return H, K, nil
  156. }
  157. // mainLoop reads incoming messages and routes channel messages
  158. // to their respective ClientChans.
  159. func (c *ClientConn) mainLoop() {
  160. // TODO(dfc) signal the underlying close to all channels
  161. defer c.Close()
  162. for {
  163. packet, err := c.readPacket()
  164. if err != nil {
  165. break
  166. }
  167. // TODO(dfc) A note on blocking channel use.
  168. // The msg, win, data and dataExt channels of a clientChan can
  169. // cause this loop to block indefinately if the consumer does
  170. // not service them.
  171. switch packet[0] {
  172. case msgChannelData:
  173. if len(packet) < 9 {
  174. // malformed data packet
  175. break
  176. }
  177. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  178. if length := int(packet[5])<<24 | int(packet[6])<<16 | int(packet[7])<<8 | int(packet[8]); length > 0 {
  179. packet = packet[9:]
  180. c.getChan(peersId).stdout.handleData(packet[:length])
  181. }
  182. case msgChannelExtendedData:
  183. if len(packet) < 13 {
  184. // malformed data packet
  185. break
  186. }
  187. peersId := uint32(packet[1])<<24 | uint32(packet[2])<<16 | uint32(packet[3])<<8 | uint32(packet[4])
  188. datatype := uint32(packet[5])<<24 | uint32(packet[6])<<16 | uint32(packet[7])<<8 | uint32(packet[8])
  189. if length := int(packet[9])<<24 | int(packet[10])<<16 | int(packet[11])<<8 | int(packet[12]); length > 0 {
  190. packet = packet[13:]
  191. // RFC 4254 5.2 defines data_type_code 1 to be data destined
  192. // for stderr on interactive sessions. Other data types are
  193. // silently discarded.
  194. if datatype == 1 {
  195. c.getChan(peersId).stderr.handleData(packet[:length])
  196. }
  197. }
  198. default:
  199. switch msg := decode(packet).(type) {
  200. case *channelOpenMsg:
  201. c.getChan(msg.PeersId).msg <- msg
  202. case *channelOpenConfirmMsg:
  203. c.getChan(msg.PeersId).msg <- msg
  204. case *channelOpenFailureMsg:
  205. c.getChan(msg.PeersId).msg <- msg
  206. case *channelCloseMsg:
  207. ch := c.getChan(msg.PeersId)
  208. ch.theyClosed = true
  209. close(ch.stdin.win)
  210. ch.stdout.eof()
  211. ch.stderr.eof()
  212. close(ch.msg)
  213. if !ch.weClosed {
  214. ch.weClosed = true
  215. ch.sendClose()
  216. }
  217. c.chanlist.remove(msg.PeersId)
  218. case *channelEOFMsg:
  219. ch := c.getChan(msg.PeersId)
  220. ch.stdout.eof()
  221. // RFC 4254 is mute on how EOF affects dataExt messages but
  222. // it is logical to signal EOF at the same time.
  223. ch.stderr.eof()
  224. case *channelRequestSuccessMsg:
  225. c.getChan(msg.PeersId).msg <- msg
  226. case *channelRequestFailureMsg:
  227. c.getChan(msg.PeersId).msg <- msg
  228. case *channelRequestMsg:
  229. c.getChan(msg.PeersId).msg <- msg
  230. case *windowAdjustMsg:
  231. c.getChan(msg.PeersId).stdin.win <- int(msg.AdditionalBytes)
  232. case *disconnectMsg:
  233. break
  234. default:
  235. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  236. }
  237. }
  238. }
  239. }
  240. // Dial connects to the given network address using net.Dial and
  241. // then initiates a SSH handshake, returning the resulting client connection.
  242. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  243. conn, err := net.Dial(network, addr)
  244. if err != nil {
  245. return nil, err
  246. }
  247. return Client(conn, config)
  248. }
  249. // A ClientConfig structure is used to configure a ClientConn. After one has
  250. // been passed to an SSH function it must not be modified.
  251. type ClientConfig struct {
  252. // Rand provides the source of entropy for key exchange. If Rand is
  253. // nil, the cryptographic random reader in package crypto/rand will
  254. // be used.
  255. Rand io.Reader
  256. // The username to authenticate.
  257. User string
  258. // A slice of ClientAuth methods. Only the first instance
  259. // of a particular RFC 4252 method will be used during authentication.
  260. Auth []ClientAuth
  261. // Cryptographic-related configuration.
  262. Crypto CryptoConfig
  263. }
  264. func (c *ClientConfig) rand() io.Reader {
  265. if c.Rand == nil {
  266. return rand.Reader
  267. }
  268. return c.Rand
  269. }
  270. // A clientChan represents a single RFC 4254 channel that is multiplexed
  271. // over a single SSH connection.
  272. type clientChan struct {
  273. packetWriter
  274. id, peersId uint32
  275. stdin *chanWriter // receives window adjustments
  276. stdout *chanReader // receives the payload of channelData messages
  277. stderr *chanReader // receives the payload of channelExtendedData messages
  278. msg chan interface{} // incoming messages
  279. theyClosed bool // indicates the close msg has been received from the remote side
  280. weClosed bool // incidates the close msg has been sent from our side
  281. }
  282. // newClientChan returns a partially constructed *clientChan
  283. // using the local id provided. To be usable clientChan.peersId
  284. // needs to be assigned once known.
  285. func newClientChan(t *transport, id uint32) *clientChan {
  286. c := &clientChan{
  287. packetWriter: t,
  288. id: id,
  289. msg: make(chan interface{}, 16),
  290. }
  291. c.stdin = &chanWriter{
  292. win: make(chan int, 16),
  293. clientChan: c,
  294. }
  295. c.stdout = &chanReader{
  296. data: make(chan []byte, 16),
  297. clientChan: c,
  298. }
  299. c.stderr = &chanReader{
  300. data: make(chan []byte, 16),
  301. clientChan: c,
  302. }
  303. return c
  304. }
  305. // waitForChannelOpenResponse, if successful, fills out
  306. // the peerId and records any initial window advertisement.
  307. func (c *clientChan) waitForChannelOpenResponse() error {
  308. switch msg := (<-c.msg).(type) {
  309. case *channelOpenConfirmMsg:
  310. // fixup peersId field
  311. c.peersId = msg.MyId
  312. c.stdin.win <- int(msg.MyWindow)
  313. return nil
  314. case *channelOpenFailureMsg:
  315. return errors.New(safeString(msg.Message))
  316. }
  317. return errors.New("unexpected packet")
  318. }
  319. // sendEOF sends EOF to the server. RFC 4254 Section 5.3
  320. func (c *clientChan) sendEOF() error {
  321. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  322. PeersId: c.peersId,
  323. }))
  324. }
  325. // sendClose signals the intent to close the channel.
  326. func (c *clientChan) sendClose() error {
  327. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  328. PeersId: c.peersId,
  329. }))
  330. }
  331. // Close closes the channel. This does not close the underlying connection.
  332. func (c *clientChan) Close() error {
  333. if !c.weClosed {
  334. c.weClosed = true
  335. return c.sendClose()
  336. }
  337. return nil
  338. }
  339. // Thread safe channel list.
  340. type chanlist struct {
  341. // protects concurrent access to chans
  342. sync.Mutex
  343. // chans are indexed by the local id of the channel, clientChan.id.
  344. // The PeersId value of messages received by ClientConn.mainLoop is
  345. // used to locate the right local clientChan in this slice.
  346. chans []*clientChan
  347. }
  348. // Allocate a new ClientChan with the next avail local id.
  349. func (c *chanlist) newChan(t *transport) *clientChan {
  350. c.Lock()
  351. defer c.Unlock()
  352. for i := range c.chans {
  353. if c.chans[i] == nil {
  354. ch := newClientChan(t, uint32(i))
  355. c.chans[i] = ch
  356. return ch
  357. }
  358. }
  359. i := len(c.chans)
  360. ch := newClientChan(t, uint32(i))
  361. c.chans = append(c.chans, ch)
  362. return ch
  363. }
  364. func (c *chanlist) getChan(id uint32) *clientChan {
  365. c.Lock()
  366. defer c.Unlock()
  367. return c.chans[int(id)]
  368. }
  369. func (c *chanlist) remove(id uint32) {
  370. c.Lock()
  371. defer c.Unlock()
  372. c.chans[int(id)] = nil
  373. }
  374. // A chanWriter represents the stdin of a remote process.
  375. type chanWriter struct {
  376. win chan int // receives window adjustments
  377. rwin int // current rwin size
  378. clientChan *clientChan // the channel backing this writer
  379. }
  380. // Write writes data to the remote process's standard input.
  381. func (w *chanWriter) Write(data []byte) (written int, err error) {
  382. for len(data) > 0 {
  383. for w.rwin < 1 {
  384. win, ok := <-w.win
  385. if !ok {
  386. return 0, io.EOF
  387. }
  388. w.rwin += win
  389. }
  390. n := min(len(data), w.rwin)
  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. w.rwin -= n
  402. written += n
  403. }
  404. return
  405. }
  406. func min(a, b int) int {
  407. if a < b {
  408. return a
  409. }
  410. return b
  411. }
  412. func (w *chanWriter) Close() error {
  413. return w.clientChan.sendEOF()
  414. }
  415. // A chanReader represents stdout or stderr of a remote process.
  416. type chanReader struct {
  417. // TODO(dfc) a fixed size channel may not be the right data structure.
  418. // If writes to this channel block, they will block mainLoop, making
  419. // it unable to receive new messages from the remote side.
  420. data chan []byte // receives data from remote
  421. dataClosed bool // protects data from being closed twice
  422. clientChan *clientChan // the channel backing this reader
  423. buf []byte
  424. }
  425. // eof signals to the consumer that there is no more data to be received.
  426. func (r *chanReader) eof() {
  427. if !r.dataClosed {
  428. r.dataClosed = true
  429. close(r.data)
  430. }
  431. }
  432. // handleData sends buf to the reader's consumer. If r.data is closed
  433. // the data will be silently discarded
  434. func (r *chanReader) handleData(buf []byte) {
  435. if !r.dataClosed {
  436. r.data <- buf
  437. }
  438. }
  439. // Read reads data from the remote process's stdout or stderr.
  440. func (r *chanReader) Read(data []byte) (int, error) {
  441. var ok bool
  442. for {
  443. if len(r.buf) > 0 {
  444. n := copy(data, r.buf)
  445. r.buf = r.buf[n:]
  446. msg := windowAdjustMsg{
  447. PeersId: r.clientChan.peersId,
  448. AdditionalBytes: uint32(n),
  449. }
  450. return n, r.clientChan.writePacket(marshal(msgChannelWindowAdjust, msg))
  451. }
  452. r.buf, ok = <-r.data
  453. if !ok {
  454. return 0, io.EOF
  455. }
  456. }
  457. panic("unreachable")
  458. }