channel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. "errors"
  7. "fmt"
  8. "io"
  9. "sync"
  10. "sync/atomic"
  11. )
  12. // extendedDataTypeCode identifies an OpenSSL extended data type. See RFC 4254,
  13. // section 5.2.
  14. type extendedDataTypeCode uint32
  15. const (
  16. // extendedDataStderr is the extended data type that is used for stderr.
  17. extendedDataStderr extendedDataTypeCode = 1
  18. // minPacketLength defines the smallest valid packet
  19. minPacketLength = 9
  20. )
  21. // A Channel is an ordered, reliable, duplex stream that is multiplexed over an
  22. // SSH connection. Channel.Read can return a ChannelRequest as an error.
  23. type Channel interface {
  24. // Accept accepts the channel creation request.
  25. Accept() error
  26. // Reject rejects the channel creation request. After calling this, no
  27. // other methods on the Channel may be called. If they are then the
  28. // peer is likely to signal a protocol error and drop the connection.
  29. Reject(reason RejectionReason, message string) error
  30. // Read may return a ChannelRequest as an error.
  31. Read(data []byte) (int, error)
  32. Write(data []byte) (int, error)
  33. Close() error
  34. // Stderr returns an io.Writer that writes to this channel with the
  35. // extended data type set to stderr.
  36. Stderr() io.Writer
  37. // AckRequest either sends an ack or nack to the channel request.
  38. AckRequest(ok bool) error
  39. // ChannelType returns the type of the channel, as supplied by the
  40. // client.
  41. ChannelType() string
  42. // ExtraData returns the arbitary payload for this channel, as supplied
  43. // by the client. This data is specific to the channel type.
  44. ExtraData() []byte
  45. }
  46. // ChannelRequest represents a request sent on a channel, outside of the normal
  47. // stream of bytes. It may result from calling Read on a Channel.
  48. type ChannelRequest struct {
  49. Request string
  50. WantReply bool
  51. Payload []byte
  52. }
  53. func (c ChannelRequest) Error() string {
  54. return "ssh: channel request received"
  55. }
  56. // RejectionReason is an enumeration used when rejecting channel creation
  57. // requests. See RFC 4254, section 5.1.
  58. type RejectionReason uint32
  59. const (
  60. Prohibited RejectionReason = iota + 1
  61. ConnectionFailed
  62. UnknownChannelType
  63. ResourceShortage
  64. )
  65. type channel struct {
  66. conn // the underlying transport
  67. localId, remoteId uint32
  68. remoteWin window
  69. maxPacket uint32
  70. isClosed uint32 // atomic bool, non zero if true
  71. }
  72. func (c *channel) sendWindowAdj(n int) error {
  73. msg := windowAdjustMsg{
  74. PeersId: c.remoteId,
  75. AdditionalBytes: uint32(n),
  76. }
  77. return c.writePacket(marshal(msgChannelWindowAdjust, msg))
  78. }
  79. // sendEOF sends EOF to the remote side. RFC 4254 Section 5.3
  80. func (c *channel) sendEOF() error {
  81. return c.writePacket(marshal(msgChannelEOF, channelEOFMsg{
  82. PeersId: c.remoteId,
  83. }))
  84. }
  85. // sendClose informs the remote side of our intent to close the channel.
  86. func (c *channel) sendClose() error {
  87. return c.conn.writePacket(marshal(msgChannelClose, channelCloseMsg{
  88. PeersId: c.remoteId,
  89. }))
  90. }
  91. func (c *channel) sendChannelOpenFailure(reason RejectionReason, message string) error {
  92. reject := channelOpenFailureMsg{
  93. PeersId: c.remoteId,
  94. Reason: reason,
  95. Message: message,
  96. Language: "en",
  97. }
  98. return c.writePacket(marshal(msgChannelOpenFailure, reject))
  99. }
  100. func (c *channel) writePacket(b []byte) error {
  101. if c.closed() {
  102. return io.EOF
  103. }
  104. if uint32(len(b)) > c.maxPacket {
  105. return fmt.Errorf("ssh: cannot write %d bytes, maxPacket is %d bytes", len(b), c.maxPacket)
  106. }
  107. return c.conn.writePacket(b)
  108. }
  109. func (c *channel) closed() bool {
  110. return atomic.LoadUint32(&c.isClosed) > 0
  111. }
  112. func (c *channel) setClosed() bool {
  113. return atomic.CompareAndSwapUint32(&c.isClosed, 0, 1)
  114. }
  115. type serverChan struct {
  116. channel
  117. // immutable once created
  118. chanType string
  119. extraData []byte
  120. serverConn *ServerConn
  121. myWindow uint32
  122. theyClosed bool // indicates the close msg has been received from the remote side
  123. theySentEOF bool
  124. isDead uint32
  125. err error
  126. pendingRequests []ChannelRequest
  127. pendingData []byte
  128. head, length int
  129. // This lock is inferior to serverConn.lock
  130. cond *sync.Cond
  131. }
  132. func (c *serverChan) Accept() error {
  133. c.serverConn.lock.Lock()
  134. defer c.serverConn.lock.Unlock()
  135. if c.serverConn.err != nil {
  136. return c.serverConn.err
  137. }
  138. confirm := channelOpenConfirmMsg{
  139. PeersId: c.remoteId,
  140. MyId: c.localId,
  141. MyWindow: c.myWindow,
  142. MaxPacketSize: c.maxPacket,
  143. }
  144. return c.writePacket(marshal(msgChannelOpenConfirm, confirm))
  145. }
  146. func (c *serverChan) Reject(reason RejectionReason, message string) error {
  147. c.serverConn.lock.Lock()
  148. defer c.serverConn.lock.Unlock()
  149. if c.serverConn.err != nil {
  150. return c.serverConn.err
  151. }
  152. return c.sendChannelOpenFailure(reason, message)
  153. }
  154. func (c *serverChan) handlePacket(packet interface{}) {
  155. c.cond.L.Lock()
  156. defer c.cond.L.Unlock()
  157. switch packet := packet.(type) {
  158. case *channelRequestMsg:
  159. req := ChannelRequest{
  160. Request: packet.Request,
  161. WantReply: packet.WantReply,
  162. Payload: packet.RequestSpecificData,
  163. }
  164. c.pendingRequests = append(c.pendingRequests, req)
  165. c.cond.Signal()
  166. case *channelCloseMsg:
  167. c.theyClosed = true
  168. c.cond.Signal()
  169. case *channelEOFMsg:
  170. c.theySentEOF = true
  171. c.cond.Signal()
  172. case *windowAdjustMsg:
  173. if !c.remoteWin.add(packet.AdditionalBytes) {
  174. panic("illegal window update")
  175. }
  176. default:
  177. panic("unknown packet type")
  178. }
  179. }
  180. func (c *serverChan) handleData(data []byte) {
  181. c.cond.L.Lock()
  182. defer c.cond.L.Unlock()
  183. // The other side should never send us more than our window.
  184. if len(data)+c.length > len(c.pendingData) {
  185. // TODO(agl): we should tear down the channel with a protocol
  186. // error.
  187. return
  188. }
  189. c.myWindow -= uint32(len(data))
  190. for i := 0; i < 2; i++ {
  191. tail := c.head + c.length
  192. if tail >= len(c.pendingData) {
  193. tail -= len(c.pendingData)
  194. }
  195. n := copy(c.pendingData[tail:], data)
  196. data = data[n:]
  197. c.length += n
  198. }
  199. c.cond.Signal()
  200. }
  201. func (c *serverChan) Stderr() io.Writer {
  202. return extendedDataChannel{c: c, t: extendedDataStderr}
  203. }
  204. // extendedDataChannel is an io.Writer that writes any data to c as extended
  205. // data of the given type.
  206. type extendedDataChannel struct {
  207. t extendedDataTypeCode
  208. c *serverChan
  209. }
  210. func (edc extendedDataChannel) Write(data []byte) (n int, err error) {
  211. const headerLength = 13 // 1 byte message type, 4 bytes remoteId, 4 bytes extended message type, 4 bytes data length
  212. c := edc.c
  213. for len(data) > 0 {
  214. space := min(c.maxPacket-headerLength, len(data))
  215. if space, err = c.getWindowSpace(space); err != nil {
  216. return 0, err
  217. }
  218. todo := data
  219. if uint32(len(todo)) > space {
  220. todo = todo[:space]
  221. }
  222. packet := make([]byte, headerLength+len(todo))
  223. packet[0] = msgChannelExtendedData
  224. marshalUint32(packet[1:], c.remoteId)
  225. marshalUint32(packet[5:], uint32(edc.t))
  226. marshalUint32(packet[9:], uint32(len(todo)))
  227. copy(packet[13:], todo)
  228. if err = c.writePacket(packet); err != nil {
  229. return
  230. }
  231. n += len(todo)
  232. data = data[len(todo):]
  233. }
  234. return
  235. }
  236. func (c *serverChan) Read(data []byte) (n int, err error) {
  237. n, err, windowAdjustment := c.read(data)
  238. if windowAdjustment > 0 {
  239. packet := marshal(msgChannelWindowAdjust, windowAdjustMsg{
  240. PeersId: c.remoteId,
  241. AdditionalBytes: windowAdjustment,
  242. })
  243. err = c.writePacket(packet)
  244. }
  245. return
  246. }
  247. func (c *serverChan) read(data []byte) (n int, err error, windowAdjustment uint32) {
  248. c.cond.L.Lock()
  249. defer c.cond.L.Unlock()
  250. if c.err != nil {
  251. return 0, c.err, 0
  252. }
  253. for {
  254. if c.theySentEOF || c.theyClosed || c.dead() {
  255. return 0, io.EOF, 0
  256. }
  257. if len(c.pendingRequests) > 0 {
  258. req := c.pendingRequests[0]
  259. if len(c.pendingRequests) == 1 {
  260. c.pendingRequests = nil
  261. } else {
  262. oldPendingRequests := c.pendingRequests
  263. c.pendingRequests = make([]ChannelRequest, len(oldPendingRequests)-1)
  264. copy(c.pendingRequests, oldPendingRequests[1:])
  265. }
  266. return 0, req, 0
  267. }
  268. if c.length > 0 {
  269. tail := min(uint32(c.head+c.length), len(c.pendingData))
  270. n = copy(data, c.pendingData[c.head:tail])
  271. c.head += n
  272. c.length -= n
  273. if c.head == len(c.pendingData) {
  274. c.head = 0
  275. }
  276. windowAdjustment = uint32(len(c.pendingData)-c.length) - c.myWindow
  277. if windowAdjustment < uint32(len(c.pendingData)/2) {
  278. windowAdjustment = 0
  279. }
  280. c.myWindow += windowAdjustment
  281. return
  282. }
  283. c.cond.Wait()
  284. }
  285. }
  286. // getWindowSpace takes, at most, max bytes of space from the peer's window. It
  287. // returns the number of bytes actually reserved.
  288. func (c *serverChan) getWindowSpace(max uint32) (uint32, error) {
  289. if c.dead() || c.closed() {
  290. return 0, io.EOF
  291. }
  292. return c.remoteWin.reserve(max), nil
  293. }
  294. func (c *serverChan) dead() bool {
  295. return atomic.LoadUint32(&c.isDead) > 0
  296. }
  297. func (c *serverChan) setDead() {
  298. atomic.StoreUint32(&c.isDead, 1)
  299. }
  300. func (c *serverChan) Write(data []byte) (n int, err error) {
  301. const headerLength = 9 // 1 byte message type, 4 bytes remoteId, 4 bytes data length
  302. for len(data) > 0 {
  303. space := min(c.maxPacket-headerLength, len(data))
  304. if space, err = c.getWindowSpace(space); err != nil {
  305. return 0, err
  306. }
  307. todo := data
  308. if uint32(len(todo)) > space {
  309. todo = todo[:space]
  310. }
  311. packet := make([]byte, headerLength+len(todo))
  312. packet[0] = msgChannelData
  313. marshalUint32(packet[1:], c.remoteId)
  314. marshalUint32(packet[5:], uint32(len(todo)))
  315. copy(packet[9:], todo)
  316. if err = c.writePacket(packet); err != nil {
  317. return
  318. }
  319. n += len(todo)
  320. data = data[len(todo):]
  321. }
  322. return
  323. }
  324. // Close signals the intent to close the channel.
  325. func (c *serverChan) Close() error {
  326. c.serverConn.lock.Lock()
  327. defer c.serverConn.lock.Unlock()
  328. if c.serverConn.err != nil {
  329. return c.serverConn.err
  330. }
  331. if !c.setClosed() {
  332. return errors.New("ssh: channel already closed")
  333. }
  334. return c.sendClose()
  335. }
  336. func (c *serverChan) AckRequest(ok bool) error {
  337. c.serverConn.lock.Lock()
  338. defer c.serverConn.lock.Unlock()
  339. if c.serverConn.err != nil {
  340. return c.serverConn.err
  341. }
  342. if !ok {
  343. ack := channelRequestFailureMsg{
  344. PeersId: c.remoteId,
  345. }
  346. return c.writePacket(marshal(msgChannelFailure, ack))
  347. }
  348. ack := channelRequestSuccessMsg{
  349. PeersId: c.remoteId,
  350. }
  351. return c.writePacket(marshal(msgChannelSuccess, ack))
  352. }
  353. func (c *serverChan) ChannelType() string {
  354. return c.chanType
  355. }
  356. func (c *serverChan) ExtraData() []byte {
  357. return c.extraData
  358. }
  359. // A clientChan represents a single RFC 4254 channel multiplexed
  360. // over a SSH connection.
  361. type clientChan struct {
  362. channel
  363. stdin *chanWriter
  364. stdout *chanReader
  365. stderr *chanReader
  366. msg chan interface{}
  367. }
  368. // newClientChan returns a partially constructed *clientChan
  369. // using the local id provided. To be usable clientChan.remoteId
  370. // needs to be assigned once known.
  371. func newClientChan(cc conn, id uint32) *clientChan {
  372. c := &clientChan{
  373. channel: channel{
  374. conn: cc,
  375. localId: id,
  376. remoteWin: window{Cond: newCond()},
  377. },
  378. msg: make(chan interface{}, 16),
  379. }
  380. c.stdin = &chanWriter{
  381. channel: &c.channel,
  382. }
  383. c.stdout = &chanReader{
  384. channel: &c.channel,
  385. buffer: newBuffer(),
  386. }
  387. c.stderr = &chanReader{
  388. channel: &c.channel,
  389. buffer: newBuffer(),
  390. }
  391. return c
  392. }
  393. // waitForChannelOpenResponse, if successful, fills out
  394. // the remoteId and records any initial window advertisement.
  395. func (c *clientChan) waitForChannelOpenResponse() error {
  396. switch msg := (<-c.msg).(type) {
  397. case *channelOpenConfirmMsg:
  398. if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 {
  399. return errors.New("ssh: invalid MaxPacketSize from peer")
  400. }
  401. // fixup remoteId field
  402. c.remoteId = msg.MyId
  403. c.maxPacket = msg.MaxPacketSize
  404. c.remoteWin.add(msg.MyWindow)
  405. return nil
  406. case *channelOpenFailureMsg:
  407. return errors.New(safeString(msg.Message))
  408. }
  409. return errors.New("ssh: unexpected packet")
  410. }
  411. // Close signals the intent to close the channel.
  412. func (c *clientChan) Close() error {
  413. if !c.setClosed() {
  414. return errors.New("ssh: channel already closed")
  415. }
  416. c.stdout.eof()
  417. c.stderr.eof()
  418. return c.sendClose()
  419. }
  420. // A chanWriter represents the stdin of a remote process.
  421. type chanWriter struct {
  422. *channel
  423. // indicates the writer has been closed. eof is owned by the
  424. // caller of Write/Close.
  425. eof bool
  426. }
  427. // Write writes data to the remote process's standard input.
  428. func (w *chanWriter) Write(data []byte) (written int, err error) {
  429. const headerLength = 9 // 1 byte message type, 4 bytes remoteId, 4 bytes data length
  430. for len(data) > 0 {
  431. if w.eof || w.closed() {
  432. err = io.EOF
  433. return
  434. }
  435. // never send more data than maxPacket even if
  436. // there is sufficent window.
  437. n := min(w.maxPacket-headerLength, len(data))
  438. r := w.remoteWin.reserve(n)
  439. n = r
  440. remoteId := w.remoteId
  441. packet := []byte{
  442. msgChannelData,
  443. byte(remoteId >> 24), byte(remoteId >> 16), byte(remoteId >> 8), byte(remoteId),
  444. byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n),
  445. }
  446. if err = w.writePacket(append(packet, data[:n]...)); err != nil {
  447. break
  448. }
  449. data = data[n:]
  450. written += int(n)
  451. }
  452. return
  453. }
  454. func min(a uint32, b int) uint32 {
  455. if a < uint32(b) {
  456. return a
  457. }
  458. return uint32(b)
  459. }
  460. func (w *chanWriter) Close() error {
  461. w.eof = true
  462. return w.sendEOF()
  463. }
  464. // A chanReader represents stdout or stderr of a remote process.
  465. type chanReader struct {
  466. *channel // the channel backing this reader
  467. *buffer
  468. }
  469. // Read reads data from the remote process's stdout or stderr.
  470. func (r *chanReader) Read(buf []byte) (int, error) {
  471. n, err := r.buffer.Read(buf)
  472. if err != nil {
  473. if err == io.EOF {
  474. return n, err
  475. }
  476. return 0, err
  477. }
  478. err = r.sendWindowAdj(n)
  479. if err == io.EOF && n > 0 {
  480. // sendWindowAdjust can return io.EOF if the remote peer has
  481. // closed the connection, however we want to defer forwarding io.EOF to the
  482. // caller of Read until the buffer has been drained.
  483. err = nil
  484. }
  485. return n, err
  486. }