Skip to main content

ferogram_mtproto/
bind_temp_key.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2//
3// ferogram: async Telegram MTProto client in Rust
4// https://github.com/ankit-chaubey/ferogram
5//
6// Licensed under either the MIT License or the Apache License 2.0.
7// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
8// https://github.com/ankit-chaubey/ferogram
9//
10// Feel free to use, modify, and share this code.
11// Please keep this notice when redistributing.
12
13use ferogram_crypto::{aes, derive_aes_key_iv_v1, fill_random};
14
15fn serialize_inner(
16    nonce: i64,
17    temp_auth_key_id: i64,
18    perm_auth_key_id: i64,
19    temp_session_id: i64,
20    expires_at: i32,
21) -> [u8; 40] {
22    let mut out = [0u8; 40];
23    out[0..4].copy_from_slice(&0x75a3f765_u32.to_le_bytes());
24    out[4..12].copy_from_slice(&nonce.to_le_bytes());
25    out[12..20].copy_from_slice(&temp_auth_key_id.to_le_bytes());
26    out[20..28].copy_from_slice(&perm_auth_key_id.to_le_bytes());
27    out[28..36].copy_from_slice(&temp_session_id.to_le_bytes());
28    out[36..40].copy_from_slice(&expires_at.to_le_bytes());
29    out
30}
31
32/// Build the `encrypted_message` bytes for `auth.bindTempAuthKey`.
33pub fn encrypt_bind_inner(
34    perm_auth_key: &[u8; 256],
35    msg_id: i64,
36    nonce: i64,
37    temp_auth_key_id: i64,
38    perm_auth_key_id: i64,
39    temp_session_id: i64,
40    expires_at: i32,
41) -> Vec<u8> {
42    let inner = serialize_inner(
43        nonce,
44        temp_auth_key_id,
45        perm_auth_key_id,
46        temp_session_id,
47        expires_at,
48    );
49
50    let header_len = 32usize;
51    let content_len = header_len + 40;
52    let pad_len = (16 - content_len % 16) % 16;
53    let total = content_len + pad_len;
54
55    let mut rnd = [0u8; 24];
56    fill_random(&mut rnd);
57
58    let mut plaintext = Vec::with_capacity(total);
59    plaintext.extend_from_slice(&rnd[..8]);
60    plaintext.extend_from_slice(&rnd[8..16]);
61    plaintext.extend_from_slice(&msg_id.to_le_bytes());
62    plaintext.extend_from_slice(&0i32.to_le_bytes());
63    plaintext.extend_from_slice(&40u32.to_le_bytes());
64    plaintext.extend_from_slice(&inner);
65    plaintext.extend_from_slice(&rnd[16..16 + pad_len]);
66    assert_eq!(plaintext.len(), total);
67
68    let hash: [u8; 20] = ferogram_crypto::sha1!(&plaintext[..content_len]);
69    let mut msg_key = [0u8; 16];
70    msg_key.copy_from_slice(&hash[4..20]);
71
72    let (aes_key, aes_iv) = derive_aes_key_iv_v1(perm_auth_key, &msg_key);
73    aes::ige_encrypt(&mut plaintext, &aes_key, &aes_iv);
74
75    let key_sha: [u8; 20] = ferogram_crypto::sha1!(perm_auth_key);
76
77    let mut result = Vec::with_capacity(8 + 16 + plaintext.len());
78    result.extend_from_slice(&key_sha[12..20]);
79    result.extend_from_slice(&msg_key);
80    result.extend_from_slice(&plaintext);
81    result
82}
83
84/// Serialize `auth.bindTempAuthKey#cdd42a05` to raw TL bytes.
85pub fn serialize_bind_temp_auth_key(
86    perm_auth_key_id: i64,
87    nonce: i64,
88    expires_at: i32,
89    encrypted_message: &[u8],
90) -> Vec<u8> {
91    let mut out = Vec::new();
92    out.extend_from_slice(&0xcdd42a05_u32.to_le_bytes());
93    out.extend_from_slice(&perm_auth_key_id.to_le_bytes());
94    out.extend_from_slice(&nonce.to_le_bytes());
95    out.extend_from_slice(&expires_at.to_le_bytes());
96    tl_write_bytes(&mut out, encrypted_message);
97    out
98}
99
100/// Returns the auth-key ID: SHA-1(key)[12..20] as little-endian i64.
101pub fn auth_key_id_from_key(key: &[u8; 256]) -> i64 {
102    let hash: [u8; 20] = ferogram_crypto::sha1!(key);
103    i64::from_le_bytes(hash[12..20].try_into().unwrap())
104}
105
106/// Generate a monotonic MTProto message ID from the current system clock.
107///
108/// The previous implementation used `nanos & !3` (clears bottom 2 bits), which
109/// produces values in range 0..999_999_996. `EncryptedSession::next_msg_id` uses
110/// `nanos << 2` (multiply by 4), range 0..3_999_999_996. At the same wall-clock
111/// instant the old `gen_msg_id` output was 4x smaller in the lower 32 bits than
112/// any msg_id already assigned by the session, triggering `bad_msg_notification`
113/// code 16 (msg_id too low) from the server on the bind request.
114/// Uses `nanos << 2` to match the session's scaling exactly.
115pub fn gen_msg_id() -> i64 {
116    use std::time::{SystemTime, UNIX_EPOCH};
117    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
118    let secs = now.as_secs();
119    let nanos = now.subsec_nanos() as u64;
120    // Use same formula as EncryptedSession::next_msg_id: nanos << 2.
121    // Bottom 2 bits are 0 (plaintext DH handshake message; not content-related).
122    ((secs << 32) | (nanos << 2)) as i64
123}
124
125fn tl_write_bytes(out: &mut Vec<u8>, data: &[u8]) {
126    let len = data.len();
127    if len < 254 {
128        out.push(len as u8);
129        out.extend_from_slice(data);
130        let pad = (4 - (1 + len) % 4) % 4;
131        out.extend(std::iter::repeat_n(0u8, pad));
132    } else {
133        out.push(0xfe);
134        out.push((len & 0xff) as u8);
135        out.push(((len >> 8) & 0xff) as u8);
136        out.push(((len >> 16) & 0xff) as u8);
137        out.extend_from_slice(data);
138        let pad = (4 - (4 + len) % 4) % 4;
139        out.extend(std::iter::repeat_n(0u8, pad));
140    }
141}