tcpip.go 13 KB

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