tcpip.go 12 KB

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