test(mtproto): cover single-backend DC aliases

Follow up gramsrv PR #17 with boundary coverage and public configuration docs.

Canonical-Telesrv: b4df3e72c24470e4ce09e5fc1d46e0c2944f6d3e

Reviewed-Head: e7eb07b9eb

Co-authored-by: onysd <beatvin128@gmail.com>
This commit is contained in:
iamxvbaba 2026-07-24 23:17:32 +08:00
parent 5dcdb57e4c
commit 9ef746d45e
8 changed files with 127 additions and 69 deletions

View file

@ -31,12 +31,10 @@ type Config struct {
RSAKeyPath string
// DC 是本 server 的 DC ID。
DC int
// StrictDCCheck turns on exact DC-ID validation for the permanent-key
// exchange (default off = lenient). See mtprotoedge.Options.StrictDC doc
// for the full rationale: telesrv is always a single physical backend, but
// many client forks alias dc_id 1..5 to it, so a mismatched client-chosen
// dc_id is expected, not an attack — strict mode exists only for a
// hypothetical future real multi-DC deployment.
// StrictDCCheck enables the default-off key-exchange DC-label diagnostic.
// The normal single-backend mode accepts every wire int32 label without
// partitioning auth keys, sessions, or business state. See
// mtprotoedge.Options.StrictDC for the optional strict behavior.
StrictDCCheck bool
// MTProtoMaxConnections / PerIP 覆盖 raw Accept、codec sniff、握手到认证 session
// 的完整物理连接生命周期;负数关闭对应 admission 上限。

View file

@ -49,6 +49,34 @@ func TestLoadUsesExplicitAdvertiseIP(t *testing.T) {
}
}
func TestLoadStrictDCCheck(t *testing.T) {
t.Run("defaults off", func(t *testing.T) {
disableDefaultConfigFile(t)
t.Setenv("TELESRV_STRICT_DC_CHECK", "")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.StrictDCCheck {
t.Fatal("StrictDCCheck = true, want default false")
}
})
t.Run("explicitly enabled", func(t *testing.T) {
disableDefaultConfigFile(t)
t.Setenv("TELESRV_STRICT_DC_CHECK", "true")
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if !cfg.StrictDCCheck {
t.Fatal("StrictDCCheck = false, want true")
}
})
}
func TestLoadMTProtoAdmissionAndRPCBudgets(t *testing.T) {
disableDefaultConfigFile(t)
t.Setenv("TELESRV_MTPROTO_MAX_CONNECTIONS", "12345")

View file

@ -25,14 +25,12 @@ import (
// runServerExchange is a gotd server exchange compatibility shim.
//
// DrKLO Android marks media temporary auth-key exchange with a negative DC in
// p_q_inner_data_temp_dc (for example DC 2 -> -2). gotd v0.158.0 validates this
// field by exact equality and rejects that legitimate media-temp path. The
// temp-key DC check accepts any value whose absolute value matches this
// server DC. The permanent-key check is lenient by default too (see
// Options.StrictDC doc) — self-hosted single-server deployments commonly
// have clients that alias dc_id 1..5 to the one backend, so a client-chosen
// dc_id that isn't our configured DC is expected, not an error.
// In the default single-backend mode, p_q_inner_data_dc and
// p_q_inner_data_temp_dc carry client routing labels only: every int32 value is
// admitted and the label is not persisted or used for key/session identity.
// This also covers DrKLO Android's negative media-temp labels. StrictDC retains
// exact permanent / absolute-value temporary validation as an explicit,
// default-off diagnostic for a future real multi-DC deployment.
func (s *Server) runServerExchange(ctx context.Context, conn transport.Conn) (exchange.ServerExchangeResult, error) {
ex := serverExchangeCompat{
conn: conn,
@ -351,14 +349,7 @@ func (s serverExchangeCompat) validatePQInnerDataDC(d mt.PQInnerDataClass) error
case *mt.PQInnerDataDC:
if innerDataDC.DC != s.dc {
if !s.strictDC {
// Lenient by default (Options.StrictDC doc has the full
// rationale): telesrv is a single physical backend, and
// self-hosted client forks commonly alias dc_id 1..5 to this
// one server, so a client-chosen dc_id that isn't our
// configured DC is expected, not an error. dc_id plays no
// role in key derivation, so accepting it doesn't weaken the
// exchange.
s.log.Debug("Accepted permanent auth key DC mismatch (lenient mode)",
s.log.Debug("Accepted permanent auth key DC alias",
zap.Int("server_dc", s.dc),
zap.Int("client_dc", innerDataDC.DC))
return nil
@ -369,8 +360,8 @@ func (s serverExchangeCompat) validatePQInnerDataDC(d mt.PQInnerDataClass) error
if !sameDCByAbs(innerDataDC.DC, s.dc) && s.strictDC {
return wrongDCError(s.dc, innerDataDC.DC)
}
if innerDataDC.DC < 0 {
s.log.Warn("Accepted Android media temp auth key negative DC",
if !sameDCByAbs(innerDataDC.DC, s.dc) {
s.log.Debug("Accepted temporary auth key DC alias",
zap.Int("server_dc", s.dc),
zap.Int("client_dc", innerDataDC.DC),
zap.Int("expires_in", innerDataDC.ExpiresIn))

View file

@ -7,6 +7,7 @@ import (
"crypto/rsa"
"encoding/binary"
"errors"
"fmt"
"math/big"
"net"
"testing"
@ -366,41 +367,85 @@ func TestKeyExchangeAcceptsAndroidMediaTempNegativeDC(t *testing.T) {
}
}
func TestKeyExchangeRejectsWrongNegativeTempDCWhenStrict(t *testing.T) {
ex := serverExchangeCompat{dc: 2, strictDC: true, log: zaptest.NewLogger(t)}
err := ex.validatePQInnerDataDC(&mt.PQInnerDataTempDC{DC: -3})
var exErr *exchange.ServerExchangeError
if !errors.As(err, &exErr) {
t.Fatalf("err = %T %v, want ServerExchangeError", err, err)
}
if exErr.Code != codec.CodeWrongDC {
t.Fatalf("error code = %d, want %d", exErr.Code, codec.CodeWrongDC)
}
}
// TestKeyExchangeAcceptsMismatchedDCByDefault asserts that, in the default
// lenient mode, neither permanent nor temp key exchange requires dc_id to
// equal the server's configured DC. telesrv is always a single physical
// backend; self-hosted client forks commonly alias dc_id 1..5 to it (see
// Options.StrictDC doc), so a mismatched client-chosen dc_id must not be
// rejected — doing so previously broke every account whose client picked a
// starting dc_id other than the server's.
func TestKeyExchangeAcceptsMismatchedDCByDefault(t *testing.T) {
func TestKeyExchangeAcceptsAnyDCLabelByDefault(t *testing.T) {
ex := serverExchangeCompat{dc: 2, log: zaptest.NewLogger(t)}
if err := ex.validatePQInnerDataDC(&mt.PQInnerDataDC{DC: 3}); err != nil {
t.Fatalf("permanent DC mismatch: err = %v, want nil (lenient by default)", err)
labels := []int{
2, // canonical
3, // another production DC
0, // no conventional DC mapping
-2, // Android media-temp convention
10002, // test-environment style label
-10002, // negative test-environment style label
-1 << 31,
1<<31 - 1,
}
if err := ex.validatePQInnerDataDC(&mt.PQInnerDataTempDC{DC: -3}); err != nil {
t.Fatalf("temp DC mismatch: err = %v, want nil (lenient by default)", err)
for _, label := range labels {
t.Run(fmt.Sprintf("permanent_%d", label), func(t *testing.T) {
if err := ex.validatePQInnerDataDC(&mt.PQInnerDataDC{DC: label}); err != nil {
t.Fatalf("validate permanent DC label %d: %v", label, err)
}
})
t.Run(fmt.Sprintf("temporary_%d", label), func(t *testing.T) {
if err := ex.validatePQInnerDataDC(&mt.PQInnerDataTempDC{DC: label, ExpiresIn: 60}); err != nil {
t.Fatalf("validate temporary DC label %d: %v", label, err)
}
})
}
}
// TestKeyExchangeRejectsMismatchedPermanentDCWhenStrict asserts that
// strictDC=true still enforces exact DC-ID equality for permanent-key
// exchange (kept for a hypothetical future real multi-DC deployment).
func TestKeyExchangeRejectsMismatchedPermanentDCWhenStrict(t *testing.T) {
func TestKeyExchangePersistsArbitraryPermanentDCLabelByDefault(t *testing.T) {
const clientDC = 10002
keys := memory.NewAuthKeyStore()
addr, pub, _ := startTestServer(t, Options{DC: 2, AuthKeys: keys})
_, auth, _ := dialHandshake(t, addr, clientDC, pub)
saved, found, err := keys.Get(context.Background(), auth.AuthKey.ID)
if err != nil {
t.Fatalf("get persisted auth key: %v", err)
}
if !found {
t.Fatalf("auth key %x was not persisted", auth.AuthKey.ID)
}
if saved.Value != [256]byte(auth.AuthKey.Value) {
t.Fatal("persisted auth key value mismatch")
}
}
func TestKeyExchangeStrictDCValidation(t *testing.T) {
ex := serverExchangeCompat{dc: 2, strictDC: true, log: zaptest.NewLogger(t)}
err := ex.validatePQInnerDataDC(&mt.PQInnerDataDC{DC: 3})
tests := []struct {
name string
data mt.PQInnerDataClass
wantErr bool
}{
{name: "permanent exact", data: &mt.PQInnerDataDC{DC: 2}},
{name: "permanent other", data: &mt.PQInnerDataDC{DC: 3}, wantErr: true},
{name: "permanent zero", data: &mt.PQInnerDataDC{DC: 0}, wantErr: true},
{name: "temporary positive exact", data: &mt.PQInnerDataTempDC{DC: 2}},
{name: "temporary negative exact", data: &mt.PQInnerDataTempDC{DC: -2}},
{name: "temporary other", data: &mt.PQInnerDataTempDC{DC: 3}, wantErr: true},
{name: "temporary negative other", data: &mt.PQInnerDataTempDC{DC: -3}, wantErr: true},
{name: "temporary test label", data: &mt.PQInnerDataTempDC{DC: 10002}, wantErr: true},
{name: "temporary min int32", data: &mt.PQInnerDataTempDC{DC: -1 << 31}, wantErr: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
err := ex.validatePQInnerDataDC(test.data)
if !test.wantErr {
if err != nil {
t.Fatalf("validate: %v", err)
}
return
}
assertWrongDCError(t, err)
})
}
}
func assertWrongDCError(t *testing.T, err error) {
t.Helper()
var exErr *exchange.ServerExchangeError
if !errors.As(err, &exErr) {
t.Fatalf("err = %T %v, want ServerExchangeError", err, err)

View file

@ -303,20 +303,12 @@ type Options struct {
// DC 是本 server 的 DC ID。默认 2。
DC int
// StrictDC turns on exact DC-ID validation for the permanent-key exchange
// (default off = lenient). telesrv is always a single physical backend —
// there is no real multi-DC federation behind it — but self-hosted client
// forks commonly run in "single-server backend" mode, where dc_id 1..5 all
// alias to this one server so that any old data referencing a specific
// dc_id still resolves correctly. When a client adds a new local account it
// picks its own starting dc_id (its usual multi-DC load-spreading
// behavior, unrelated to which physical server it's actually talking to)
// — that choice is not guaranteed to equal our configured DC. Strict
// validation would reject those accounts with "-444 wrong dc_id" even
// though they are connecting to the right (and only) server; dc_id is a
// client-side routing label here, not part of key derivation, so
// accepting the mismatch does not weaken the exchange. The switch exists
// for a hypothetical future real multi-DC deployment.
// StrictDC enables DC-label validation during key exchange. It is false by
// default: this single physical backend accepts every wire int32 label for
// permanent and temporary keys, and the label never changes auth-key
// persistence, session identity, or business state. When enabled,
// permanent labels must equal DC and temporary labels may equal +/-DC.
// This diagnostic switch does not itself provide multi-DC isolation.
StrictDC bool
// RSAKey 是 server RSA 私钥用于密钥交换。nil 时无法完成握手。
RSAKey *rsa.PrivateKey