tcpip.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. "math/rand"
  10. "net"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // Listen requests the remote peer open a listening socket
  17. // on addr. Incoming connections will be available by calling
  18. // Accept on the returned net.Listener.
  19. func (c *ClientConn) Listen(n, addr string) (net.Listener, error) {
  20. laddr, err := net.ResolveTCPAddr(n, addr)
  21. if err != nil {
  22. return nil, err
  23. }
  24. return c.ListenTCP(laddr)
  25. }
  26. // RFC 4254 7.1
  27. type channelForwardMsg struct {
  28. Message string
  29. WantReply bool
  30. raddr string
  31. rport uint32
  32. }
  33. // Automatic port allocation is broken with OpenSSH before 6.0. See
  34. // also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In
  35. // particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0,
  36. // rather than the actual port number. This means you can never open
  37. // two different listeners with auto allocated ports. We work around
  38. // this by trying explicit ports until we succeed.
  39. const openSSHPrefix = "OpenSSH_"
  40. // isBrokenOpenSSHVersion returns true if the given version string
  41. // specifies a version of OpenSSH that is known to have a bug in port
  42. // forwarding.
  43. func isBrokenOpenSSHVersion(versionStr string) bool {
  44. i := strings.Index(versionStr, openSSHPrefix)
  45. if i < 0 {
  46. return false
  47. }
  48. i += len(openSSHPrefix)
  49. j := i
  50. for ; j < len(versionStr); j++ {
  51. if versionStr[j] < '0' || versionStr[j] > '9' {
  52. break
  53. }
  54. }
  55. version, _ := strconv.Atoi(versionStr[i:j])
  56. return version < 6
  57. }
  58. // autoPortListenWorkaround simulates automatic port allocation by
  59. // trying random ports repeatedly.
  60. func (c *ClientConn) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) {
  61. var sshListener net.Listener
  62. var err error
  63. const tries = 10
  64. for i := 0; i < tries; i++ {
  65. addr := *laddr
  66. addr.Port = 1024 + rand.Intn(60000)
  67. sshListener, err = c.ListenTCP(&addr)
  68. if err == nil {
  69. laddr.Port = addr.Port
  70. return sshListener, err
  71. }
  72. }
  73. return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err)
  74. }
  75. // ListenTCP requests the remote peer open a listening socket
  76. // on laddr. Incoming connections will be available by calling
  77. // Accept on the returned net.Listener.
  78. func (c *ClientConn) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) {
  79. if laddr.Port == 0 && isBrokenOpenSSHVersion(c.serverVersion) {
  80. return c.autoPortListenWorkaround(laddr)
  81. }
  82. m := channelForwardMsg{
  83. "tcpip-forward",
  84. true, // sendGlobalRequest waits for a reply
  85. laddr.IP.String(),
  86. uint32(laddr.Port),
  87. }
  88. // send message
  89. resp, err := c.sendGlobalRequest(m)
  90. if err != nil {
  91. return nil, err
  92. }
  93. // If the original port was 0, then the remote side will
  94. // supply a real port number in the response.
  95. if laddr.Port == 0 {
  96. port, _, ok := parseUint32(resp.Data)
  97. if !ok {
  98. return nil, errors.New("unable to parse response")
  99. }
  100. laddr.Port = int(port)
  101. }
  102. // Register this forward, using the port number we obtained.
  103. ch := c.forwardList.add(*laddr)
  104. return &tcpListener{laddr, c, ch}, nil
  105. }
  106. // forwardList stores a mapping between remote
  107. // forward requests and the tcpListeners.
  108. type forwardList struct {
  109. sync.Mutex
  110. entries []forwardEntry
  111. }
  112. // forwardEntry represents an established mapping of a laddr on a
  113. // remote ssh server to a channel connected to a tcpListener.
  114. type forwardEntry struct {
  115. laddr net.TCPAddr
  116. c chan forward
  117. }
  118. // forward represents an incoming forwarded tcpip connection. The
  119. // arguments to add/remove/lookup should be address as specified in
  120. // the original forward-request.
  121. type forward struct {
  122. c *clientChan // the ssh client channel underlying this forward
  123. raddr *net.TCPAddr // the raddr of the incoming connection
  124. }
  125. func (l *forwardList) add(addr net.TCPAddr) chan forward {
  126. l.Lock()
  127. defer l.Unlock()
  128. f := forwardEntry{
  129. addr,
  130. make(chan forward, 1),
  131. }
  132. l.entries = append(l.entries, f)
  133. return f.c
  134. }
  135. // remove removes the forward entry, and the channel feeding its
  136. // listener.
  137. func (l *forwardList) remove(addr net.TCPAddr) {
  138. l.Lock()
  139. defer l.Unlock()
  140. for i, f := range l.entries {
  141. if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port {
  142. l.entries = append(l.entries[:i], l.entries[i+1:]...)
  143. close(f.c)
  144. return
  145. }
  146. }
  147. }
  148. // closeAll closes and clears all forwards.
  149. func (l *forwardList) closeAll() {
  150. l.Lock()
  151. defer l.Unlock()
  152. for _, f := range l.entries {
  153. close(f.c)
  154. }
  155. l.entries = nil
  156. }
  157. func (l *forwardList) lookup(addr net.TCPAddr) (chan forward, bool) {
  158. l.Lock()
  159. defer l.Unlock()
  160. for _, f := range l.entries {
  161. if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port {
  162. return f.c, true
  163. }
  164. }
  165. return nil, false
  166. }
  167. type tcpListener struct {
  168. laddr *net.TCPAddr
  169. conn *ClientConn
  170. in <-chan forward
  171. }
  172. // Accept waits for and returns the next connection to the listener.
  173. func (l *tcpListener) Accept() (net.Conn, error) {
  174. s, ok := <-l.in
  175. if !ok {
  176. return nil, io.EOF
  177. }
  178. return &tcpChanConn{
  179. tcpChan: &tcpChan{
  180. clientChan: s.c,
  181. Reader: s.c.stdout,
  182. Writer: s.c.stdin,
  183. },
  184. laddr: l.laddr,
  185. raddr: s.raddr,
  186. }, nil
  187. }
  188. // Close closes the listener.
  189. func (l *tcpListener) Close() error {
  190. m := channelForwardMsg{
  191. "cancel-tcpip-forward",
  192. true,
  193. l.laddr.IP.String(),
  194. uint32(l.laddr.Port),
  195. }
  196. l.conn.forwardList.remove(*l.laddr)
  197. if _, err := l.conn.sendGlobalRequest(m); err != nil {
  198. return err
  199. }
  200. return nil
  201. }
  202. // Addr returns the listener's network address.
  203. func (l *tcpListener) Addr() net.Addr {
  204. return l.laddr
  205. }
  206. // Dial initiates a connection to the addr from the remote host.
  207. // addr is resolved using net.ResolveTCPAddr before connection.
  208. // This could allow an observer to observe the DNS name of the
  209. // remote host. Consider using ssh.DialTCP to avoid this.
  210. func (c *ClientConn) Dial(n, addr string) (net.Conn, error) {
  211. raddr, err := net.ResolveTCPAddr(n, addr)
  212. if err != nil {
  213. return nil, err
  214. }
  215. return c.DialTCP(n, nil, raddr)
  216. }
  217. // DialTCP connects to the remote address raddr on the network net,
  218. // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
  219. // as the local address for the connection.
  220. func (c *ClientConn) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
  221. if laddr == nil {
  222. laddr = &net.TCPAddr{
  223. IP: net.IPv4zero,
  224. Port: 0,
  225. }
  226. }
  227. ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
  228. if err != nil {
  229. return nil, err
  230. }
  231. return &tcpChanConn{
  232. tcpChan: ch,
  233. laddr: laddr,
  234. raddr: raddr,
  235. }, nil
  236. }
  237. // RFC 4254 7.2
  238. type channelOpenDirectMsg struct {
  239. ChanType string
  240. PeersId uint32
  241. PeersWindow uint32
  242. MaxPacketSize uint32
  243. raddr string
  244. rport uint32
  245. laddr string
  246. lport uint32
  247. }
  248. // dial opens a direct-tcpip connection to the remote server. laddr and raddr are passed as
  249. // strings and are expected to be resolveable at the remote end.
  250. func (c *ClientConn) dial(laddr string, lport int, raddr string, rport int) (*tcpChan, error) {
  251. ch := c.newChan(c.transport)
  252. if err := c.writePacket(marshal(msgChannelOpen, channelOpenDirectMsg{
  253. ChanType: "direct-tcpip",
  254. PeersId: ch.localId,
  255. PeersWindow: 1 << 14,
  256. MaxPacketSize: 1 << 15, // RFC 4253 6.1
  257. raddr: raddr,
  258. rport: uint32(rport),
  259. laddr: laddr,
  260. lport: uint32(lport),
  261. })); err != nil {
  262. c.chanList.remove(ch.localId)
  263. return nil, err
  264. }
  265. if err := ch.waitForChannelOpenResponse(); err != nil {
  266. c.chanList.remove(ch.localId)
  267. return nil, fmt.Errorf("ssh: unable to open direct tcpip connection: %v", err)
  268. }
  269. return &tcpChan{
  270. clientChan: ch,
  271. Reader: ch.stdout,
  272. Writer: ch.stdin,
  273. }, nil
  274. }
  275. type tcpChan struct {
  276. *clientChan // the backing channel
  277. io.Reader
  278. io.Writer
  279. }
  280. // tcpChanConn fulfills the net.Conn interface without
  281. // the tcpChan having to hold laddr or raddr directly.
  282. type tcpChanConn struct {
  283. *tcpChan
  284. laddr, raddr net.Addr
  285. }
  286. // LocalAddr returns the local network address.
  287. func (t *tcpChanConn) LocalAddr() net.Addr {
  288. return t.laddr
  289. }
  290. // RemoteAddr returns the remote network address.
  291. func (t *tcpChanConn) RemoteAddr() net.Addr {
  292. return t.raddr
  293. }
  294. // SetDeadline sets the read and write deadlines associated
  295. // with the connection.
  296. func (t *tcpChanConn) SetDeadline(deadline time.Time) error {
  297. if err := t.SetReadDeadline(deadline); err != nil {
  298. return err
  299. }
  300. return t.SetWriteDeadline(deadline)
  301. }
  302. // SetReadDeadline sets the read deadline.
  303. // A zero value for t means Read will not time out.
  304. // After the deadline, the error from Read will implement net.Error
  305. // with Timeout() == true.
  306. func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error {
  307. return errors.New("ssh: tcpChan: deadline not supported")
  308. }
  309. // SetWriteDeadline exists to satisfy the net.Conn interface
  310. // but is not implemented by this type. It always returns an error.
  311. func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error {
  312. return errors.New("ssh: tcpChan: deadline not supported")
  313. }