1
0

server.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ssh
  15. import (
  16. "context"
  17. "encoding/binary"
  18. "fmt"
  19. "net"
  20. "strings"
  21. "time"
  22. libio "github.com/fatedier/golib/io"
  23. "github.com/samber/lo"
  24. "github.com/spf13/cobra"
  25. "golang.org/x/crypto/ssh"
  26. "github.com/fatedier/frp/pkg/config"
  27. v1 "github.com/fatedier/frp/pkg/config/v1"
  28. "github.com/fatedier/frp/pkg/msg"
  29. utilnet "github.com/fatedier/frp/pkg/util/net"
  30. "github.com/fatedier/frp/pkg/util/util"
  31. "github.com/fatedier/frp/pkg/util/xlog"
  32. "github.com/fatedier/frp/pkg/virtual"
  33. )
  34. const (
  35. // https://datatracker.ietf.org/doc/html/rfc4254#page-16
  36. ChannelTypeServerOpenChannel = "forwarded-tcpip"
  37. RequestTypeForward = "tcpip-forward"
  38. )
  39. type tcpipForward struct {
  40. Host string
  41. Port uint32
  42. }
  43. // https://datatracker.ietf.org/doc/html/rfc4254#page-16
  44. type forwardedTCPPayload struct {
  45. Addr string
  46. Port uint32
  47. // can be default empty value but do not delete it
  48. // because ssh protocol shoule be reserved
  49. OriginAddr string
  50. OriginPort uint32
  51. }
  52. type TunnelServer struct {
  53. underlyingConn net.Conn
  54. sshConn *ssh.ServerConn
  55. sc *ssh.ServerConfig
  56. vc *virtual.Client
  57. serverPeerListener *utilnet.InternalListener
  58. doneCh chan struct{}
  59. }
  60. func NewTunnelServer(conn net.Conn, sc *ssh.ServerConfig, serverPeerListener *utilnet.InternalListener) (*TunnelServer, error) {
  61. s := &TunnelServer{
  62. underlyingConn: conn,
  63. sc: sc,
  64. serverPeerListener: serverPeerListener,
  65. doneCh: make(chan struct{}),
  66. }
  67. return s, nil
  68. }
  69. func (s *TunnelServer) Run() error {
  70. sshConn, channels, requests, err := ssh.NewServerConn(s.underlyingConn, s.sc)
  71. if err != nil {
  72. return err
  73. }
  74. s.sshConn = sshConn
  75. addr, extraPayload, err := s.waitForwardAddrAndExtraPayload(channels, requests, 3*time.Second)
  76. if err != nil {
  77. return err
  78. }
  79. clientCfg, pc, err := s.parseClientAndProxyConfigurer(addr, extraPayload)
  80. if err != nil {
  81. return err
  82. }
  83. clientCfg.User = util.EmptyOr(sshConn.Permissions.Extensions["user"], clientCfg.User)
  84. pc.Complete(clientCfg.User)
  85. s.vc = virtual.NewClient(clientCfg)
  86. // join workConn and ssh channel
  87. s.vc.SetInWorkConnCallback(func(base *v1.ProxyBaseConfig, workConn net.Conn, m *msg.StartWorkConn) bool {
  88. c, err := s.openConn(addr)
  89. if err != nil {
  90. return false
  91. }
  92. libio.Join(c, workConn)
  93. return false
  94. })
  95. // transfer connection from virtual client to server peer listener
  96. go func() {
  97. l := s.vc.PeerListener()
  98. for {
  99. conn, err := l.Accept()
  100. if err != nil {
  101. return
  102. }
  103. _ = s.serverPeerListener.PutConn(conn)
  104. }
  105. }()
  106. xl := xlog.New().AddPrefix(xlog.LogPrefix{Name: "sshVirtualClient", Value: "sshVirtualClient", Priority: 100})
  107. ctx := xlog.NewContext(context.Background(), xl)
  108. go func() {
  109. _ = s.vc.Run(ctx)
  110. }()
  111. s.vc.UpdateProxyConfigurer([]v1.ProxyConfigurer{pc})
  112. _ = sshConn.Wait()
  113. _ = sshConn.Close()
  114. s.vc.Close()
  115. close(s.doneCh)
  116. return nil
  117. }
  118. func (s *TunnelServer) waitForwardAddrAndExtraPayload(
  119. channels <-chan ssh.NewChannel,
  120. requests <-chan *ssh.Request,
  121. timeout time.Duration,
  122. ) (*tcpipForward, string, error) {
  123. addrCh := make(chan *tcpipForward, 1)
  124. extraPayloadCh := make(chan string, 1)
  125. // get forward address
  126. go func() {
  127. addrGot := false
  128. for req := range requests {
  129. switch req.Type {
  130. case RequestTypeForward:
  131. if !addrGot {
  132. payload := tcpipForward{}
  133. if err := ssh.Unmarshal(req.Payload, &payload); err != nil {
  134. return
  135. }
  136. addrGot = true
  137. addrCh <- &payload
  138. }
  139. default:
  140. if req.WantReply {
  141. _ = req.Reply(true, nil)
  142. }
  143. }
  144. }
  145. }()
  146. // get extra payload
  147. go func() {
  148. for newChannel := range channels {
  149. // extraPayload will send to extraPayloadCh
  150. go s.handleNewChannel(newChannel, extraPayloadCh)
  151. }
  152. }()
  153. var (
  154. addr *tcpipForward
  155. extraPayload string
  156. )
  157. timer := time.NewTimer(timeout)
  158. defer timer.Stop()
  159. for {
  160. select {
  161. case v := <-addrCh:
  162. addr = v
  163. case extra := <-extraPayloadCh:
  164. extraPayload = extra
  165. case <-timer.C:
  166. return nil, "", fmt.Errorf("get addr and extra payload timeout")
  167. }
  168. if addr != nil && extraPayload != "" {
  169. break
  170. }
  171. }
  172. return addr, extraPayload, nil
  173. }
  174. func (s *TunnelServer) parseClientAndProxyConfigurer(_ *tcpipForward, extraPayload string) (*v1.ClientCommonConfig, v1.ProxyConfigurer, error) {
  175. cmd := &cobra.Command{}
  176. args := strings.Split(extraPayload, " ")
  177. if len(args) < 1 {
  178. return nil, nil, fmt.Errorf("invalid extra payload")
  179. }
  180. proxyType := strings.TrimSpace(args[0])
  181. supportTypes := []string{"tcp", "http", "https", "tcpmux", "stcp"}
  182. if !lo.Contains(supportTypes, proxyType) {
  183. return nil, nil, fmt.Errorf("invalid proxy type: %s, support types: %v", proxyType, supportTypes)
  184. }
  185. pc := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType))
  186. if pc == nil {
  187. return nil, nil, fmt.Errorf("new proxy configurer error")
  188. }
  189. config.RegisterProxyFlags(cmd, pc)
  190. clientCfg := v1.ClientCommonConfig{}
  191. config.RegisterClientCommonConfigFlags(cmd, &clientCfg)
  192. if err := cmd.ParseFlags(args); err != nil {
  193. return nil, nil, fmt.Errorf("parse flags from ssh client error: %v", err)
  194. }
  195. return &clientCfg, pc, nil
  196. }
  197. func (s *TunnelServer) handleNewChannel(channel ssh.NewChannel, extraPayloadCh chan string) {
  198. ch, reqs, err := channel.Accept()
  199. if err != nil {
  200. return
  201. }
  202. go s.keepAlive(ch)
  203. for req := range reqs {
  204. if req.Type != "exec" {
  205. continue
  206. }
  207. if len(req.Payload) <= 4 {
  208. continue
  209. }
  210. end := 4 + binary.BigEndian.Uint32(req.Payload[:4])
  211. if len(req.Payload) < int(end) {
  212. continue
  213. }
  214. extraPayload := string(req.Payload[4:end])
  215. select {
  216. case extraPayloadCh <- extraPayload:
  217. default:
  218. }
  219. }
  220. }
  221. func (s *TunnelServer) keepAlive(ch ssh.Channel) {
  222. tk := time.NewTicker(time.Second * 30)
  223. defer tk.Stop()
  224. for {
  225. select {
  226. case <-tk.C:
  227. _, err := ch.SendRequest("heartbeat", false, nil)
  228. if err != nil {
  229. return
  230. }
  231. case <-s.doneCh:
  232. return
  233. }
  234. }
  235. }
  236. func (s *TunnelServer) openConn(addr *tcpipForward) (net.Conn, error) {
  237. payload := forwardedTCPPayload{
  238. Addr: addr.Host,
  239. Port: addr.Port,
  240. }
  241. channel, reqs, err := s.sshConn.OpenChannel(ChannelTypeServerOpenChannel, ssh.Marshal(&payload))
  242. if err != nil {
  243. return nil, fmt.Errorf("open ssh channel error: %v", err)
  244. }
  245. go ssh.DiscardRequests(reqs)
  246. conn := utilnet.WrapReadWriteCloserToConn(channel, s.underlyingConn)
  247. return conn, nil
  248. }