tcpip.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. // Automatic port allocation is broken with OpenSSH before 6.0. See
  27. // also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In
  28. // particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0,
  29. // rather than the actual port number. This means you can never open
  30. // two different listeners with auto allocated ports. We work around
  31. // this by trying explicit ports until we succeed.
  32. const openSSHPrefix = "OpenSSH_"
  33. var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano()))
  34. // isBrokenOpenSSHVersion returns true if the given version string
  35. // specifies a version of OpenSSH that is known to have a bug in port
  36. // forwarding.
  37. func isBrokenOpenSSHVersion(versionStr string) bool {
  38. i := strings.Index(versionStr, openSSHPrefix)
  39. if i < 0 {
  40. return false
  41. }
  42. i += len(openSSHPrefix)
  43. j := i
  44. for ; j < len(versionStr); j++ {
  45. if versionStr[j] < '0' || versionStr[j] > '9' {
  46. break
  47. }
  48. }
  49. version, _ := strconv.Atoi(versionStr[i:j])
  50. return version < 6
  51. }
  52. // autoPortListenWorkaround simulates automatic port allocation by
  53. // trying random ports repeatedly.
  54. func (c *ClientConn) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) {
  55. var sshListener net.Listener
  56. var err error
  57. const tries = 10
  58. for i := 0; i < tries; i++ {
  59. addr := *laddr
  60. addr.Port = 1024 + portRandomizer.Intn(60000)
  61. sshListener, err = c.ListenTCP(&addr)
  62. if err == nil {
  63. laddr.Port = addr.Port
  64. return sshListener, err
  65. }
  66. }
  67. return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err)
  68. }
  69. // RFC 4254 7.1
  70. type channelForwardMsg struct {
  71. Message string
  72. WantReply bool
  73. raddr string
  74. rport uint32
  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. // The resulting connection has a zero LocalAddr() and RemoteAddr().
  209. func (c *ClientConn) Dial(n, addr string) (net.Conn, error) {
  210. // Parse the address into host and numeric port.
  211. host, portString, err := net.SplitHostPort(addr)
  212. if err != nil {
  213. return nil, err
  214. }
  215. port, err := strconv.ParseUint(portString, 10, 16)
  216. if err != nil {
  217. return nil, err
  218. }
  219. // Use a zero address for local and remote address.
  220. zeroAddr := &net.TCPAddr{
  221. IP: net.IPv4zero,
  222. Port: 0,
  223. }
  224. ch, err := c.dial(net.IPv4zero.String(), 0, host, int(port))
  225. if err != nil {
  226. return nil, err
  227. }
  228. return &tcpChanConn{
  229. tcpChan: ch,
  230. laddr: zeroAddr,
  231. raddr: zeroAddr,
  232. }, nil
  233. }
  234. // DialTCP connects to the remote address raddr on the network net,
  235. // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
  236. // as the local address for the connection.
  237. func (c *ClientConn) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
  238. if laddr == nil {
  239. laddr = &net.TCPAddr{
  240. IP: net.IPv4zero,
  241. Port: 0,
  242. }
  243. }
  244. ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return &tcpChanConn{
  249. tcpChan: ch,
  250. laddr: laddr,
  251. raddr: raddr,
  252. }, nil
  253. }
  254. // RFC 4254 7.2
  255. type channelOpenDirectMsg struct {
  256. ChanType string
  257. PeersId uint32
  258. PeersWindow uint32
  259. MaxPacketSize uint32
  260. raddr string
  261. rport uint32
  262. laddr string
  263. lport uint32
  264. }
  265. // dial opens a direct-tcpip connection to the remote server. laddr and raddr are passed as
  266. // strings and are expected to be resolvable at the remote end.
  267. func (c *ClientConn) dial(laddr string, lport int, raddr string, rport int) (*tcpChan, error) {
  268. ch := c.newChan(c.transport)
  269. if err := c.transport.writePacket(marshal(msgChannelOpen, channelOpenDirectMsg{
  270. ChanType: "direct-tcpip",
  271. PeersId: ch.localId,
  272. PeersWindow: 1 << 14,
  273. MaxPacketSize: 1 << 15, // RFC 4253 6.1
  274. raddr: raddr,
  275. rport: uint32(rport),
  276. laddr: laddr,
  277. lport: uint32(lport),
  278. })); err != nil {
  279. c.chanList.remove(ch.localId)
  280. return nil, err
  281. }
  282. if err := ch.waitForChannelOpenResponse(); err != nil {
  283. c.chanList.remove(ch.localId)
  284. return nil, fmt.Errorf("ssh: unable to open direct tcpip connection: %v", err)
  285. }
  286. return &tcpChan{
  287. clientChan: ch,
  288. Reader: ch.stdout,
  289. Writer: ch.stdin,
  290. }, nil
  291. }
  292. type tcpChan struct {
  293. *clientChan // the backing channel
  294. io.Reader
  295. io.Writer
  296. }
  297. // tcpChanConn fulfills the net.Conn interface without
  298. // the tcpChan having to hold laddr or raddr directly.
  299. type tcpChanConn struct {
  300. *tcpChan
  301. laddr, raddr net.Addr
  302. }
  303. // LocalAddr returns the local network address.
  304. func (t *tcpChanConn) LocalAddr() net.Addr {
  305. return t.laddr
  306. }
  307. // RemoteAddr returns the remote network address.
  308. func (t *tcpChanConn) RemoteAddr() net.Addr {
  309. return t.raddr
  310. }
  311. // SetDeadline sets the read and write deadlines associated
  312. // with the connection.
  313. func (t *tcpChanConn) SetDeadline(deadline time.Time) error {
  314. if err := t.SetReadDeadline(deadline); err != nil {
  315. return err
  316. }
  317. return t.SetWriteDeadline(deadline)
  318. }
  319. // SetReadDeadline sets the read deadline.
  320. // A zero value for t means Read will not time out.
  321. // After the deadline, the error from Read will implement net.Error
  322. // with Timeout() == true.
  323. func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error {
  324. return errors.New("ssh: tcpChan: deadline not supported")
  325. }
  326. // SetWriteDeadline exists to satisfy the net.Conn interface
  327. // but is not implemented by this type. It always returns an error.
  328. func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error {
  329. return errors.New("ssh: tcpChan: deadline not supported")
  330. }