tcpip.go 9.3 KB

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