tcpip.go 9.0 KB

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