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