1
0

controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 nathole
  15. import (
  16. "context"
  17. "crypto/md5"
  18. "encoding/hex"
  19. "fmt"
  20. "net"
  21. "strconv"
  22. "sync"
  23. "time"
  24. "github.com/fatedier/golib/errors"
  25. "github.com/samber/lo"
  26. "golang.org/x/sync/errgroup"
  27. "github.com/fatedier/frp/pkg/msg"
  28. "github.com/fatedier/frp/pkg/transport"
  29. "github.com/fatedier/frp/pkg/util/log"
  30. "github.com/fatedier/frp/pkg/util/util"
  31. )
  32. // NatHoleTimeout seconds.
  33. var NatHoleTimeout int64 = 10
  34. func NewTransactionID() string {
  35. id, _ := util.RandID()
  36. return fmt.Sprintf("%d%s", time.Now().Unix(), id)
  37. }
  38. type ClientCfg struct {
  39. name string
  40. sk string
  41. allowUsers []string
  42. sidCh chan string
  43. }
  44. type Session struct {
  45. sid string
  46. analysisKey string
  47. recommandMode int
  48. recommandIndex int
  49. visitorMsg *msg.NatHoleVisitor
  50. visitorTransporter transport.MessageTransporter
  51. vResp *msg.NatHoleResp
  52. vNatFeature *NatFeature
  53. vBehavior RecommandBehavior
  54. clientMsg *msg.NatHoleClient
  55. clientTransporter transport.MessageTransporter
  56. cResp *msg.NatHoleResp
  57. cNatFeature *NatFeature
  58. cBehavior RecommandBehavior
  59. notifyCh chan struct{}
  60. }
  61. func (s *Session) genAnalysisKey() {
  62. hash := md5.New()
  63. vIPs := lo.Uniq(parseIPs(s.visitorMsg.MappedAddrs))
  64. if len(vIPs) > 0 {
  65. hash.Write([]byte(vIPs[0]))
  66. }
  67. hash.Write([]byte(s.vNatFeature.NatType))
  68. hash.Write([]byte(s.vNatFeature.Behavior))
  69. hash.Write([]byte(strconv.FormatBool(s.vNatFeature.RegularPortsChange)))
  70. cIPs := lo.Uniq(parseIPs(s.clientMsg.MappedAddrs))
  71. if len(cIPs) > 0 {
  72. hash.Write([]byte(cIPs[0]))
  73. }
  74. hash.Write([]byte(s.cNatFeature.NatType))
  75. hash.Write([]byte(s.cNatFeature.Behavior))
  76. hash.Write([]byte(strconv.FormatBool(s.cNatFeature.RegularPortsChange)))
  77. s.analysisKey = hex.EncodeToString(hash.Sum(nil))
  78. }
  79. type Controller struct {
  80. clientCfgs map[string]*ClientCfg
  81. sessions map[string]*Session
  82. analyzer *Analyzer
  83. mu sync.RWMutex
  84. }
  85. func NewController(analysisDataReserveDuration time.Duration) (*Controller, error) {
  86. return &Controller{
  87. clientCfgs: make(map[string]*ClientCfg),
  88. sessions: make(map[string]*Session),
  89. analyzer: NewAnalyzer(analysisDataReserveDuration),
  90. }, nil
  91. }
  92. func (c *Controller) CleanWorker(ctx context.Context) {
  93. ticker := time.NewTicker(time.Hour)
  94. defer ticker.Stop()
  95. for {
  96. select {
  97. case <-ticker.C:
  98. start := time.Now()
  99. count, total := c.analyzer.Clean()
  100. log.Trace("clean %d/%d nathole analysis data, cost %v", count, total, time.Since(start))
  101. case <-ctx.Done():
  102. return
  103. }
  104. }
  105. }
  106. func (c *Controller) ListenClient(name string, sk string, allowUsers []string) (chan string, error) {
  107. cfg := &ClientCfg{
  108. name: name,
  109. sk: sk,
  110. allowUsers: allowUsers,
  111. sidCh: make(chan string),
  112. }
  113. c.mu.Lock()
  114. defer c.mu.Unlock()
  115. if _, ok := c.clientCfgs[name]; ok {
  116. return nil, fmt.Errorf("proxy [%s] is repeated", name)
  117. }
  118. c.clientCfgs[name] = cfg
  119. return cfg.sidCh, nil
  120. }
  121. func (c *Controller) CloseClient(name string) {
  122. c.mu.Lock()
  123. defer c.mu.Unlock()
  124. delete(c.clientCfgs, name)
  125. }
  126. func (c *Controller) GenSid() string {
  127. t := time.Now().Unix()
  128. id, _ := util.RandID()
  129. return fmt.Sprintf("%d%s", t, id)
  130. }
  131. func (c *Controller) HandleVisitor(m *msg.NatHoleVisitor, transporter transport.MessageTransporter, visitorUser string) {
  132. if m.PreCheck {
  133. cfg, ok := c.clientCfgs[m.ProxyName]
  134. if !ok {
  135. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp server for [%s] doesn't exist", m.ProxyName)))
  136. return
  137. }
  138. if !lo.Contains(cfg.allowUsers, visitorUser) && !lo.Contains(cfg.allowUsers, "*") {
  139. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, fmt.Sprintf("xtcp visitor user [%s] not allowed for [%s]", visitorUser, m.ProxyName)))
  140. return
  141. }
  142. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, ""))
  143. return
  144. }
  145. sid := c.GenSid()
  146. session := &Session{
  147. sid: sid,
  148. visitorMsg: m,
  149. visitorTransporter: transporter,
  150. notifyCh: make(chan struct{}, 1),
  151. }
  152. var (
  153. clientCfg *ClientCfg
  154. ok bool
  155. )
  156. err := func() error {
  157. c.mu.Lock()
  158. defer c.mu.Unlock()
  159. clientCfg, ok = c.clientCfgs[m.ProxyName]
  160. if !ok {
  161. return fmt.Errorf("xtcp server for [%s] doesn't exist", m.ProxyName)
  162. }
  163. if !util.ConstantTimeEqString(m.SignKey, util.GetAuthKey(clientCfg.sk, m.Timestamp)) {
  164. return fmt.Errorf("xtcp connection of [%s] auth failed", m.ProxyName)
  165. }
  166. c.sessions[sid] = session
  167. return nil
  168. }()
  169. if err != nil {
  170. log.Warn("handle visitorMsg error: %v", err)
  171. _ = transporter.Send(c.GenNatHoleResponse(m.TransactionID, nil, err.Error()))
  172. return
  173. }
  174. log.Trace("handle visitor message, sid [%s], server name: %s", sid, m.ProxyName)
  175. defer func() {
  176. c.mu.Lock()
  177. defer c.mu.Unlock()
  178. delete(c.sessions, sid)
  179. }()
  180. if err := errors.PanicToError(func() {
  181. clientCfg.sidCh <- sid
  182. }); err != nil {
  183. return
  184. }
  185. // wait for NatHoleClient message
  186. select {
  187. case <-session.notifyCh:
  188. case <-time.After(time.Duration(NatHoleTimeout) * time.Second):
  189. log.Debug("wait for NatHoleClient message timeout, sid [%s]", sid)
  190. return
  191. }
  192. // Make hole-punching decisions based on the NAT information of the client and visitor.
  193. vResp, cResp, err := c.analysis(session)
  194. if err != nil {
  195. log.Debug("sid [%s] analysis error: %v", err)
  196. vResp = c.GenNatHoleResponse(session.visitorMsg.TransactionID, nil, err.Error())
  197. cResp = c.GenNatHoleResponse(session.clientMsg.TransactionID, nil, err.Error())
  198. }
  199. session.cResp = cResp
  200. session.vResp = vResp
  201. // send response to visitor and client
  202. var g errgroup.Group
  203. g.Go(func() error {
  204. // if it's sender, wait for a while to make sure the client has send the detect messages
  205. if vResp.DetectBehavior.Role == "sender" {
  206. time.Sleep(1 * time.Second)
  207. }
  208. _ = session.visitorTransporter.Send(vResp)
  209. return nil
  210. })
  211. g.Go(func() error {
  212. // if it's sender, wait for a while to make sure the client has send the detect messages
  213. if cResp.DetectBehavior.Role == "sender" {
  214. time.Sleep(1 * time.Second)
  215. }
  216. _ = session.clientTransporter.Send(cResp)
  217. return nil
  218. })
  219. _ = g.Wait()
  220. time.Sleep(time.Duration(cResp.DetectBehavior.ReadTimeoutMs+30000) * time.Millisecond)
  221. }
  222. func (c *Controller) HandleClient(m *msg.NatHoleClient, transporter transport.MessageTransporter) {
  223. c.mu.RLock()
  224. session, ok := c.sessions[m.Sid]
  225. c.mu.RUnlock()
  226. if !ok {
  227. return
  228. }
  229. log.Trace("handle client message, sid [%s], server name: %s", session.sid, m.ProxyName)
  230. session.clientMsg = m
  231. session.clientTransporter = transporter
  232. select {
  233. case session.notifyCh <- struct{}{}:
  234. default:
  235. }
  236. }
  237. func (c *Controller) HandleReport(m *msg.NatHoleReport) {
  238. c.mu.RLock()
  239. session, ok := c.sessions[m.Sid]
  240. c.mu.RUnlock()
  241. if !ok {
  242. log.Trace("sid [%s] report make hole success: %v, but session not found", m.Sid, m.Success)
  243. return
  244. }
  245. if m.Success {
  246. c.analyzer.ReportSuccess(session.analysisKey, session.recommandMode, session.recommandIndex)
  247. }
  248. log.Info("sid [%s] report make hole success: %v, mode %v, index %v",
  249. m.Sid, m.Success, session.recommandMode, session.recommandIndex)
  250. }
  251. func (c *Controller) GenNatHoleResponse(transactionID string, session *Session, errInfo string) *msg.NatHoleResp {
  252. var sid string
  253. if session != nil {
  254. sid = session.sid
  255. }
  256. return &msg.NatHoleResp{
  257. TransactionID: transactionID,
  258. Sid: sid,
  259. Error: errInfo,
  260. }
  261. }
  262. // analysis analyzes the NAT type and behavior of the visitor and client, then makes hole-punching decisions.
  263. // return the response to the visitor and client.
  264. func (c *Controller) analysis(session *Session) (*msg.NatHoleResp, *msg.NatHoleResp, error) {
  265. cm := session.clientMsg
  266. vm := session.visitorMsg
  267. cNatFeature, err := ClassifyNATFeature(cm.MappedAddrs, parseIPs(cm.AssistedAddrs))
  268. if err != nil {
  269. return nil, nil, fmt.Errorf("classify client nat feature error: %v", err)
  270. }
  271. vNatFeature, err := ClassifyNATFeature(vm.MappedAddrs, parseIPs(vm.AssistedAddrs))
  272. if err != nil {
  273. return nil, nil, fmt.Errorf("classify visitor nat feature error: %v", err)
  274. }
  275. session.cNatFeature = cNatFeature
  276. session.vNatFeature = vNatFeature
  277. session.genAnalysisKey()
  278. mode, index, cBehavior, vBehavior := c.analyzer.GetRecommandBehaviors(session.analysisKey, cNatFeature, vNatFeature)
  279. session.recommandMode = mode
  280. session.recommandIndex = index
  281. session.cBehavior = cBehavior
  282. session.vBehavior = vBehavior
  283. timeoutMs := lo.Max([]int{cBehavior.SendDelayMs, vBehavior.SendDelayMs}) + 5000
  284. if cBehavior.ListenRandomPorts > 0 || vBehavior.ListenRandomPorts > 0 {
  285. timeoutMs += 30000
  286. }
  287. protocol := vm.Protocol
  288. vResp := &msg.NatHoleResp{
  289. TransactionID: vm.TransactionID,
  290. Sid: session.sid,
  291. Protocol: protocol,
  292. CandidateAddrs: lo.Uniq(cm.MappedAddrs),
  293. AssistedAddrs: lo.Uniq(cm.AssistedAddrs),
  294. DetectBehavior: msg.NatHoleDetectBehavior{
  295. Mode: mode,
  296. Role: vBehavior.Role,
  297. TTL: vBehavior.TTL,
  298. SendDelayMs: vBehavior.SendDelayMs,
  299. ReadTimeoutMs: timeoutMs - vBehavior.SendDelayMs,
  300. SendRandomPorts: vBehavior.PortsRandomNumber,
  301. ListenRandomPorts: vBehavior.ListenRandomPorts,
  302. CandidatePorts: getRangePorts(cm.MappedAddrs, cNatFeature.PortsDifference, vBehavior.PortsRangeNumber),
  303. },
  304. }
  305. cResp := &msg.NatHoleResp{
  306. TransactionID: cm.TransactionID,
  307. Sid: session.sid,
  308. Protocol: protocol,
  309. CandidateAddrs: lo.Uniq(vm.MappedAddrs),
  310. AssistedAddrs: lo.Uniq(vm.AssistedAddrs),
  311. DetectBehavior: msg.NatHoleDetectBehavior{
  312. Mode: mode,
  313. Role: cBehavior.Role,
  314. TTL: cBehavior.TTL,
  315. SendDelayMs: cBehavior.SendDelayMs,
  316. ReadTimeoutMs: timeoutMs - cBehavior.SendDelayMs,
  317. SendRandomPorts: cBehavior.PortsRandomNumber,
  318. ListenRandomPorts: cBehavior.ListenRandomPorts,
  319. CandidatePorts: getRangePorts(vm.MappedAddrs, vNatFeature.PortsDifference, cBehavior.PortsRangeNumber),
  320. },
  321. }
  322. log.Debug("sid [%s] visitor nat: %+v, candidateAddrs: %v; client nat: %+v, candidateAddrs: %v, protocol: %s",
  323. session.sid, *vNatFeature, vm.MappedAddrs, *cNatFeature, cm.MappedAddrs, protocol)
  324. log.Debug("sid [%s] visitor detect behavior: %+v", session.sid, vResp.DetectBehavior)
  325. log.Debug("sid [%s] client detect behavior: %+v", session.sid, cResp.DetectBehavior)
  326. return vResp, cResp, nil
  327. }
  328. func getRangePorts(addrs []string, difference, maxNumber int) []msg.PortsRange {
  329. if maxNumber <= 0 {
  330. return nil
  331. }
  332. addr, err := lo.Last(addrs)
  333. if err != nil {
  334. return nil
  335. }
  336. var ports []msg.PortsRange
  337. _, portStr, err := net.SplitHostPort(addr)
  338. if err != nil {
  339. return nil
  340. }
  341. port, err := strconv.Atoi(portStr)
  342. if err != nil {
  343. return nil
  344. }
  345. ports = append(ports, msg.PortsRange{
  346. From: lo.Max([]int{port - difference - 5, port - maxNumber, 1}),
  347. To: lo.Min([]int{port + difference + 5, port + maxNumber, 65535}),
  348. })
  349. return ports
  350. }