feat(mtproto): record client IPs and enforce the IP limit for MTProto clients

Every client the panel serves has its connected addresses recorded and its
IP limit applied, whichever process carries it. MTProto clients are served
by mtg, never by Xray, so the core's online list could not see them: their
IP log stayed empty and a configured limitIp never fired, although the form
offers both for every protocol.

mtg-multi 1.17.0 reports users.<name>.active_ips in /stats. The manager
keeps them from each scrape together with the time an address was first
seen connected, so the scan can keep the newest addresses and ban the
oldest, and the IP scan merges them the way it already merges kernel-mode
AmneziaWG peers. A failed scrape drops the addresses instead of leaving
them live, and loopback addresses (a relay in front of mtg) are skipped as
the core skips them.

Enforcement is the existing fail2ban path. The temporary credential drop
is Xray-only, so on Windows, where it is the only mechanism, an MTProto
limit is recorded but not enforced.
This commit is contained in:
Sanaei
2026-11-29 12:13:19 +03:30
parent 3e1fc3c24f
commit 22fe0c4cd9
4 changed files with 197 additions and 22 deletions
+57 -4
View File
@@ -157,6 +157,8 @@ type managed struct {
apiToken string
last map[string]clientCounters
fronted clientCounters
// ips is replaced whole on every scrape and never edited, so readers may share it.
ips map[string]map[string]int64
}
// Manager owns the set of running mtg processes keyed by inbound id.
@@ -436,6 +438,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
tag string
last map[string]clientCounters
fronted clientCounters
ips map[string]map[string]int64
}
m.mu.Lock()
snaps := make([]snap, 0, len(m.procs))
@@ -445,16 +448,23 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []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, fronted: cur.fronted})
snaps = append(snaps, snap{id: id, apiPort: cur.apiPort, apiToken: cur.apiToken, tag: cur.tag, last: lastCopy, fronted: cur.fronted, ips: cur.ips})
}
m.mu.Unlock()
var out []Traffic
var fronted []FrontedTraffic
var online []string
now := time.Now().Unix()
for _, s := range snaps {
stats, ok := scrapeStats(s.apiPort, s.apiToken)
if !ok {
// Nothing is known about who is connected now: stale addresses must not stay live.
m.mu.Lock()
if cur, ok := m.procs[s.id]; ok {
cur.ips = nil
}
m.mu.Unlock()
continue
}
newLast := make(map[string]clientCounters, len(stats.Users))
@@ -482,12 +492,54 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
if cur, ok := m.procs[s.id]; ok {
cur.last = newLast
cur.fronted = frontedNow
cur.ips = activeIPsSince(s.ips, stats.Users, now)
}
m.mu.Unlock()
}
return out, fronted, online
}
// ClientIPs returns the addresses mtg reported connected at the last scrape,
// as email -> address -> Unix time the address was first seen connected.
func (m *Manager) ClientIPs() map[string]map[string]int64 {
m.mu.Lock()
defer m.mu.Unlock()
out := map[string]map[string]int64{}
for _, cur := range m.procs {
for email, ips := range cur.ips {
if _, ok := out[email]; !ok {
out[email] = make(map[string]int64, len(ips))
}
for ip, since := range ips {
out[email][ip] = max(out[email][ip], since)
}
}
}
return out
}
// activeIPsSince carries each address's first sighting over from prev while mtg still
// lists it. A loopback address is a relay in front of mtg, not a client, as in the core.
func activeIPsSince(prev map[string]map[string]int64, users map[string]statsUser, now int64) map[string]map[string]int64 {
out := make(map[string]map[string]int64, len(users))
for email, u := range users {
for _, ip := range u.ActiveIPs {
if addr, err := netip.ParseAddr(ip); err == nil && addr.IsLoopback() {
continue
}
since, known := prev[email][ip]
if !known {
since = now
}
if _, ok := out[email]; !ok {
out[email] = make(map[string]int64, len(u.ActiveIPs))
}
out[email][ip] = since
}
}
return out
}
func (m *Manager) HasRunning() bool {
m.mu.Lock()
defer m.mu.Unlock()
@@ -658,9 +710,10 @@ func writeConfig(path string, inst Instance, apiPort int, apiToken string) error
// the client sent to the proxy (upload) and bytes_out is what the proxy returned
// (download).
type statsUser struct {
Connections int64 `json:"connections"`
BytesIn int64 `json:"bytes_in"`
BytesOut int64 `json:"bytes_out"`
Connections int64 `json:"connections"`
BytesIn int64 `json:"bytes_in"`
BytesOut int64 `json:"bytes_out"`
ActiveIPs []string `json:"active_ips"`
}
func (u statsUser) counters() clientCounters {
@@ -0,0 +1,73 @@
package mtproto
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"time"
)
// The IP limit keeps a client's newest addresses and bans the oldest, so an address
// must keep the time it connected for as long as mtg reports it.
func TestActiveIPsSince(t *testing.T) {
prev := map[string]map[string]int64{
"alice": {"203.0.113.7": 100, "203.0.113.8": 110},
}
users := map[string]statsUser{
"alice": {ActiveIPs: []string{"203.0.113.7", "198.51.100.4", "127.0.0.1", "::1"}},
"bob": {ActiveIPs: []string{"2001:db8::1"}},
"carol": {},
}
got := activeIPsSince(prev, users, 200)
want := map[string]map[string]int64{
"alice": {"203.0.113.7": 100, "198.51.100.4": 200},
"bob": {"2001:db8::1": 200},
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("activeIPsSince = %v, want %v", got, want)
}
}
// MTProto clients never reach Xray, so its online list cannot see them: without
// mtg's own addresses their IP log stays empty and their IP limit never fires.
func TestClientIPsFollowTheLastScrape(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)
if got := mgr.ClientIPs(); len(got) != 0 {
t.Fatalf("no address is known before the first scrape, got %v", got)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, `{"users":{"alice":{"connections":2,"bytes_in":1,"bytes_out":2,"active_ips":["203.0.113.7"]}}}`)
}))
mgr.procs[1].apiPort = serverPort(t, srv)
before := time.Now().Unix()
mgr.CollectTraffic()
after := time.Now().Unix()
got := mgr.ClientIPs()
seen, ok := got["alice"]["203.0.113.7"]
if len(got) != 1 || len(got["alice"]) != 1 || !ok || seen < before || seen > after {
t.Fatalf("ClientIPs = %v, want alice at 203.0.113.7 seen in [%d, %d]", got, before, after)
}
// A scrape that fails says nothing about who is connected: the addresses of the
// previous one must not stay "live", or a client that left keeps counting.
srv.Close()
mgr.CollectTraffic()
if got := mgr.ClientIPs(); len(got) != 0 {
t.Fatalf("a failed scrape must drop the known addresses, got %v", fmt.Sprint(got))
}
}
+33 -18
View File
@@ -17,6 +17,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/mtproto"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
@@ -39,6 +40,7 @@ type onlineUsersSource interface {
type CheckClientIpJob struct {
bannedSeen map[string]int64
onlineUsers onlineUsersSource
mtprotoIPs func() map[string]map[string]int64
allowlist ipLimitAllowlist
lastIpPrune int64
}
@@ -52,31 +54,26 @@ const ipPruneIntervalSeconds = int64(5 * 60)
// NewCheckClientIpJob creates a new client IP monitoring job instance.
func NewCheckClientIpJob() *CheckClientIpJob {
return &CheckClientIpJob{onlineUsers: &service.XrayService{}}
return &CheckClientIpJob{
onlineUsers: &service.XrayService{},
mtprotoIPs: mtproto.GetManager().ClientIPs,
}
}
func (j *CheckClientIpJob) Run() {
j.pruneStaleIpRows()
observed, apiMode := j.collectFromOnlineAPI()
// Kernel-mode AmneziaWG peers never reach Xray, so its online users cannot
// see them; their connect locations come from the kernel interface instead.
kernelIPs := amneziawgkern.GetCollector().ClientIPs()
if len(kernelIPs) > 0 {
if observed == nil {
observed = make(map[string]map[string]int64, len(kernelIPs))
}
for email, ips := range kernelIPs {
if _, ok := observed[email]; !ok {
observed[email] = make(map[string]int64, len(ips))
}
for ip, ts := range ips {
if prev, seen := observed[email][ip]; !seen || ts > prev {
observed[email][ip] = ts
}
}
// Kernel-mode AmneziaWG peers and MTProto clients never reach Xray, so its online
// users cannot see them; the kernel interface and the mtg sidecars report their own.
sidecarSeen := false
for _, ips := range []map[string]map[string]int64{amneziawgkern.GetCollector().ClientIPs(), j.mtprotoIPs()} {
if len(ips) == 0 {
continue
}
sidecarSeen = true
observed = mergeObservedIPs(observed, ips)
}
if !apiMode && len(kernelIPs) == 0 {
if !apiMode && !sidecarSeen {
// xray is down or predates the online-stats API. There is no access-log
// fallback anymore, so there is nothing to do this run.
logger.Debug("[LimitIP] online-stats API unavailable this run; skipping")
@@ -101,6 +98,24 @@ func (j *CheckClientIpJob) Run() {
j.processObserved(observed, enforce, true)
}
// mergeObservedIPs folds src (email -> ip -> last-seen) into dst, newest sighting winning.
func mergeObservedIPs(dst, src map[string]map[string]int64) map[string]map[string]int64 {
if dst == nil {
dst = make(map[string]map[string]int64, len(src))
}
for email, ips := range src {
if _, ok := dst[email]; !ok {
dst[email] = make(map[string]int64, len(ips))
}
for ip, ts := range ips {
if prev, seen := dst[email][ip]; !seen || ts > prev {
dst[email][ip] = ts
}
}
}
return dst
}
// resolveEnforce decides whether limits can actually be enforced this run: a
// disabled fail2ban gates every platform, a missing binary the ones needing it.
func (j *CheckClientIpJob) resolveEnforce(f2bEnabled, hasLimit, f2bInstalled, needsBinary bool) bool {
@@ -5,6 +5,7 @@ import (
"log"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
@@ -555,3 +556,36 @@ func TestUpdateInboundClientIps_AllowlistedIpIsNeitherCountedNorBanned(t *testin
}
}
}
// An MTProto client is served by mtg, not Xray: its addresses come from the sidecar
// and must be recorded and limited even while the online-stats API has nothing.
func TestRun_EnforcesIpLimitOnMtprotoClients(t *testing.T) {
setupIntegrationDB(t)
t.Setenv("XUI_ENABLE_FAIL2BAN", "true")
fakeFail2BanClient(t)
const email = "mtproto-user"
seedLinkedInboundWithClient(t, "inbound-mtproto", email, 1)
now := time.Now().Unix()
j := NewCheckClientIpJob()
j.mtprotoIPs = func() map[string]map[string]int64 {
return map[string]map[string]int64{email: {"203.0.113.30": now - 600, "203.0.113.31": now - 5}}
}
// The first scan only records; enforcement needs the stored row.
j.Run()
j.Run()
got := ipSet(readClientIps(t, email))
if _, kept := got["203.0.113.31"]; !kept || len(got) != 1 {
t.Fatalf("only the newest address stays recorded as live, got %v", got)
}
body, err := os.ReadFile(readIpLimitLogPath())
if err != nil {
t.Fatalf("read 3xipl.log: %v", err)
}
want := "[LIMIT_IP] Email = " + email + " || Disconnecting OLD IP = 203.0.113.30 || Timestamp = "
if !strings.Contains(string(body), want) || strings.Contains(string(body), "203.0.113.31") {
t.Fatalf("the oldest address alone must be queued for a ban, 3xipl.log:\n%s", body)
}
}