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.

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