controller.go 11 KB

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