client.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 = new(kexDHReplyMsg)
  140. if err = unmarshal(kexDHReply, packet, msgKexDHReply); err != nil {
  141. return nil, nil, err
  142. }
  143. if kexDHReply.Y.Sign() == 0 || kexDHReply.Y.Cmp(group.p) >= 0 {
  144. return nil, nil, errors.New("server DH parameter out of bounds")
  145. }
  146. kInt := new(big.Int).Exp(kexDHReply.Y, x, group.p)
  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, win, 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. close(ch.stdin.win)
  214. ch.stdout.eof()
  215. ch.stderr.eof()
  216. close(ch.msg)
  217. if !ch.weClosed {
  218. ch.weClosed = true
  219. ch.sendClose()
  220. }
  221. c.chanlist.remove(msg.PeersId)
  222. case *channelEOFMsg:
  223. ch := c.getChan(msg.PeersId)
  224. ch.stdout.eof()
  225. // RFC 4254 is mute on how EOF affects dataExt messages but
  226. // it is logical to signal EOF at the same time.
  227. ch.stderr.eof()
  228. case *channelRequestSuccessMsg:
  229. c.getChan(msg.PeersId).msg <- msg
  230. case *channelRequestFailureMsg:
  231. c.getChan(msg.PeersId).msg <- msg
  232. case *channelRequestMsg:
  233. c.getChan(msg.PeersId).msg <- msg
  234. case *windowAdjustMsg:
  235. c.getChan(msg.PeersId).stdin.win <- int(msg.AdditionalBytes)
  236. case *disconnectMsg:
  237. break
  238. default:
  239. fmt.Printf("mainLoop: unhandled message %T: %v\n", msg, msg)
  240. }
  241. }
  242. }
  243. }
  244. // Dial connects to the given network address using net.Dial and
  245. // then initiates a SSH handshake, returning the resulting client connection.
  246. func Dial(network, addr string, config *ClientConfig) (*ClientConn, error) {
  247. conn, err := net.Dial(network, addr)
  248. if err != nil {
  249. return nil, err
  250. }
  251. return Client(conn, config)
  252. }
  253. // A ClientConfig structure is used to configure a ClientConn. After one has
  254. // been passed to an SSH function it must not be modified.
  255. type ClientConfig struct {
  256. // Rand provides the source of entropy for key exchange. If Rand is
  257. // nil, the cryptographic random reader in package crypto/rand will
  258. // be used.
  259. Rand io.Reader
  260. // The username to authenticate.
  261. User string
  262. // A slice of ClientAuth methods. Only the first instance
  263. // of a particular RFC 4252 method will be used during authentication.
  264. Auth []ClientAuth
  265. // Cryptographic-related configuration.
  266. Crypto CryptoConfig
  267. }
  268. func (c *ClientConfig) rand() io.Reader {
  269. if c.Rand == nil {
  270. return rand.Reader
  271. }
  272. return c.Rand
  273. }
  274. // A clientChan represents a single RFC 4254 channel that is multiplexed
  275. // over a single SSH connection.
  276. type clientChan struct {
  277. packetWriter
  278. id, peersId uint32
  279. stdin *chanWriter // receives window adjustments
  280. stdout *chanReader // receives the payload of channelData messages
  281. stderr *chanReader // receives the payload of channelExtendedData messages
  282. msg chan interface{} // incoming messages
  283. theyClosed bool // indicates the close msg has been received from the remote side
  284. weClosed bool // incidates the close msg has been sent from our side
  285. }
  286. // newClientChan returns a partially constructed *clientChan
  287. // using the local id provided. To be usable clientChan.peersId
  288. // needs to be assigned once known.
  289. func newClientChan(t *transport, id uint32) *clientChan {
  290. c := &clientChan{
  291. packetWriter: t,
  292. id: id,
  293. msg: make(chan interface{}, 16),
  294. }
  295. c.stdin = &chanWriter{
  296. win: make(chan int, 16),
  297. clientChan: c,
  298. }
  299. c.stdout = &chanReader{
  300. data: make(chan []byte, 16),
  301. clientChan: c,
  302. }
  303. c.stderr = &chanReader{
  304. data: make(chan []byte, 16),
  305. clientChan: c,
  306. }
  307. return c
  308. }
  309. // waitForChannelOpenResponse, if successful, fills out
  310. // the peerId and records any initial window advertisement.
  311. func (c *clientChan) waitForChannelOpenResponse() error {
  312. switch msg := (<-c.msg).(type) {
  313. case *channelOpenConfirmMsg:
  314. // fixup peersId field
  315. c.peersId = msg.MyId
  316. c.stdin.win <- int(msg.MyWindow)
  317. return nil
  318. case *channelOpenFailureMsg:
  319. return errors.New(safeString(msg.Message))
  320. }
  321. return errors.New("unexpected packet")
  322. }
  323. // sendEOF sends EOF to the server. RFC 4254 Section 5.3
  324. func (c *clientChan) sendEOF() error {
  325. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  326. PeersId: c.peersId,
  327. }))
  328. }
  329. // sendClose signals the intent to close the channel.
  330. func (c *clientChan) sendClose() error {
  331. return c.writePacket(marshal(msgChannelClose, channelCloseMsg{
  332. PeersId: c.peersId,
  333. }))
  334. }
  335. // Close closes the channel. This does not close the underlying connection.
  336. func (c *clientChan) Close() error {
  337. if !c.weClosed {
  338. c.weClosed = true
  339. return c.sendClose()
  340. }
  341. return nil
  342. }
  343. // Thread safe channel list.
  344. type chanlist struct {
  345. // protects concurrent access to chans
  346. sync.Mutex
  347. // chans are indexed by the local id of the channel, clientChan.id.
  348. // The PeersId value of messages received by ClientConn.mainLoop is
  349. // used to locate the right local clientChan in this slice.
  350. chans []*clientChan
  351. }
  352. // Allocate a new ClientChan with the next avail local id.
  353. func (c *chanlist) newChan(t *transport) *clientChan {
  354. c.Lock()
  355. defer c.Unlock()
  356. for i := range c.chans {
  357. if c.chans[i] == nil {
  358. ch := newClientChan(t, uint32(i))
  359. c.chans[i] = ch
  360. return ch
  361. }
  362. }
  363. i := len(c.chans)
  364. ch := newClientChan(t, uint32(i))
  365. c.chans = append(c.chans, ch)
  366. return ch
  367. }
  368. func (c *chanlist) getChan(id uint32) *clientChan {
  369. c.Lock()
  370. defer c.Unlock()
  371. return c.chans[int(id)]
  372. }
  373. func (c *chanlist) remove(id uint32) {
  374. c.Lock()
  375. defer c.Unlock()
  376. c.chans[int(id)] = nil
  377. }
  378. // A chanWriter represents the stdin of a remote process.
  379. type chanWriter struct {
  380. win chan int // receives window adjustments
  381. rwin int // current rwin size
  382. clientChan *clientChan // the channel backing this writer
  383. }
  384. // Write writes data to the remote process's standard input.
  385. func (w *chanWriter) Write(data []byte) (written int, err error) {
  386. for len(data) > 0 {
  387. for w.rwin < 1 {
  388. win, ok := <-w.win
  389. if !ok {
  390. return 0, io.EOF
  391. }
  392. w.rwin += win
  393. }
  394. n := min(len(data), w.rwin)
  395. peersId := w.clientChan.peersId
  396. packet := []byte{
  397. msgChannelData,
  398. byte(peersId >> 24), byte(peersId >> 16), byte(peersId >> 8), byte(peersId),
  399. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  400. }
  401. if err = w.clientChan.writePacket(append(packet, data[:n]...)); err != nil {
  402. break
  403. }
  404. data = data[n:]
  405. w.rwin -= n
  406. written += n
  407. }
  408. return
  409. }
  410. func min(a, b int) int {
  411. if a < b {
  412. return a
  413. }
  414. return b
  415. }
  416. func (w *chanWriter) Close() error {
  417. return w.clientChan.sendEOF()
  418. }
  419. // A chanReader represents stdout or stderr of a remote process.
  420. type chanReader struct {
  421. // TODO(dfc) a fixed size channel may not be the right data structure.
  422. // If writes to this channel block, they will block mainLoop, making
  423. // it unable to receive new messages from the remote side.
  424. data chan []byte // receives data from remote
  425. dataClosed bool // protects data from being closed twice
  426. clientChan *clientChan // the channel backing this reader
  427. buf []byte
  428. }
  429. // eof signals to the consumer that there is no more data to be received.
  430. func (r *chanReader) eof() {
  431. if !r.dataClosed {
  432. r.dataClosed = true
  433. close(r.data)
  434. }
  435. }
  436. // handleData sends buf to the reader's consumer. If r.data is closed
  437. // the data will be silently discarded
  438. func (r *chanReader) handleData(buf []byte) {
  439. if !r.dataClosed {
  440. r.data <- buf
  441. }
  442. }
  443. // Read reads data from the remote process's stdout or stderr.
  444. func (r *chanReader) Read(data []byte) (int, error) {
  445. var ok bool
  446. for {
  447. if len(r.buf) > 0 {
  448. n := copy(data, r.buf)
  449. r.buf = r.buf[n:]
  450. msg := windowAdjustMsg{
  451. PeersId: r.clientChan.peersId,
  452. AdditionalBytes: uint32(n),
  453. }
  454. return n, r.clientChan.writePacket(marshal(msgChannelWindowAdjust, msg))
  455. }
  456. r.buf, ok = <-r.data
  457. if !ok {
  458. return 0, io.EOF
  459. }
  460. }
  461. panic("unreachable")
  462. }