1/*
2 This file is part of Mtproto-proxy Library.
3
4 Mtproto-proxy Library is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
8
9 Mtproto-proxy Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with Mtproto-proxy Library. If not, see <http://www.gnu.org/licenses/>.
16
17 Copyright 2010-2013 Vkontakte Ltd
18 2010-2013 Nikolai Durov
19 2010-2013 Andrey Lopatin
20 2013 Vitaliy Valtman
21
22 Copyright 2014-2016 Telegram Messenger Inc
23 2014-2016 Nikolai Durov
24 2014-2016 Vitaliy Valtman
25*/
26
27#define _FILE_OFFSET_BITS 64
28
29#include <assert.h>
30#include <fcntl.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <time.h>
35#include <unistd.h>
36
37// #include <openssl/aes.h>
38
39#include "kprintf.h"
40#include "precise-time.h"
41
42#include "net/net-crypto-aes.h"
43#include "net/net-config.h"
44
45#include "net/net-connections.h"
46#include "md5.h"
47#include "sha1.h"
48
49#include "jobs/jobs.h"
50#include "common/common-stats.h"
51
52#define MODULE crypto_aes
53
54MODULE_STAT_TYPE {
55 int allocated_aes_crypto, allocated_aes_crypto_temp;
56};
57
58MODULE_INIT
59
60MODULE_STAT_FUNCTION
61 SB_SUM_ONE_I (allocated_aes_crypto);
62 SB_SUM_ONE_I (allocated_aes_crypto_temp);
63
64 sb_printf (sb,
65 "aes_pwd_hash\t%s\n",
66 pwd_config_md5);
67MODULE_STAT_FUNCTION_END
68
69void fetch_aes_crypto_stat (int *allocated_aes_crypto_ptr, int *allocated_aes_crypto_temp_ptr) {
70 if (allocated_aes_crypto_ptr) {
71 *allocated_aes_crypto_ptr = SB_SUM_I (allocated_aes_crypto);
72 }
73 if (allocated_aes_crypto_temp_ptr) {
74 *allocated_aes_crypto_temp_ptr = SB_SUM_I (allocated_aes_crypto_temp);
75 }
76}
77
78aes_secret_t main_secret;
79
80int aes_crypto_init (connection_job_t c, void *key_data, int key_data_len) {
81 assert (key_data_len == sizeof (struct aes_key_data));
82 struct aes_crypto *T = NULL;
83 assert (!posix_memalign ((void **)&T, 16, sizeof (struct aes_crypto)));
84 struct aes_key_data *D = key_data;
85 assert (T);
86
87 MODULE_STAT->allocated_aes_crypto ++;
88
89 tg_aes_set_decrypt_key (&T->read_aeskey, D->read_key, 256);
90 memcpy (T->read_iv, D->read_iv, 16);
91 tg_aes_set_encrypt_key (&T->write_aeskey, D->write_key, 256);
92 memcpy (T->write_iv, D->write_iv, 16);
93 // T->read_pos = T->write_pos = 0;
94 T->read_num = T->write_num = 0;
95 CONN_INFO(c)->crypto = T;
96 return 0;
97}
98
99int aes_crypto_ctr128_init (connection_job_t c, void *key_data, int key_data_len) {
100 assert (key_data_len == sizeof (struct aes_key_data));
101 struct aes_crypto *T = NULL;
102 assert (!posix_memalign ((void **)&T, 16, sizeof (struct aes_crypto)));
103 struct aes_key_data *D = key_data;
104 assert (T);
105
106 MODULE_STAT->allocated_aes_crypto ++;
107
108 tg_aes_set_encrypt_key (&T->read_aeskey, D->read_key, 256); // NB: *_encrypt_key here!
109 memcpy (T->read_iv, D->read_iv, 16);
110 tg_aes_set_encrypt_key (&T->write_aeskey, D->write_key, 256);
111 memcpy (T->write_iv, D->write_iv, 16);
112 // T->read_pos = T->write_pos = 0;
113 T->read_num = T->write_num = 0;
114 CONN_INFO(c)->crypto = T;
115 return 0;
116}
117
118int aes_crypto_free (connection_job_t c) {
119 if (CONN_INFO(c)->crypto) {
120 free (CONN_INFO(c)->crypto);
121 CONN_INFO(c)->crypto = 0;
122 MODULE_STAT->allocated_aes_crypto --;
123 }
124 if (CONN_INFO(c)->crypto_temp) {
125 free (CONN_INFO(c)->crypto_temp);
126 CONN_INFO(c)->crypto_temp = 0;
127 MODULE_STAT->allocated_aes_crypto_temp --;
128 }
129 return 0;
130}
131
132
133int aes_initialized;
134static char rand_buf[64];
135
136// filename = 0 -- use DEFAULT_PWD_FILE
137// 1 = init ok, else < 0
138int aes_load_pwd_file (const char *filename) {
139 int h = open ("/dev/random", O_RDONLY | O_NONBLOCK);
140 int r = 0;
141
142 if (h >= 0) {
143 r = read (h, rand_buf, 16);
144 if (r < 0) {
145 perror ("READ");
146 r = 0;
147 }
148 if (r > 0) {
149 vkprintf (2, "added %d bytes of real entropy to the AES security key\n", r);
150 }
151 if (r < 0) {
152 perror ("read from random");
153 r = 0;
154 }
155 close (h);
156 }
157
158 if (r < 16) {
159 h = open ("/dev/urandom", O_RDONLY);
160 if (h < 0) {
161 main_secret.secret_len = 0;
162 return -1;
163 }
164 int s = read (h, rand_buf + r, 16 - r);
165 if (r + s != 16) {
166 main_secret.secret_len = 0;
167 return -1;
168 }
169 close (h);
170 }
171
172 *(long *) rand_buf ^= lrand48_j();
173
174 srand48 (*(long *)rand_buf);
175
176 if (!filename) {
177 filename = DEFAULT_PWD_FILE;
178 }
179
180 h = open (filename, O_RDONLY);
181
182 if (h < 0) {
183 vkprintf (1, "cannot open password file %s: %m\n", filename);
184 return -0x80000000;
185 }
186
187 r = read (h, pwd_config_buf, MAX_PWD_CONFIG_LEN + 1);
188
189 close (h);
190
191 if (r < 0) {
192 vkprintf (1, "error reading password file %s: %m\n", filename);
193 return -1;
194 }
195
196 vkprintf (1, "loaded %d bytes from password file %s\n", r, filename);
197
198 if (r > MAX_PWD_CONFIG_LEN) {
199 pwd_config_len = 0;
200 return -1;
201 }
202
203 pwd_config_len = r;
204 memset (pwd_config_buf + r, 0, 4);
205
206 if (r < MIN_PWD_LEN || r > MAX_PWD_LEN) {
207 vkprintf (1, "secret file %s too long or too short: loaded %d bytes, expected %d..%d\n", filename, r, MIN_PWD_LEN, MAX_PWD_LEN);
208 return -1;
209 }
210
211 md5_hex (pwd_config_buf, pwd_config_len, pwd_config_md5);
212
213 memcpy (main_secret.secret, pwd_config_buf, r);
214 main_secret.secret_len = r;
215
216 aes_initialized = 1;
217
218 return 1;
219}
220
221int aes_generate_nonce (char res[16]) {
222 *(int *)(rand_buf + 16) = lrand48_j ();
223 *(int *)(rand_buf + 20) = lrand48_j ();
224 *(long long *)(rand_buf + 24) = rdtsc ();
225 struct timespec T;
226 assert (clock_gettime(CLOCK_REALTIME, &T) >= 0);
227 *(int *)(rand_buf + 32) = T.tv_sec;
228 *(int *)(rand_buf + 36) = T.tv_nsec;
229 (*(int *)(rand_buf + 40))++;
230
231 md5 ((unsigned char *)rand_buf, 44, (unsigned char *)res);
232 return 0;
233}
234
235
236// str := nonce_server.nonce_client.client_timestamp.server_ip.client_port.("SERVER"/"CLIENT").client_ip.server_port.master_key.nonce_server.[client_ipv6.server_ipv6].nonce_client
237// key := SUBSTR(MD5(str+1),0,12).SHA1(str)
238// iv := MD5(str+2)
239
240int aes_create_keys (struct aes_key_data *R, int am_client, const char nonce_server[16], const char nonce_client[16], int client_timestamp,
241 unsigned server_ip, unsigned short server_port, const unsigned char server_ipv6[16],
242 unsigned client_ip, unsigned short client_port, const unsigned char client_ipv6[16],
243 const aes_secret_t *key, const unsigned char *temp_key, int temp_key_len) {
244 unsigned char str[16+16+4+4+2+6+4+2+MAX_PWD_LEN+16+16+4+16*2 + 256];
245 int i, str_len;
246
247 if (!key->secret_len) {
248 return -1;
249 }
250
251 assert (key->secret_len >= MIN_PWD_LEN && key->secret_len <= MAX_PWD_LEN);
252
253 memcpy (str, nonce_server, 16);
254 memcpy (str + 16, nonce_client, 16);
255 *((int *) (str + 32)) = client_timestamp;
256 *((unsigned *) (str + 36)) = server_ip;
257 *((unsigned short *) (str + 40)) = client_port;
258 memcpy (str + 42, am_client ? "CLIENT" : "SERVER", 6);
259 *((unsigned *) (str + 48)) = client_ip;
260 *((unsigned short *) (str + 52)) = server_port;
261 memcpy (str + 54, key->secret, key->secret_len);
262 memcpy (str + 54 + key->secret_len, nonce_server, 16);
263 str_len = 70 + key->secret_len;
264
265 if (!server_ip) {
266 assert (!client_ip);
267 memcpy (str + str_len, client_ipv6, 16);
268 memcpy (str + str_len + 16, server_ipv6, 16);
269 str_len += 32;
270 } else {
271 assert (client_ip);
272 }
273
274 memcpy (str + str_len, nonce_client, 16);
275 str_len += 16;
276
277 if (temp_key_len > sizeof (str)) {
278 temp_key_len = sizeof (str);
279 }
280
281 int first_len = str_len < temp_key_len ? str_len : temp_key_len;
282
283 for (i = 0; i < first_len; i++) {
284 str[i] ^= temp_key[i];
285 }
286
287 for (i = first_len; i < temp_key_len; i++) {
288 str[i] = temp_key[i];
289 }
290
291 if (str_len < temp_key_len) {
292 str_len = temp_key_len;
293 }
294
295 md5 (str + 1, str_len - 1, R->write_key);
296 sha1 (str, str_len, R->write_key + 12);
297 md5 (str + 2, str_len - 2, R->write_iv);
298
299 //memcpy (str + 42, !am_client ? "CLIENT" : "SERVER", 6);
300 str[42] ^= 'C' ^ 'S';
301 str[43] ^= 'L' ^ 'E';
302 str[44] ^= 'I' ^ 'R';
303 str[45] ^= 'E' ^ 'V';
304 str[46] ^= 'N' ^ 'E';
305 str[47] ^= 'T' ^ 'R';
306
307 md5 (str + 1, str_len - 1, R->read_key);
308 sha1 (str, str_len, R->read_key + 12);
309 md5 (str + 2, str_len - 2, R->read_iv);
310
311 memset (str, 0, str_len);
312
313 return 1;
314}
315
316int get_crypto_key_id (void) {
317 if (main_secret.secret_len >= 4) {
318 return main_secret.key_signature;
319 } else {
320 return 0;
321 }
322}
323
324int get_extra_crypto_key_ids (int *buf, int max) {
325 return 0;
326}
327
328int is_valid_crypto_key_id (int x) {
329 return x && x == main_secret.key_signature && main_secret.secret_len >= 4;
330}
331
332void free_crypto_temp (void *crypto, int len) {
333 memset (crypto, 0, len);
334 free (crypto);
335 MODULE_STAT->allocated_aes_crypto_temp --;
336}
337
338void *alloc_crypto_temp (int len) {
339 void *res = malloc (len);
340 assert (res);
341 MODULE_STAT->allocated_aes_crypto_temp ++;
342 return res;
343}
344