MTProto Protocol Layer in Teamgram Server
Skill Type
This is a reference/knowledge skill. It contains no executable code. It documents the MTProto protocol handling internals of Teamgram Server (open-source, Apache-2.0 licensed) for developers who need to understand, debug, or extend the protocol layer.
Overview
KHF client and Teamgram Server communicate via Telegram's MTProto binary protocol. The Teamgram gateway layer (gnetway) performs 3 key operations:
- 1. Handshake / authkey generation (unauthenticated phase: authkey_id=0 -> handshake)
- Authenticated message decryption (AES-IGE)
- Forward decrypted payload (TLMessage2.Object) to session service via gRPC
Runtime Environment (for Teamgram Server operators)
If you are deploying Teamgram Server (not just reading this skill), the MTProto layer requires:
| Component | Purpose | Configuration |
|---|
| gnetway service | TCP/WS gateway, listens on ports 10443/5222/11443 | INLINECODE0 |
| session service |
Manages auth sessions, routes RPCs |
app/interface/session/etc/session.yaml |
| MySQL | Stores auth_key records (
auth_keys,
auth_key_infos tables) | Configured in service YAML files |
| Redis | Caches auth_key for fast lookup | Configured in service YAML files |
| etcd | Service discovery between gnetway and session |
etcd.hosts in YAML config |
No credentials are required to read or install this skill. The above table is for reference only when operating the actual Teamgram Server.
Core Data Structure
The decrypted data structure is mtproto.TLMessage2, whose Object field contains the specific TL RPC call (e.g., auth.sendCode, messages.sendMessage, etc.).
QuickAck Mechanism
gnetway implements QuickAck token computation. ACKs must be encoded through the codec to avoid obfuscated CTR counter desync (otherwise Android clients will fail at decryptServerResponse).
Reference function (from app/interface/gnetway/internal/server/gnet/server_gnet.go:298-305 in teamgram-server):
CODEBLOCK0
Encrypted Message Processing Flow
- 1. Decrypt via INLINECODE10
- Extract from decrypted payload header:
salt, sessionId, INLINECODE13 - Forward
payload[16:] to session service via SessionDispatcher.SendData (gRPC)
auth_key Caching and QueryAuthKey
When connContext lacks an authKey, gnetway asynchronously calls the session service's QueryAuthKey RPC, then proceeds with onEncryptedMessage after receiving the key.
Key management note: auth_keys are generated during the DH handshake, stored in MySQL (auth_keys table), and cached in Redis. They are never exposed outside the server process. The gnetway service holds keys only in memory during active connections.
KHF Client Protocol Constants (must match server)
Extracted from KHF client source code:
- - INLINECODE20
- INLINECODE21
- INLINECODE22
These are public application identifiers, not secrets. They must match between client and server for TL schema compatibility.
Important Notes
- - QuickAck must be encoded through codec, otherwise obfuscated CTR counter will desync
- Messages with authkeyid=0 go through handshake flow; non-zero go through decryption flow
- After AES-IGE decryption, the first 16 bytes of payload are salt+sessionId, followed by TLMessage2 data
Source Code References
All code referenced in this skill is from the open-source Teamgram Server project:
- - Repository: https://github.com/teamgram/teamgram-server
- License: Apache-2.0
- Gateway code: INLINECODE23
- Session code: INLINECODE24
- MTProto codec:
mtproto/ package
Teamgram 服务器中的 MTProto 协议层
技能类型
这是一个参考/知识技能。 它不包含任何可执行代码。它记录了 Teamgram 服务器(开源,Apache-2.0 许可)的 MTProto 协议处理内部机制,供需要理解、调试或扩展协议层的开发者使用。
概述
KHF 客户端和 Teamgram 服务器通过 Telegram 的 MTProto 二进制协议进行通信。Teamgram 网关层(gnetway)执行 3 个关键操作:
- 1. 握手 / authkey 生成(未认证阶段:authkey_id=0 -> 握手)
- 认证消息解密(AES-IGE)
- 通过 gRPC 将解密后的负载(TLMessage2.Object)转发到会话服务
运行时环境(适用于 Teamgram 服务器运维人员)
如果你正在部署 Teamgram 服务器(不仅仅是阅读此技能),MTProto 层需要:
| 组件 | 用途 | 配置 |
|---|
| gnetway 服务 | TCP/WS 网关,监听端口 10443/5222/11443 | app/interface/gnetway/etc/gnetway.yaml |
| session 服务 |
管理认证会话,路由 RPC | app/interface/session/etc/session.yaml |
| MySQL | 存储 auth
key 记录(authkeys、auth
keyinfos 表) | 在服务 YAML 文件中配置 |
| Redis | 缓存 auth_key 以便快速查找 | 在服务 YAML 文件中配置 |
| etcd | gnetway 和 session 之间的服务发现 | YAML 配置中的 etcd.hosts |
阅读或安装此技能无需任何凭据。 上表仅供实际操作 Teamgram 服务器时参考。
核心数据结构
解密后的数据结构是 mtproto.TLMessage2,其 Object 字段包含特定的 TL RPC 调用(例如 auth.sendCode、messages.sendMessage 等)。
QuickAck 机制
gnetway 实现了 QuickAck 令牌计算。ACK 必须通过编解码器编码,以避免混淆的 CTR 计数器不同步(否则 Android 客户端将在 decryptServerResponse 时失败)。
参考函数(来自 teamgram-server 中的 app/interface/gnetway/internal/server/gnet/servergnet.go:298-305):
go
func computeQuickAckToken(authKey []byte, encryptedData []byte) uint32 {
h := sha256.New()
h.Write(authKey[88 : 88+32])
h.Write(encryptedData)
var sum [32]byte
h.Sum(sum[:0])
return binary.LittleEndian.Uint32(sum[:4]) | 0x80000000
}
加密消息处理流程
- 1. 通过 authKey.AesIgeDecrypt 解密
- 从解密后的负载头部提取:salt、sessionId、msgId
- 通过 SessionDispatcher.SendData(gRPC)将 payload[16:] 转发到会话服务
auth_key 缓存与 QueryAuthKey
当 connContext 缺少 authKey 时,gnetway 异步调用会话服务的 QueryAuthKey RPC,然后在收到密钥后继续执行 onEncryptedMessage。
密钥管理说明: authkeys 在 DH 握手期间生成,存储在 MySQL(authkeys 表)中,并缓存在 Redis 中。它们永远不会暴露在服务器进程之外。gnetway 服务仅在活动连接期间在内存中持有密钥。
KHF 客户端协议常量(必须与服务器匹配)
从 KHF 客户端源代码中提取:
- - TLRPC.LAYER = 222
- BuildVars.APPID = 4
- BuildVars.APPHASH = 014b35b6184100b085b0d0572f9b5103
这些是公开的应用程序标识符,而非机密信息。它们必须在客户端和服务器之间匹配,以确保 TL 模式兼容性。
重要说明
- - QuickAck 必须通过编解码器编码,否则混淆的 CTR 计数器将不同步
- authkeyid=0 的消息走握手流程;非零的消息走解密流程
- AES-IGE 解密后,负载的前 16 个字节是 salt+sessionId,之后是 TLMessage2 数据
源代码参考
此技能中引用的所有代码均来自开源 Teamgram 服务器项目:
- - 仓库:https://github.com/teamgram/teamgram-server
- 许可证:Apache-2.0
- 网关代码:app/interface/gnetway/
- 会话代码:app/interface/session/
- MTProto 编解码器:mtproto/ 包