← 返回 Skills 市场
zhihang9978

MTProto 2.0

作者 zhihang9978 · GitHub ↗ · v1.0.1 · MIT-0
cross-platform ✓ 安全检测通过
247
总下载
0
收藏
0
当前安装
2
版本数
在 OpenClaw 中安装
/install mtproto-2-0
功能描述
MTProto 2.0 protocol implementation guide for Telegram backend development. Use when implementing MTProto encryption, handshake, message serialization, or bu...
使用说明 (SKILL.md)

MTProto 2.0 Protocol

Complete implementation guide for Telegram's MTProto 2.0 encryption protocol.

⚠️ IMPORTANT SECURITY NOTICE

This skill provides educational guidance on MTProto 2.0 protocol. Before using in production:

  1. Verify Auth Key ID size: Ensure 8-byte alignment throughout your implementation
  2. Use crypto/rand: Never use math/rand for cryptographic operations
  3. Test against official vectors: Validate against Telegram's reference implementations
  4. Audit by experts: Have cryptographers review before handling real keys
  5. Check off-by-one errors: Carefully validate all buffer sizes and offsets

See references/security-notice.md for detailed corrections.

Quick Reference

Core Components

  • Auth Key: 256-bit symmetric key from DH exchange
  • Server Salt: 64-bit anti-replay nonce
  • Message Key: 128-bit message identifier
  • AES-256-IGE: Encryption mode with error propagation

When to Use

Use this skill when:

  1. Implementing MTProto handshake (req_pq → req_DH_params → set_client_DH_params)
  2. Encrypting/decrypting MTProto messages
  3. Serializing TL objects
  4. Building Telegram-compatible gateways
  5. Debugging connection issues

Handshake Flow

Client                              Server
  |                                    |
  | 1. req_pq                        |
  |----------------------------------->|
  |                                    |
  | 2. server_public_key_fingerprints|
  |\x3C-----------------------------------|
  |                                    |
  | 3. req_DH_params                 |
  |----------------------------------->|
  |                                    |
  | 4. server_DH_params              |
  |\x3C-----------------------------------|
  |                                    |
  | 5. set_client_DH_params          |
  |----------------------------------->|
  |                                    |
  | 6. dh_gen_ok                     |
  |\x3C-----------------------------------|

See references/handshake.md for detailed implementation.

Encryption

AES-256-IGE Mode

// Key derivation from Auth Key + Message Key
func deriveKeys(authKey, msgKey []byte) (aesKey, aesIV []byte) {
    x := sha256.Sum256(append(msgKey, authKey[:36]...))
    y := sha256.Sum256(append(authKey[40:76], msgKey...))
    
    aesKey = append(x[:8], y[8:24]...)
    aesIV = append(y[:8], x[24:32]...)
    return
}

See references/encryption.md for complete algorithm.

Message Format

Encrypted Message Structure

┌─────────────────────────────────────────────────────────┐
│ Auth Key ID     │ 8 bytes  │ SHA1(authKey)[96:128]      │
├─────────────────────────────────────────────────────────┤
│ Message Key     │ 16 bytes │ SHA256(plaintext)[8:24]    │
├─────────────────────────────────────────────────────────┤
│ Encrypted Data  │ Variable │ AES-256-IGE encrypted      │
└─────────────────────────────────────────────────────────┘

Plaintext Structure

┌─────────────────────────────────────────────────────────┐
│ Salt            │ 8 bytes  │ Server Salt                │
├─────────────────────────────────────────────────────────┤
│ Session ID      │ 8 bytes  │ Unique session ID          │
├─────────────────────────────────────────────────────────┤
│ Message ID      │ 8 bytes  │ Timestamp + sequence       │
├─────────────────────────────────────────────────────────┤
│ Sequence No     │ 4 bytes  │ Packet sequence            │
├─────────────────────────────────────────────────────────┤
│ Length          │ 4 bytes  │ Message body length        │
├─────────────────────────────────────────────────────────┤
│ Message Body    │ Variable │ TL-serialized data         │
├─────────────────────────────────────────────────────────┤
│ Padding         │ 0-15 B   │ Random padding             │
└─────────────────────────────────────────────────────────┘

See references/message-format.md for details.

TL Language

Type Serialization

// Constructor with ID
user#938458c1 id:long first_name:string = User;

// Method definition
checkPhone#6fe51dfb phone_number:string = Bool;

See references/tl-language.md for TL schema reference.

Security Features

Forward Secrecy

  • Auth Key derived from ephemeral DH exchange
  • Keys rotated periodically
  • Old key compromise doesn't expose history

Anti-Replay Protection

  • Server Salt changes per connection
  • Message ID includes timestamp
  • Sequence number verification
  • Time window validation

Integrity Verification

  • Message Key from SHA256 hash
  • AES-IGE error propagation
  • Length field validation

Go Implementation

Basic Connection

type MTProtoConn struct {
    conn      net.Conn
    authKey   []byte
    salt      int64
    sessionID int64
    seqNo     int32
}

func (m *MTProtoConn) Send(msg TLObject) error {
    // 1. Serialize
    plaintext := msg.Encode()
    
    // 2. Calculate Message Key
    msgKey := calcMsgKey(plaintext, m.authKey)
    
    // 3. Derive AES keys
    aesKey, aesIV := deriveKeys(m.authKey, msgKey)
    
    // 4. Encrypt
    encrypted := encryptAESIGE(plaintext, aesKey, aesIV)
    
    // 5. Construct packet
    packet := constructPacket(m.authKey, msgKey, encrypted)
    
    // 6. Send
    _, err := m.conn.Write(packet)
    return err
}

References

Official Resources

安全使用建议
This is a documentation/implementation guide (no installation or network behavior). It is internally coherent and appropriate for implementing MTProto, but several example code snippets are insecure if copied verbatim: they use math/rand for cryptographic nonces/padding, sometimes ignore errors (e.g., aes.NewCipher returned error ignored), and show padding/IV handling that must be carefully reviewed. The bundle itself includes a 'Security Notice' that identifies and corrects many of these issues — follow those corrections. Before using any example code in production you should: (1) replace all math/rand usages with crypto/rand, (2) ensure constant-time comparisons for MACs, (3) handle errors properly and avoid panics, (4) validate DH primes and parameter sizes, (5) test against official Telegram reference vectors, and (6) obtain a cryptographer/security audit. If you need the skill to perform runtime actions (build/run code, handle real keys, or contact networks), do not use these examples directly; instead implement corrected, reviewed code and treat all sample keys/IDs as documentation-only.
功能分析
Type: OpenClaw Skill Name: mtproto-2-0 Version: 1.0.1 The skill bundle is a comprehensive technical guide for implementing the MTProto 2.0 protocol. It contains educational documentation and Go code snippets for AES-256-IGE encryption, Diffie-Hellman handshakes, and TL serialization. Notably, the bundle includes a dedicated security notice (references/security-notice.md) that proactively identifies and corrects common implementation vulnerabilities, such as the use of non-cryptographic random number generators (math/rand). No indicators of malicious intent, data exfiltration, or prompt injection were found.
能力评估
Purpose & Capability
Name/description match the provided content: all files are MTProto protocol references, handshake, encryption, TL language, and implementation examples. There are no unrelated env vars, binaries, or installs requested.
Instruction Scope
SKILL.md and referenced files are purely implementation guidance and do not instruct the agent to read system files, exfiltrate data, or call external endpoints. However, multiple code examples demonstrate insecure practices (use of math/rand, improper IV handling, panic-based error handling, ignoring returned errors) — the package includes a clear security-notice that calls these out and provides corrections.
Install Mechanism
Instruction-only skill with no install spec and no code to be downloaded or executed at install time, so there is no install-time code execution risk.
Credentials
No environment variables, credentials, or config paths are requested. There are no surprising permissions or cross-service credentials required.
Persistence & Privilege
Skill is not always-enabled and uses default invocation behavior. It does not request to persist configuration or modify other skills or system-wide settings.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install mtproto-2-0
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /mtproto-2-0 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.1
v1.0.1: Added security notice document with critical fixes for production use. Fixed Auth Key ID size documentation, crypto/rand usage, and off-by-one error warnings.
v1.0.0
Initial release: MTProto 2.0 protocol implementation guide for Telegram backend development
元数据
Slug mtproto-2-0
版本 1.0.1
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 2
常见问题

MTProto 2.0 是什么?

MTProto 2.0 protocol implementation guide for Telegram backend development. Use when implementing MTProto encryption, handshake, message serialization, or bu... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 247 次。

如何安装 MTProto 2.0?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install mtproto-2-0」即可一键安装,无需额外配置。

MTProto 2.0 是免费的吗?

是的,MTProto 2.0 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

MTProto 2.0 支持哪些平台?

MTProto 2.0 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 MTProto 2.0?

由 zhihang9978(@zhihang9978)开发并维护,当前版本 v1.0.1。

💬 留言讨论