tcpip.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. // [Psiphon]
  300. // directTCPIPNoSplitTunnel is the same as "direct-tcpip", except it indicates
  301. // custom split tunnel behavior. It shares the same payload. We allow the
  302. // Client.Dial network type to optionally specify a channel type instead.
  303. const directTCPIPNoSplitTunnel = "direct-tcpip-no-split-tunnel@psiphon.ca"
  304. // Dial initiates a connection to the addr from the remote host.
  305. // The resulting connection has a zero LocalAddr() and RemoteAddr().
  306. func (c *Client) Dial(n, addr string) (net.Conn, error) {
  307. var ch Channel
  308. switch n {
  309. case "tcp", "tcp4", "tcp6", "direct-tcpip", directTCPIPNoSplitTunnel:
  310. // Parse the address into host and numeric port.
  311. host, portString, err := net.SplitHostPort(addr)
  312. if err != nil {
  313. return nil, err
  314. }
  315. port, err := strconv.ParseUint(portString, 10, 16)
  316. if err != nil {
  317. return nil, err
  318. }
  319. // [Psiphon]
  320. channelType := "direct-tcpip"
  321. if n == directTCPIPNoSplitTunnel {
  322. channelType = directTCPIPNoSplitTunnel
  323. }
  324. ch, err = c.dial(channelType, net.IPv4zero.String(), 0, host, int(port))
  325. if err != nil {
  326. return nil, err
  327. }
  328. // Use a zero address for local and remote address.
  329. zeroAddr := &net.TCPAddr{
  330. IP: net.IPv4zero,
  331. Port: 0,
  332. }
  333. return &chanConn{
  334. Channel: ch,
  335. laddr: zeroAddr,
  336. raddr: zeroAddr,
  337. }, nil
  338. case "unix":
  339. var err error
  340. ch, err = c.dialStreamLocal(addr)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return &chanConn{
  345. Channel: ch,
  346. laddr: &net.UnixAddr{
  347. Name: "@",
  348. Net: "unix",
  349. },
  350. raddr: &net.UnixAddr{
  351. Name: addr,
  352. Net: "unix",
  353. },
  354. }, nil
  355. default:
  356. return nil, fmt.Errorf("ssh: unsupported protocol: %s", n)
  357. }
  358. }
  359. // DialTCP connects to the remote address raddr on the network net,
  360. // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
  361. // as the local address for the connection.
  362. func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
  363. if laddr == nil {
  364. laddr = &net.TCPAddr{
  365. IP: net.IPv4zero,
  366. Port: 0,
  367. }
  368. }
  369. ch, err := c.dial("direct-tcpip", laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port)
  370. if err != nil {
  371. return nil, err
  372. }
  373. return &chanConn{
  374. Channel: ch,
  375. laddr: laddr,
  376. raddr: raddr,
  377. }, nil
  378. }
  379. // RFC 4254 7.2
  380. type channelOpenDirectMsg struct {
  381. raddr string
  382. rport uint32
  383. laddr string
  384. lport uint32
  385. }
  386. func (c *Client) dial(channelType string, laddr string, lport int, raddr string, rport int) (Channel, error) {
  387. msg := channelOpenDirectMsg{
  388. raddr: raddr,
  389. rport: uint32(rport),
  390. laddr: laddr,
  391. lport: uint32(lport),
  392. }
  393. ch, in, err := c.OpenChannel(channelType, Marshal(&msg))
  394. if err != nil {
  395. return nil, err
  396. }
  397. go DiscardRequests(in)
  398. return ch, err
  399. }
  400. type tcpChan struct {
  401. Channel // the backing channel
  402. }
  403. // chanConn fulfills the net.Conn interface without
  404. // the tcpChan having to hold laddr or raddr directly.
  405. type chanConn struct {
  406. Channel
  407. laddr, raddr net.Addr
  408. }
  409. // LocalAddr returns the local network address.
  410. func (t *chanConn) LocalAddr() net.Addr {
  411. return t.laddr
  412. }
  413. // RemoteAddr returns the remote network address.
  414. func (t *chanConn) RemoteAddr() net.Addr {
  415. return t.raddr
  416. }
  417. // SetDeadline sets the read and write deadlines associated
  418. // with the connection.
  419. func (t *chanConn) SetDeadline(deadline time.Time) error {
  420. if err := t.SetReadDeadline(deadline); err != nil {
  421. return err
  422. }
  423. return t.SetWriteDeadline(deadline)
  424. }
  425. // SetReadDeadline sets the read deadline.
  426. // A zero value for t means Read will not time out.
  427. // After the deadline, the error from Read will implement net.Error
  428. // with Timeout() == true.
  429. func (t *chanConn) SetReadDeadline(deadline time.Time) error {
  430. // for compatibility with previous version,
  431. // the error message contains "tcpChan"
  432. return errors.New("ssh: tcpChan: deadline not supported")
  433. }
  434. // SetWriteDeadline exists to satisfy the net.Conn interface
  435. // but is not implemented by this type. It always returns an error.
  436. func (t *chanConn) SetWriteDeadline(deadline time.Time) error {
  437. return errors.New("ssh: tcpChan: deadline not supported")
  438. }