diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go index fdd19127d..b37d3c4ff 100644 --- a/internal/mtproto/manager.go +++ b/internal/mtproto/manager.go @@ -10,6 +10,7 @@ import ( "maps" "net" "net/http" + "net/netip" "net/url" "os" "slices" @@ -129,11 +130,24 @@ type Traffic struct { Down int64 } +// FrontedTraffic is what an mtg process relayed to its fronting target since the +// previous scrape. No client owns these bytes; only the inbound does. +type FrontedTraffic struct { + Tag string + Up int64 + Down int64 +} + type clientCounters struct { up int64 down int64 } +// since returns the growth over prev; a counter that went backwards counts as none. +func (c clientCounters) since(prev clientCounters) (up, down int64) { + return max(c.up-prev.up, 0), max(c.down-prev.down, 0) +} + type managed struct { proc *Process tag string @@ -142,6 +156,7 @@ type managed struct { apiPort int apiToken string last map[string]clientCounters + fronted clientCounters } // Manager owns the set of running mtg processes keyed by inbound id. @@ -411,16 +426,16 @@ func (m *Manager) StopAll() { } } -// CollectTraffic scrapes each running mtg /stats endpoint and returns the -// per-client byte deltas since the previous scrape, plus the emails of clients -// with at least one live connection. -func (m *Manager) CollectTraffic() ([]Traffic, []string) { +// CollectTraffic scrapes each running mtg /stats endpoint for the byte deltas since the +// previous scrape, per client and per inbound's fronted connections, and the online emails. +func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) { type snap struct { id int apiPort int apiToken string tag string last map[string]clientCounters + fronted clientCounters } m.mu.Lock() snaps := make([]snap, 0, len(m.procs)) @@ -430,22 +445,22 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) { } lastCopy := make(map[string]clientCounters, len(cur.last)) maps.Copy(lastCopy, cur.last) - snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy}) + snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy, fronted: cur.fronted}) } m.mu.Unlock() var out []Traffic + var fronted []FrontedTraffic var online []string for _, s := range snaps { - users, ok := scrapeStats(s.apiPort, s.apiToken) + stats, ok := scrapeStats(s.apiPort, s.apiToken) if !ok { continue } - newLast := make(map[string]clientCounters, len(users)) - for email, u := range users { - up := u.BytesIn - down := u.BytesOut - newLast[email] = clientCounters{up: up, down: down} + newLast := make(map[string]clientCounters, len(stats.Users)) + for email, u := range stats.Users { + now := u.counters() + newLast[email] = now if u.Connections > 0 { online = append(online, email) } @@ -453,26 +468,24 @@ func (m *Manager) CollectTraffic() ([]Traffic, []string) { if !had { continue } - du := up - prev.up - dd := down - prev.down - if du < 0 { - du = 0 - } - if dd < 0 { - dd = 0 - } - if du > 0 || dd > 0 { + if du, dd := now.since(prev); du > 0 || dd > 0 { out = append(out, Traffic{Tag: s.tag, Email: email, Up: du, Down: dd}) } } + // mtg counts fronted bytes from zero at start, the same point this baseline begins. + frontedNow := stats.Fronting.counters() + if du, dd := frontedNow.since(s.fronted); du > 0 || dd > 0 { + fronted = append(fronted, FrontedTraffic{Tag: s.tag, Up: du, Down: dd}) + } m.mu.Lock() if cur, ok := m.procs[s.id]; ok { cur.last = newLast + cur.fronted = frontedNow } m.mu.Unlock() } - return out, online + return out, fronted, online } func (m *Manager) HasRunning() bool { @@ -563,7 +576,8 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { if inst.PublicIPv6 != "" { fmt.Fprintf(&b, "public-ipv6 = %q\n", inst.PublicIPv6) } - if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol { + requireSNIMatch := !frontsIntoOwnNetwork(inst.FrontingIP) + if inst.FrontingIP != "" || inst.FrontingPort > 0 || inst.FrontingProxyProtocol || requireSNIMatch { b.WriteString("\n[domain-fronting]\n") if inst.FrontingIP != "" { fmt.Fprintf(&b, "host = %q\n", inst.FrontingIP) @@ -574,6 +588,9 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { if inst.FrontingProxyProtocol { b.WriteString("proxy-protocol = true\n") } + if requireSNIMatch { + b.WriteString("require-sni-match = true\n") + } } // When the inbound opts into Xray routing, mtg reaches Telegram through the // loopback SOCKS bridge the panel injects into the running Xray config. mtg @@ -620,6 +637,16 @@ func renderConfig(inst Instance, apiPort int, apiToken string) string { return b.String() } +// frontsIntoOwnNetwork reports whether the fronting target is the operator's own server. +// Any other target answers by the stranger's SNI: a CDN there makes the inbound an open relay. +func frontsIntoOwnNetwork(host string) bool { + addr, err := netip.ParseAddr(host) + if err != nil { + return false + } + return addr.IsLoopback() || addr.IsPrivate() || addr.IsLinkLocalUnicast() +} + func writeConfig(path string, inst Instance, apiPort int, apiToken string) error { if err := os.MkdirAll(configDir(), 0o750); err != nil { return err @@ -636,6 +663,17 @@ type statsUser struct { BytesOut int64 `json:"bytes_out"` } +func (u statsUser) counters() clientCounters { + return clientCounters{up: u.BytesIn, down: u.BytesOut} +} + +// statsSnapshot is the part of mtg-multi's /stats the panel reads. Fronting counts the +// connections relayed to the fronting target; a binary older than 1.17.0 omits it. +type statsSnapshot struct { + Users map[string]statsUser `json:"users"` + Fronting statsUser `json:"fronting"` +} + type secretPutEntry struct { Secret string `json:"secret"` AdTag string `json:"ad_tag,omitempty"` @@ -718,26 +756,23 @@ func applySecrets(port int, token string, inst Instance) bool { return resp.StatusCode == http.StatusOK } -// scrapeStats reads the mtg-multi /stats JSON API and returns the per-user -// cumulative counters. Best-effort: an unreachable endpoint or unparseable body -// yields ok=false. -func scrapeStats(port int, token string) (map[string]statsUser, bool) { +// scrapeStats reads the mtg-multi /stats JSON API. Best-effort: an unreachable +// endpoint or unparseable body yields ok=false. +func scrapeStats(port int, token string) (statsSnapshot, bool) { client := http.Client{Timeout: 3 * time.Second} req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats", port), nil) if err != nil { - return nil, false + return statsSnapshot{}, false } authorize(req, token) resp, err := client.Do(req) if err != nil { - return nil, false + return statsSnapshot{}, false } defer resp.Body.Close() - var parsed struct { - Users map[string]statsUser `json:"users"` - } + var parsed statsSnapshot if err := json.NewDecoder(resp.Body).Decode(&parsed); err != nil { - return nil, false + return statsSnapshot{}, false } - return parsed.Users, true + return parsed, true } diff --git a/internal/mtproto/manager_fronting_test.go b/internal/mtproto/manager_fronting_test.go new file mode 100644 index 000000000..df9b06c61 --- /dev/null +++ b/internal/mtproto/manager_fronting_test.go @@ -0,0 +1,117 @@ +package mtproto + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" +) + +// mtg relays an unauthenticated connection to the fronting target by the SNI the +// stranger sent, so a public target turns the inbound into an open relay (CDN "clean IP"). +func TestRenderConfigRequiresSNIMatchForPublicFronting(t *testing.T) { + cases := []struct { + name string + frontingIP string + want bool + }{ + {"FakeTLS domain resolved over DNS", "", true}, + {"public address", "104.16.132.229", true}, + {"hostname", "cdn.example.com", true}, + {"loopback web server", "127.0.0.1", false}, + {"IPv6 loopback web server", "::1", false}, + {"web server on the private network", "10.0.0.5", false}, + {"web server on a unique-local network", "fd00::5", false}, + {"web server on the link", "169.254.10.1", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cfg := renderConfig(Instance{ + Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}}, + Listen: "0.0.0.0", Port: 2087, + FrontingIP: tc.frontingIP, + }, 5000, "") + got := strings.Contains(cfg, "\n[domain-fronting]\n") && strings.Contains(cfg, "\nrequire-sni-match = true\n") + if got != tc.want { + t.Fatalf("require-sni-match emitted = %v, want %v:\n%s", got, tc.want, cfg) + } + if strings.Index(cfg, "require-sni-match") > strings.Index(cfg, "[secrets]") { + t.Fatalf("require-sni-match must stay inside [domain-fronting], before [secrets]:\n%s", cfg) + } + }) + } +} + +// Fronted bytes belong to no secret, so they never showed in the per-user map: +// an inbound relaying gigabytes to its fronting domain reported no traffic. +func TestCollectTrafficReportsFrontedBytes(t *testing.T) { + pidFile := installFakeMtg(t) + mgr := &Manager{procs: map[int]*managed{}, swept: true} + if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { + t.Fatalf("ensure: %v", err) + } + waitSpawnCount(t, pidFile, 1) + t.Cleanup(mgr.StopAll) + + scrapes := []string{ + `"fronting":{"connections":3,"bytes_in":100,"bytes_out":1000,"rejected":0}`, + `"fronting":{"connections":3,"bytes_in":150,"bytes_out":1600,"rejected":7}`, + `"fronting":{"connections":0,"bytes_in":150,"bytes_out":1600,"rejected":9}`, + } + var scrape atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + body := scrapes[min(int(scrape.Add(1))-1, len(scrapes)-1)] + _, _ = io.WriteString(w, fmt.Sprintf(`{%s,"users":{"alice":{"connections":0,"bytes_in":10,"bytes_out":20}}}`, body)) + })) + defer srv.Close() + mgr.procs[1].apiPort = serverPort(t, srv) + + wants := [][]FrontedTraffic{ + {{Tag: "inbound-1", Up: 100, Down: 1000}}, + {{Tag: "inbound-1", Up: 50, Down: 600}}, + nil, + } + for i, want := range wants { + clients, fronted, _ := mgr.CollectTraffic() + if len(clients) != 0 { + t.Fatalf("scrape %d: fronted bytes must not be attributed to a client: %+v", i+1, clients) + } + if !reflect.DeepEqual(fronted, want) { + t.Fatalf("scrape %d: fronted = %+v, want %+v", i+1, fronted, want) + } + } +} + +func TestCollectTrafficWithoutFrontingCounters(t *testing.T) { + pidFile := installFakeMtg(t) + mgr := &Manager{procs: map[int]*managed{}, swept: true} + if err := mgr.Ensure(mtgInst(1, SecretEntry{Name: "alice", Secret: "ee01"})); err != nil { + t.Fatalf("ensure: %v", err) + } + waitSpawnCount(t, pidFile, 1) + t.Cleanup(mgr.StopAll) + + var scrape atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + n := int64(scrape.Add(1)) + _, _ = io.WriteString(w, fmt.Sprintf(`{"users":{"alice":{"connections":1,"bytes_in":%d,"bytes_out":%d}}}`, 10*n, 20*n)) + })) + defer srv.Close() + mgr.procs[1].apiPort = serverPort(t, srv) + + mgr.CollectTraffic() + clients, fronted, online := mgr.CollectTraffic() + if want := []Traffic{{Tag: "inbound-1", Email: "alice", Up: 10, Down: 20}}; !reflect.DeepEqual(clients, want) { + t.Fatalf("clients = %+v, want %+v", clients, want) + } + if len(fronted) != 0 { + t.Fatalf("an mtg without fronting counters must report no fronted traffic: %+v", fronted) + } + if !reflect.DeepEqual(online, []string{"alice"}) { + t.Fatalf("online = %+v, want [alice]", online) + } +} diff --git a/internal/mtproto/manager_mutation_test.go b/internal/mtproto/manager_mutation_test.go index 914f205dd..d726db800 100644 --- a/internal/mtproto/manager_mutation_test.go +++ b/internal/mtproto/manager_mutation_test.go @@ -41,10 +41,11 @@ func TestScrapeStats(t *testing.T) { })) defer srv.Close() - users, ok := scrapeStats(serverPort(t, srv), "sesame") + stats, ok := scrapeStats(serverPort(t, srv), "sesame") if !ok { t.Fatal("scrapeStats should succeed against a valid /stats endpoint") } + users := stats.Users if len(users) != 2 { t.Fatalf("expected 2 users, got %d: %+v", len(users), users) } diff --git a/internal/mtproto/manager_test.go b/internal/mtproto/manager_test.go index 412975aac..3ce15539b 100644 --- a/internal/mtproto/manager_test.go +++ b/internal/mtproto/manager_test.go @@ -123,13 +123,13 @@ func TestInstanceFromInboundLeavesOutWhatMtgCannotParse(t *testing.T) { } func TestRenderConfig(t *testing.T) { - // A bare instance emits only the required keys, api-bind-to, and the - // [secrets] section, with no optional keys and no [domain-fronting]. + // A bare instance emits only the required keys, api-bind-to, the SNI gate of + // [domain-fronting] and the [secrets] section, with no optional keys. bare := renderConfig(Instance{ Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}}, Listen: "0.0.0.0", Port: 8443, }, 5000, "") - for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[defense.pending-handshakes]", "[secret-ad-tags]", "api-token"} { + for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "host =", "proxy-protocol =", "[stats.prometheus]", "[throttle]", "[defense.pending-handshakes]", "[secret-ad-tags]", "api-token"} { if strings.Contains(bare, unwanted) { t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare) } diff --git a/internal/web/job/mtproto_job.go b/internal/web/job/mtproto_job.go index 21ebfaec4..82a474f07 100644 --- a/internal/web/job/mtproto_job.go +++ b/internal/web/job/mtproto_job.go @@ -41,11 +41,27 @@ func (j *MtprotoJob) Run() { mgr := mtproto.GetManager() mgr.Reconcile(desired) - deltas, onlineEmails := mgr.CollectTraffic() + deltas, fronted, onlineEmails := mgr.CollectTraffic() + traffics, clientTraffics := rollUpMtprotoTraffic(deltas, fronted, routedTags) - // A routed inbound's total is already metered through the Xray bridge by - // xray_traffic_job, so only non-routed inbounds are rolled up here; per-client - // deltas are always kept, since the bridge cannot tell mtproto users apart. + if len(traffics) > 0 || len(clientTraffics) > 0 { + if _, _, err := j.inboundService.AddTraffic(traffics, clientTraffics); err != nil { + logger.Warning("mtproto job: add traffic failed:", err) + } + } + + j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags) +} + +// rollUpMtprotoTraffic turns scraped mtg deltas into inbound and client traffic. +// Fronted bytes join every inbound's total: mtg dials the fronting target itself, past Xray. +func rollUpMtprotoTraffic( + deltas []mtproto.Traffic, + fronted []mtproto.FrontedTraffic, + routedTags map[string]bool, +) ([]*xray.Traffic, []*xray.ClientTraffic) { + // xray_traffic_job already meters a routed inbound's client bytes through the bridge; + // per-client deltas are always kept, since the bridge cannot tell mtproto users apart. clientTraffics := make([]*xray.ClientTraffic, 0, len(deltas)) inboundUp := make(map[string]int64) inboundDown := make(map[string]int64) @@ -60,6 +76,10 @@ func (j *MtprotoJob) Run() { inboundDown[d.Tag] += d.Down } } + for _, f := range fronted { + inboundUp[f.Tag] += f.Up + inboundDown[f.Tag] += f.Down + } traffics := make([]*xray.Traffic, 0, len(inboundUp)) for tag, up := range inboundUp { @@ -70,12 +90,5 @@ func (j *MtprotoJob) Run() { Down: inboundDown[tag], }) } - - if len(traffics) > 0 || len(clientTraffics) > 0 { - if _, _, err := j.inboundService.AddTraffic(traffics, clientTraffics); err != nil { - logger.Warning("mtproto job: add traffic failed:", err) - } - } - - j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags) + return traffics, clientTraffics } diff --git a/internal/web/job/mtproto_job_test.go b/internal/web/job/mtproto_job_test.go new file mode 100644 index 000000000..f1dc72833 --- /dev/null +++ b/internal/web/job/mtproto_job_test.go @@ -0,0 +1,48 @@ +package job + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/mtproto" +) + +// Fronted bytes leave through mtg's own dialer, never through the Xray bridge, +// so a routed inbound has to count them here or nothing counts them at all. +func TestRollUpMtprotoTraffic(t *testing.T) { + routed := map[string]bool{"routed": true} + clients := []mtproto.Traffic{ + {Tag: "direct", Email: "alice", Up: 1, Down: 2}, + {Tag: "direct", Email: "bob", Up: 10, Down: 20}, + {Tag: "routed", Email: "carol", Up: 100, Down: 200}, + } + fronted := []mtproto.FrontedTraffic{ + {Tag: "direct", Up: 1000, Down: 2000}, + {Tag: "routed", Up: 10000, Down: 20000}, + } + + inbounds, clientTraffics := rollUpMtprotoTraffic(clients, fronted, routed) + + got := map[string][2]int64{} + for _, tr := range inbounds { + if !tr.IsInbound { + t.Fatalf("traffic for %q must be inbound traffic", tr.Tag) + } + got[tr.Tag] = [2]int64{tr.Up, tr.Down} + } + want := map[string][2]int64{ + "direct": {1011, 2022}, + "routed": {10000, 20000}, + } + if len(got) != len(want) || got["direct"] != want["direct"] || got["routed"] != want["routed"] { + t.Fatalf("inbound totals = %v, want %v", got, want) + } + + if len(clientTraffics) != 3 { + t.Fatalf("every client delta must be kept, fronted bytes belong to no client: %+v", clientTraffics) + } + for i, c := range clients { + if ct := clientTraffics[i]; ct.Email != c.Email || ct.Up != c.Up || ct.Down != c.Down { + t.Fatalf("client traffic %d = %+v, want %+v", i, ct, c) + } + } +}