client.go 17 KB

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