You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

407 lines
10 KiB

  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. // See RFC 4254, section 7.2
  139. type forwardedTCPPayload struct {
  140. Addr string
  141. Port uint32
  142. OriginAddr string
  143. OriginPort uint32
  144. }
  145. // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr.
  146. func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) {
  147. if port == 0 || port > 65535 {
  148. return nil, fmt.Errorf("ssh: port number out of range: %d", port)
  149. }
  150. ip := net.ParseIP(string(addr))
  151. if ip == nil {
  152. return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr)
  153. }
  154. return &net.TCPAddr{IP: ip, Port: int(port)}, nil
  155. }
  156. func (l *forwardList) handleChannels(in <-chan NewChannel) {
  157. for ch := range in {
  158. var payload forwardedTCPPayload
  159. if err := Unmarshal(ch.ExtraData(), &payload); err != nil {
  160. ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error())
  161. continue
  162. }
  163. // RFC 4254 section 7.2 specifies that incoming
  164. // addresses should list the address, in string
  165. // format. It is implied that this should be an IP
  166. // address, as it would be impossible to connect to it
  167. // otherwise.
  168. laddr, err := parseTCPAddr(payload.Addr, payload.Port)
  169. if err != nil {
  170. ch.Reject(ConnectionFailed, err.Error())
  171. continue
  172. }
  173. raddr, err := parseTCPAddr(payload.OriginAddr, payload.OriginPort)
  174. if err != nil {
  175. ch.Reject(ConnectionFailed, err.Error())
  176. continue
  177. }
  178. if ok := l.forward(*laddr, *raddr, ch); !ok {
  179. // Section 7.2, implementations MUST reject spurious incoming
  180. // connections.
  181. ch.Reject(Prohibited, "no forward for address")
  182. continue
  183. }
  184. }
  185. }
  186. // remove removes the forward entry, and the channel feeding its
  187. // listener.
  188. func (l *forwardList) remove(addr net.TCPAddr) {
  189. l.Lock()
  190. defer l.Unlock()
  191. for i, f := range l.entries {
  192. if addr.IP.Equal(f.laddr.IP) && addr.Port == f.laddr.Port {
  193. l.entries = append(l.entries[:i], l.entries[i+1:]...)
  194. close(f.c)
  195. return
  196. }
  197. }
  198. }
  199. // closeAll closes and clears all forwards.
  200. func (l *forwardList) closeAll() {
  201. l.Lock()
  202. defer l.Unlock()
  203. for _, f := range l.entries {
  204. close(f.c)
  205. }
  206. l.entries = nil
  207. }
  208. func (l *forwardList) forward(laddr, raddr net.TCPAddr, ch NewChannel) bool {
  209. l.Lock()
  210. defer l.Unlock()
  211. for _, f := range l.entries {
  212. if laddr.IP.Equal(f.laddr.IP) && laddr.Port == f.laddr.Port {
  213. f.c <- forward{ch, &raddr}
  214. return true
  215. }
  216. }
  217. return false
  218. }
  219. type tcpListener struct {
  220. laddr *net.TCPAddr
  221. conn *Client
  222. in <-chan forward
  223. }
  224. // Accept waits for and returns the next connection to the listener.
  225. func (l *tcpListener) Accept() (net.Conn, error) {
  226. s, ok := <-l.in
  227. if !ok {
  228. return nil, io.EOF
  229. }
  230. ch, incoming, err := s.newCh.Accept()
  231. if err != nil {
  232. return nil, err
  233. }
  234. go DiscardRequests(incoming)
  235. return &tcpChanConn{
  236. Channel: ch,
  237. laddr: l.laddr,
  238. raddr: s.raddr,
  239. }, nil
  240. }
  241. // Close closes the listener.
  242. func (l *tcpListener) Close() error {
  243. m := channelForwardMsg{
  244. l.laddr.IP.String(),
  245. uint32(l.laddr.Port),
  246. }
  247. // this also closes the listener.
  248. l.conn.forwards.remove(*l.laddr)
  249. ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m))
  250. if err == nil && !ok {
  251. err = errors.New("ssh: cancel-tcpip-forward failed")
  252. }
  253. return err
  254. }
  255. // Addr returns the listener's network address.
  256. func (l *tcpListener) Addr() net.Addr {
  257. return l.laddr
  258. }
  259. // Dial initiates a connection to the addr from the remote host.
  260. // The resulting connection has a zero LocalAddr() and RemoteAddr().
  261. func (c *Client) Dial(n, addr string) (net.Conn, error) {
  262. // Parse the address into host and numeric port.
  263. host, portString, err := net.SplitHostPort(addr)
  264. if err != nil {
  265. return nil, err
  266. }
  267. port, err := strconv.ParseUint(portString, 10, 16)
  268. if err != nil {
  269. return nil, err
  270. }
  271. // Use a zero address for local and remote address.
  272. zeroAddr := &net.TCPAddr{
  273. IP: net.IPv4zero,
  274. Port: 0,
  275. }
  276. ch, err := c.dial(net.IPv4zero.String(), 0, host, int(port))
  277. if err != nil {
  278. return nil, err
  279. }
  280. return &tcpChanConn{
  281. Channel: ch,
  282. laddr: zeroAddr,
  283. raddr: zeroAddr,
  284. }, nil
  285. }
  286. // DialTCP connects to the remote address raddr on the network net,
  287. // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
  288. // as the local address for the connection.
  289. func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
  290. if laddr == nil {
  291. laddr = &net.TCPAddr{
  292. IP: net.IPv4zero,
  293. Port: 0,
  294. }
  295. }
  296. ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
  297. if err != nil {
  298. return nil, err
  299. }
  300. return &tcpChanConn{
  301. Channel: ch,
  302. laddr: laddr,
  303. raddr: raddr,
  304. }, nil
  305. }
  306. // RFC 4254 7.2
  307. type channelOpenDirectMsg struct {
  308. raddr string
  309. rport uint32
  310. laddr string
  311. lport uint32
  312. }
  313. func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) {
  314. msg := channelOpenDirectMsg{
  315. raddr: raddr,
  316. rport: uint32(rport),
  317. laddr: laddr,
  318. lport: uint32(lport),
  319. }
  320. ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg))
  321. if err != nil {
  322. return nil, err
  323. }
  324. go DiscardRequests(in)
  325. return ch, err
  326. }
  327. type tcpChan struct {
  328. Channel // the backing channel
  329. }
  330. // tcpChanConn fulfills the net.Conn interface without
  331. // the tcpChan having to hold laddr or raddr directly.
  332. type tcpChanConn struct {
  333. Channel
  334. laddr, raddr net.Addr
  335. }
  336. // LocalAddr returns the local network address.
  337. func (t *tcpChanConn) LocalAddr() net.Addr {
  338. return t.laddr
  339. }
  340. // RemoteAddr returns the remote network address.
  341. func (t *tcpChanConn) RemoteAddr() net.Addr {
  342. return t.raddr
  343. }
  344. // SetDeadline sets the read and write deadlines associated
  345. // with the connection.
  346. func (t *tcpChanConn) SetDeadline(deadline time.Time) error {
  347. if err := t.SetReadDeadline(deadline); err != nil {
  348. return err
  349. }
  350. return t.SetWriteDeadline(deadline)
  351. }
  352. // SetReadDeadline sets the read deadline.
  353. // A zero value for t means Read will not time out.
  354. // After the deadline, the error from Read will implement net.Error
  355. // with Timeout() == true.
  356. func (t *tcpChanConn) SetReadDeadline(deadline time.Time) error {
  357. return errors.New("ssh: tcpChan: deadline not supported")
  358. }
  359. // SetWriteDeadline exists to satisfy the net.Conn interface
  360. // but is not implemented by this type. It always returns an error.
  361. func (t *tcpChanConn) SetWriteDeadline(deadline time.Time) error {
  362. return errors.New("ssh: tcpChan: deadline not supported")
  363. }