forked from vysheng/tgl
-
Notifications
You must be signed in to change notification settings - Fork 9
/
mtproto-client.c
1495 lines (1271 loc) · 45.9 KB
/
mtproto-client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of tgl-library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Copyright Nikolay Durov, Andrey Lopatin 2012-2013
Vitaly Valtman 2013-2015
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _FILE_OFFSET_BITS 64
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#ifdef WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#endif
#include "crypto/rand.h"
#include "crypto/rsa_pem.h"
#include "crypto/sha.h"
//#include "telegram.h"
#include "queries.h"
//#include "loop.h"
#include "tgl-structures.h"
#include "tgl-binlog.h"
#include "auto.h"
#include "auto/auto-types.h"
#include "auto/auto-skip.h"
#include "tgl.h"
#include "mtproto-client.h"
#include "tools.h"
#include "tree.h"
#include "updates.h"
#include "mtproto-utils.h"
#include "auto.h"
#include "tgl-methods-in.h"
#include "mtproto-common.h"
#define MAX_NET_RES (1L << 16)
//extern int log_level;
static long long generate_next_msg_id (struct tgl_state *TLS, struct tgl_dc *DC, struct tgl_session *S);
static double get_server_time (struct tgl_dc *DC);
// for statistic only
static int total_packets_sent;
static long long total_data_sent;
static int rpc_execute (struct tgl_state *TLS, struct connection *c, int op, int len);
static int rpc_becomes_ready (struct tgl_state *TLS, struct connection *c);
static int rpc_close (struct tgl_state *TLS, struct connection *c);
static double get_utime (int clock_id) {
struct timespec T;
tgl_my_clock_gettime (clock_id, &T);
return T.tv_sec + (double) T.tv_nsec * 1e-9;
}
#define MAX_RESPONSE_SIZE (1L << 24)
static TGLC_rsa *rsa_load_public_key (struct tgl_state *TLS, const char *public_key_name) {
FILE *f = fopen (public_key_name, "r");
if (f == NULL) {
vlogprintf (E_WARNING, "Couldn't open public key file: %s\n", public_key_name);
return NULL;
}
TGLC_rsa *res = TGLC_pem_read_RSAPublicKey (f);
fclose (f);
if (res == NULL) {
vlogprintf (E_WARNING, "TGLC_pem_read_RSAPublicKey returns NULL.\n");
return NULL;
}
vlogprintf (E_NOTICE, "public key '%s' loaded successfully\n", public_key_name);
return res;
}
/*
*
* UNAUTHORIZED (DH KEY EXCHANGE) PROTOCOL PART
*
*/
#define ENCRYPT_BUFFER_INTS 16384
static int encrypt_buffer[ENCRYPT_BUFFER_INTS];
#define DECRYPT_BUFFER_INTS 16384
static int decrypt_buffer[ENCRYPT_BUFFER_INTS];
static int encrypt_packet_buffer (struct tgl_state *TLS, struct tgl_dc *DC) {
TGLC_rsa *key = TLS->rsa_key_loaded[DC->rsa_key_idx];
return tgl_pad_rsa_encrypt (TLS, (char *) packet_buffer, (packet_ptr - packet_buffer) * 4, (char *) encrypt_buffer, ENCRYPT_BUFFER_INTS * 4, TGLC_rsa_n (key), TGLC_rsa_e (key));
}
static int encrypt_packet_buffer_aes_unauth (const char server_nonce[16], const char hidden_client_nonce[32]) {
tgl_init_aes_unauth (server_nonce, hidden_client_nonce, 1);
return tgl_pad_aes_encrypt ((char *) packet_buffer, (packet_ptr - packet_buffer) * 4, (char *) encrypt_buffer, ENCRYPT_BUFFER_INTS * 4);
}
//
// Used in unauthorized part of protocol
//
static int rpc_send_packet (struct tgl_state *TLS, struct connection *c) {
static struct {
long long auth_key_id;
long long out_msg_id;
int msg_len;
} unenc_msg_header;
int len = (packet_ptr - packet_buffer) * 4;
TLS->net_methods->incr_out_packet_num (c);
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
struct tgl_session *S = TLS->net_methods->get_session (c);
unenc_msg_header.out_msg_id = generate_next_msg_id (TLS, DC, S);
unenc_msg_header.msg_len = len;
int total_len = len + 20;
assert (total_len > 0 && !(total_len & 0xfc000003));
total_len >>= 2;
vlogprintf (E_DEBUG, "writing packet: total_len = %d, len = %d\n", total_len, len);
if (total_len < 0x7f) {
assert (TLS->net_methods->write_out (c, &total_len, 1) == 1);
} else {
total_len = (total_len << 8) | 0x7f;
assert (TLS->net_methods->write_out (c, &total_len, 4) == 4);
}
TLS->net_methods->write_out (c, &unenc_msg_header, 20);
TLS->net_methods->write_out (c, packet_buffer, len);
TLS->net_methods->flush_out (c);
total_packets_sent ++;
total_data_sent += total_len;
return 1;
}
static int rpc_send_message (struct tgl_state *TLS, struct connection *c, void *data, int len) {
assert (len > 0 && !(len & 0xfc000003));
int total_len = len >> 2;
if (total_len < 0x7f) {
assert (TLS->net_methods->write_out (c, &total_len, 1) == 1);
} else {
total_len = (total_len << 8) | 0x7f;
assert (TLS->net_methods->write_out (c, &total_len, 4) == 4);
}
TLS->net_methods->incr_out_packet_num (c);
assert (TLS->net_methods->write_out (c, data, len) == len);
TLS->net_methods->flush_out (c);
total_packets_sent ++;
total_data_sent += total_len;
return 1;
}
//
// State machine. See description at
// https://core.telegram.org/mtproto/auth_key
//
static int check_unauthorized_header (struct tgl_state *TLS) {
long long auth_key_id = fetch_long ();
if (auth_key_id) {
vlogprintf (E_ERROR, "ERROR: auth_key_id should be NULL\n");
return -1;
}
fetch_long (); // msg_id
int len = fetch_int ();
if (len != 4 * (in_end - in_ptr)) {
vlogprintf (E_ERROR, "ERROR: length mismatch\n");
return -1;
}
return 0;
}
/* {{{ REQ_PQ */
// req_pq#60469778 nonce:int128 = ResPQ
static int send_req_pq_packet (struct tgl_state *TLS, struct connection *c) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
assert (DC->state == st_init);
tglt_secure_random (DC->nonce, 16);
clear_packet ();
out_int (CODE_req_pq);
out_ints ((int *)DC->nonce, 4);
rpc_send_packet (TLS, c);
DC->state = st_reqpq_sent;
return 1;
}
// req_pq#60469778 nonce:int128 = ResPQ
static int send_req_pq_temp_packet (struct tgl_state *TLS, struct connection *c) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
assert (DC->state == st_authorized);
tglt_secure_random (DC->nonce, 16);
clear_packet ();
out_int (CODE_req_pq);
out_ints ((int *)DC->nonce, 4);
rpc_send_packet (TLS, c);
DC->state = st_reqpq_sent_temp;
return 1;
}
/* }}} */
/* {{{ REQ DH */
// req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;
// p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;
// p_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;
static void send_req_dh_packet (struct tgl_state *TLS, struct connection *c, TGLC_bn *pq, int temp_key) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
TGLC_bn *p = TGLC_bn_new ();
TGLC_bn *q = TGLC_bn_new ();
assert (bn_factorize (pq, p, q) >= 0);
clear_packet ();
packet_ptr += 5;
out_int (temp_key ? CODE_p_q_inner_data_temp : CODE_p_q_inner_data);
out_bignum (pq);
out_bignum (p);
out_bignum (q);
out_ints ((int *) DC->nonce, 4);
out_ints ((int *) DC->server_nonce, 4);
tglt_secure_random (DC->new_nonce, 32);
out_ints ((int *) DC->new_nonce, 8);
if (temp_key) {
out_int (TLS->temp_key_expire_time);
}
TGLC_sha1 ((unsigned char *) (packet_buffer + 5), (packet_ptr - packet_buffer - 5) * 4, (unsigned char *) packet_buffer);
int l = encrypt_packet_buffer (TLS, DC);
clear_packet ();
out_int (CODE_req_DH_params);
out_ints ((int *) DC->nonce, 4);
out_ints ((int *) DC->server_nonce, 4);
out_bignum (p);
out_bignum (q);
out_long (TLS->rsa_key_fingerprint[DC->rsa_key_idx]);
out_cstring ((char *) encrypt_buffer, l);
TGLC_bn_free (p);
TGLC_bn_free (q);
DC->state = temp_key ? st_reqdh_sent_temp : st_reqdh_sent;
rpc_send_packet (TLS, c);
}
/* }}} */
/* {{{ SEND DH PARAMS */
// set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;
// client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data
static void send_dh_params (struct tgl_state *TLS, struct connection *c, TGLC_bn *dh_prime, TGLC_bn *g_a, int g, int temp_key) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
clear_packet ();
packet_ptr += 5;
out_int (CODE_client_DH_inner_data);
out_ints ((int *) DC->nonce, 4);
out_ints ((int *) DC->server_nonce, 4);
out_long (0);
TGLC_bn *dh_g = TGLC_bn_new ();
ensure (TGLC_bn_set_word (dh_g, g));
static unsigned char s_power[256];
tglt_secure_random (s_power, 256);
TGLC_bn *dh_power = TGLC_bn_bin2bn ((unsigned char *)s_power, 256, 0);
ensure_ptr (dh_power);
TGLC_bn *y = TGLC_bn_new ();
ensure_ptr (y);
ensure (TGLC_bn_mod_exp (y, dh_g, dh_power, dh_prime, TLS->TGLC_bn_ctx));
out_bignum (y);
TGLC_bn_free (y);
TGLC_bn *auth_key_num = TGLC_bn_new ();
ensure (TGLC_bn_mod_exp (auth_key_num, g_a, dh_power, dh_prime, TLS->TGLC_bn_ctx));
int l = TGLC_bn_num_bytes (auth_key_num);
assert (l >= 250 && l <= 256);
assert (TGLC_bn_bn2bin (auth_key_num, (unsigned char *)(temp_key ? DC->temp_auth_key : DC->auth_key)));
if (l < 256) {
char *key = temp_key ? DC->temp_auth_key : DC->auth_key;
memmove (key + 256 - l, key, l);
memset (key, 0, 256 - l);
}
TGLC_bn_free (dh_power);
TGLC_bn_free (auth_key_num);
TGLC_bn_free (dh_g);
TGLC_sha1 ((unsigned char *) (packet_buffer + 5), (packet_ptr - packet_buffer - 5) * 4, (unsigned char *) packet_buffer);
l = encrypt_packet_buffer_aes_unauth (DC->server_nonce, DC->new_nonce);
clear_packet ();
out_int (CODE_set_client_DH_params);
out_ints ((int *) DC->nonce, 4);
out_ints ((int *) DC->server_nonce, 4);
out_cstring ((char *) encrypt_buffer, l);
DC->state = temp_key ? st_client_dh_sent_temp : st_client_dh_sent;;
rpc_send_packet (TLS, c);
}
/* }}} */
/* {{{ RECV RESPQ */
// resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector long = ResPQ
static int process_respq_answer (struct tgl_state *TLS, struct connection *c, char *packet, int len, int temp_key) {
assert (!(len & 3));
in_ptr = (int *)packet;
in_end = in_ptr + (len / 4);
if (check_unauthorized_header (TLS) < 0) {
return -1;
}
int *in_save = in_ptr;
if (skip_type_any (TYPE_TO_PARAM (res_p_q)) < 0 || in_ptr != in_end) {
vlogprintf (E_ERROR, "can not parse req_p_q answer\n");
return -1;
}
in_ptr = in_save;
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
assert (fetch_int() == CODE_res_p_q);
static int tmp[4];
fetch_ints (tmp, 4);
if (memcmp (tmp, DC->nonce, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
fetch_ints (DC->server_nonce, 4);
TGLC_bn *pq = TGLC_bn_new ();
assert (fetch_bignum (pq) >= 0);
assert (fetch_int () == CODE_vector);
int fingerprints_num = fetch_int ();
assert (fingerprints_num >= 0);
DC->rsa_key_idx = -1;
int i;
for (i = 0; i < fingerprints_num; i++) {
int j;
long long fprint = fetch_long ();
for (j = 0; j < TLS->rsa_key_num; j++) {
if (TLS->rsa_key_loaded[j]) {
if (fprint == TLS->rsa_key_fingerprint[j]) {
DC->rsa_key_idx = j;
break;
}
}
}
}
assert (in_ptr == in_end);
if (DC->rsa_key_idx == -1) {
vlogprintf (E_ERROR, "fatal: don't have any matching keys\n");
return -1;
}
send_req_dh_packet (TLS, c, pq, temp_key);
TGLC_bn_free (pq);
return 1;
}
/* }}} */
/* {{{ RECV DH */
// server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;
// server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;
// server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;
static int process_dh_answer (struct tgl_state *TLS, struct connection *c, char *packet, int len, int temp_key) {
assert (!(len & 3));
in_ptr = (int *)packet;
in_end = in_ptr + (len / 4);
if (check_unauthorized_header (TLS) < 0) {
return -1;
}
int *in_save = in_ptr;
if (skip_type_any (TYPE_TO_PARAM (server_d_h_params)) < 0 || in_ptr != in_end) {
vlogprintf (E_ERROR, "can not parse server_DH_params answer\n");
return -1;
}
in_ptr = in_save;
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
unsigned op = fetch_int ();
assert (op == CODE_server__d_h_params_ok || op == CODE_server__d_h_params_fail);
int tmp[4];
fetch_ints (tmp, 4);
if (memcmp (tmp, DC->nonce, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
assert (!memcmp (tmp, DC->nonce, 16));
fetch_ints (tmp, 4);
if (memcmp (tmp, DC->server_nonce, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
assert (!memcmp (tmp, DC->server_nonce, 16));
if (op == CODE_server__d_h_params_fail) {
vlogprintf (E_ERROR, "DH params fail\n");
return -1;
}
tgl_init_aes_unauth (DC->server_nonce, DC->new_nonce, 0);
int l = prefetch_strlen ();
assert (l >= 0);
if (!l) {
vlogprintf (E_ERROR, "non-empty encrypted part expected\n");
return -1;
}
l = tgl_pad_aes_decrypt (fetch_str (l), l, (char *) decrypt_buffer, DECRYPT_BUFFER_INTS * 4 - 16);
assert (in_ptr == in_end);
in_ptr = decrypt_buffer + 5;
in_end = decrypt_buffer + (l >> 2);
if (skip_type_any (TYPE_TO_PARAM (server_d_h_inner_data)) < 0) {
vlogprintf (E_ERROR, "can not parse server_DH_inner_data answer\n");
return -1;
}
in_ptr = decrypt_buffer + 5;
assert (fetch_int () == (int)CODE_server_DH_inner_data);
fetch_ints (tmp, 4);
if (memcmp (tmp, DC->nonce, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
assert (!memcmp (tmp, DC->nonce, 16));
fetch_ints (tmp, 4);
if (memcmp (tmp, DC->server_nonce, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
assert (!memcmp (tmp, DC->server_nonce, 16));
int g = fetch_int ();
TGLC_bn *dh_prime = TGLC_bn_new ();
TGLC_bn *g_a = TGLC_bn_new ();
assert (fetch_bignum (dh_prime) > 0);
assert (fetch_bignum (g_a) > 0);
if (tglmp_check_DH_params (TLS, dh_prime, g) < 0) {
vlogprintf (E_ERROR, "bad DH params\n");
return -1;
}
if (tglmp_check_g_a (TLS, dh_prime, g_a) < 0) {
vlogprintf (E_ERROR, "bad dh_prime\n");
return -1;
}
int server_time = fetch_int ();
assert (in_ptr <= in_end);
static char sha1_buffer[20];
TGLC_sha1 ((unsigned char *) decrypt_buffer + 20, (in_ptr - decrypt_buffer - 5) * 4, (unsigned char *) sha1_buffer);
if (memcmp (decrypt_buffer, sha1_buffer, 20)) {
vlogprintf (E_ERROR, "bad encrypted message SHA1\n");
return -1;
}
if ((char *) in_end - (char *) in_ptr >= 16) {
vlogprintf (E_ERROR, "too much padding\n");
return -1;
}
DC->server_time_delta = server_time - get_utime (CLOCK_REALTIME);
DC->server_time_udelta = server_time - get_utime (CLOCK_MONOTONIC);
send_dh_params (TLS, c, dh_prime, g_a, g, temp_key);
TGLC_bn_free (dh_prime);
TGLC_bn_free (g_a);
return 1;
}
/* }}} */
static void create_temp_auth_key (struct tgl_state *TLS, struct connection *c) {
assert (TLS->enable_pfs);
send_req_pq_temp_packet (TLS, c);
}
int tglmp_encrypt_inner_temp (struct tgl_state *TLS, struct connection *c, int *msg, int msg_ints, int useful, void *data, long long msg_id);
static long long msg_id_override;
static void mpc_on_get_config (struct tgl_state *TLS, void *extra, int success);
static void bind_temp_auth_key (struct tgl_state *TLS, struct connection *c);
/* {{{ RECV AUTH COMPLETE */
// dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;
// dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;
// dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;
static int process_auth_complete (struct tgl_state *TLS, struct connection *c, char *packet, int len, int temp_key) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
assert (!(len & 3));
in_ptr = (int *)packet;
in_end = in_ptr + (len / 4);
if (check_unauthorized_header (TLS) < 0) {
return -1;
}
int *in_save = in_ptr;
if (skip_type_any (TYPE_TO_PARAM (set_client_d_h_params_answer)) < 0 || in_ptr != in_end) {
vlogprintf (E_ERROR, "can not parse server_DH_params answer\n");
return -1;
}
in_ptr = in_save;
unsigned op = fetch_int ();
assert (op == CODE_dh_gen_ok || op == CODE_dh_gen_retry || op == CODE_dh_gen_fail);
int tmp[4];
fetch_ints (tmp, 4);
if (memcmp (DC->nonce, tmp, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
fetch_ints (tmp, 4);
if (memcmp (DC->server_nonce, tmp, 16)) {
vlogprintf (E_ERROR, "nonce mismatch\n");
return -1;
}
if (op != CODE_dh_gen_ok) {
vlogprintf (E_ERROR, "something bad. Retry regen\n");
return -1;
}
fetch_ints (tmp, 4);
static unsigned char th[44], sha1_buffer[20];
memcpy (th, DC->new_nonce, 32);
th[32] = 1;
if (!temp_key) {
TGLC_sha1 ((unsigned char *)DC->auth_key, 256, sha1_buffer);
} else {
TGLC_sha1 ((unsigned char *)DC->temp_auth_key, 256, sha1_buffer);
}
memcpy (th + 33, sha1_buffer, 8);
TGLC_sha1 (th, 41, sha1_buffer);
if (memcmp (tmp, sha1_buffer + 4, 16)) {
vlogprintf (E_ERROR, "hash mismatch\n");
return -1;
}
if (!temp_key) {
bl_do_set_auth_key (TLS, DC->id, (unsigned char *)DC->auth_key);
TGLC_sha1 ((unsigned char *)DC->auth_key, 256, sha1_buffer);
} else {
TGLC_sha1 ((unsigned char *)DC->temp_auth_key, 256, sha1_buffer);
DC->temp_auth_key_id = *(long long *)(sha1_buffer + 12);
}
DC->server_salt = *(long long *)DC->server_nonce ^ *(long long *)DC->new_nonce;
DC->state = st_authorized;
vlogprintf (E_DEBUG, "Auth success\n");
if (temp_key) {
bind_temp_auth_key (TLS, c);
} else {
DC->flags |= 1;
if (TLS->enable_pfs) {
assert (TLS->enable_pfs);
create_temp_auth_key (TLS, c);
} else {
DC->temp_auth_key_id = DC->auth_key_id;
memcpy (DC->temp_auth_key, DC->auth_key, 256);
DC->flags |= 2;
if (!(DC->flags & 4)) {
tgl_do_help_get_config_dc (TLS, DC, mpc_on_get_config, DC);
}
}
}
return 1;
}
/* }}} */
static void bind_temp_auth_key (struct tgl_state *TLS, struct connection *c) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
if (DC->temp_auth_key_bind_query_id) {
tglq_query_delete (TLS, DC->temp_auth_key_bind_query_id);
}
struct tgl_session *S = TLS->net_methods->get_session (c);
long long msg_id = generate_next_msg_id (TLS, DC, S);
clear_packet ();
out_int (CODE_bind_auth_key_inner);
long long rand;
tglt_secure_random (&rand, 8);
out_long (rand);
out_long (DC->temp_auth_key_id);
out_long (DC->auth_key_id);
if (!S->session_id) {
tglt_secure_random (&S->session_id, 8);
}
out_long (S->session_id);
int expires = time (0) + DC->server_time_delta + TLS->temp_key_expire_time;
out_int (expires);
static int data[1000];
int len = tglmp_encrypt_inner_temp (TLS, c, packet_buffer, packet_ptr - packet_buffer, 0, data, msg_id);
msg_id_override = msg_id;
DC->temp_auth_key_bind_query_id = msg_id;
tgl_do_send_bind_temp_key (TLS, DC, rand, expires, (void *)data, len, msg_id);
msg_id_override = 0;
}
/*
*
* AUTHORIZED (MAIN) PROTOCOL PART
*
*/
static struct encrypted_message enc_msg;
static double get_server_time (struct tgl_dc *DC) {
//if (!DC->server_time_udelta) {
// DC->server_time_udelta = get_utime (CLOCK_REALTIME) - get_utime (CLOCK_MONOTONIC);
//}
return get_utime (CLOCK_MONOTONIC) + DC->server_time_udelta;
}
static long long generate_next_msg_id (struct tgl_state *TLS, struct tgl_dc *DC, struct tgl_session *S) {
long long next_id = (long long) (get_server_time (DC) * (1LL << 32)) & -4;
if (next_id <= TLS->last_msg_id) {
next_id = TLS->last_msg_id += 4;
} else {
TLS->last_msg_id = next_id;
}
S->last_msg_id = next_id; // See tglmp_encrypt_send_message
return next_id;
}
static void init_enc_msg (struct tgl_state *TLS, struct tgl_session *S, int useful) {
struct tgl_dc *DC = S->dc;
assert (DC->state == st_authorized);
assert (DC->temp_auth_key_id);
vlogprintf (E_DEBUG, "temp_auth_key_id = 0x%016" INT64_PRINTF_MODIFIER "x, auth_key_id = 0x%016" INT64_PRINTF_MODIFIER "x\n", DC->temp_auth_key_id, DC->auth_key_id);
enc_msg.auth_key_id = DC->temp_auth_key_id;
enc_msg.server_salt = DC->server_salt;
if (!S->session_id) {
tglt_secure_random (&S->session_id, 8);
}
enc_msg.session_id = S->session_id;
enc_msg.msg_id = msg_id_override ? msg_id_override : generate_next_msg_id (TLS, DC, S);
enc_msg.seq_no = S->seq_no;
if (useful) {
enc_msg.seq_no |= 1;
}
S->seq_no += 2;
};
static void init_enc_msg_inner_temp (struct tgl_dc *DC, long long msg_id) {
enc_msg.auth_key_id = DC->auth_key_id;
tglt_secure_random (&enc_msg.server_salt, 8);
tglt_secure_random (&enc_msg.session_id, 8);
enc_msg.msg_id = msg_id;
enc_msg.seq_no = 0;
};
static int aes_encrypt_message (struct tgl_state *TLS, char *key, struct encrypted_message *enc) {
unsigned char sha1_buffer[20];
const int MINSZ = offsetof (struct encrypted_message, message);
const int UNENCSZ = offsetof (struct encrypted_message, server_salt);
int enc_len = (MINSZ - UNENCSZ) + enc->msg_len;
assert (enc->msg_len >= 0 && enc->msg_len <= MAX_MESSAGE_INTS * 4 - 16 && !(enc->msg_len & 3));
TGLC_sha1 ((unsigned char *) &enc->server_salt, enc_len, sha1_buffer);
vlogprintf (E_DEBUG, "sending message with sha1 %08x\n", *(int *)sha1_buffer);
memcpy (enc->msg_key, sha1_buffer + 4, 16);
tgl_init_aes_auth (key, enc->msg_key, 1);
return tgl_pad_aes_encrypt ((char *) &enc->server_salt, enc_len, (char *) &enc->server_salt, MAX_MESSAGE_INTS * 4 + (MINSZ - UNENCSZ));
}
long long tglmp_encrypt_send_message (struct tgl_state *TLS, struct connection *c, int *msg, int msg_ints, int flags) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
struct tgl_session *S = TLS->net_methods->get_session (c);
assert (S);
if (!(DC->flags & 4) && !(flags & 2)) {
return generate_next_msg_id (TLS, DC, S);
}
const int UNENCSZ = offsetof (struct encrypted_message, server_salt);
if (msg_ints <= 0 || msg_ints > MAX_MESSAGE_INTS - 4) {
return -1;
}
if (msg) {
memcpy (enc_msg.message, msg, msg_ints * 4);
enc_msg.msg_len = msg_ints * 4;
} else {
if ((enc_msg.msg_len & 0x80000003) || enc_msg.msg_len > MAX_MESSAGE_INTS * 4 - 16) {
return -1;
}
}
init_enc_msg (TLS, S, flags & 1);
int l = aes_encrypt_message (TLS, DC->temp_auth_key, &enc_msg);
assert (l > 0);
rpc_send_message (TLS, c, &enc_msg, l + UNENCSZ);
return S->last_msg_id; // Pray that this was set by generate_next_msg_id somehow
}
int tglmp_encrypt_inner_temp (struct tgl_state *TLS, struct connection *c, int *msg, int msg_ints, int useful, void *data, long long msg_id) {
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
struct tgl_session *S = TLS->net_methods->get_session (c);
assert (S);
const int UNENCSZ = offsetof (struct encrypted_message, server_salt);
if (msg_ints <= 0 || msg_ints > MAX_MESSAGE_INTS - 4) {
return -1;
}
memcpy (enc_msg.message, msg, msg_ints * 4);
enc_msg.msg_len = msg_ints * 4;
init_enc_msg_inner_temp (DC, msg_id);
int l = aes_encrypt_message (TLS, DC->auth_key, &enc_msg);
assert (l > 0);
//rpc_send_message (c, &enc_msg, l + UNENCSZ);
memcpy (data, &enc_msg, l + UNENCSZ);
return l + UNENCSZ;
}
static int rpc_execute_answer (struct tgl_state *TLS, struct connection *c, long long msg_id);
static int work_container (struct tgl_state *TLS, struct connection *c, long long msg_id) {
vlogprintf (E_DEBUG, "work_container: msg_id = %" INT64_PRINTF_MODIFIER "d\n", msg_id);
assert (fetch_int () == CODE_msg_container);
int n = fetch_int ();
int i;
for (i = 0; i < n; i++) {
long long id = fetch_long ();
//int seqno = fetch_int ();
fetch_int (); // seq_no
if (id & 1) {
tgln_insert_msg_id (TLS, TLS->net_methods->get_session (c), id);
}
int bytes = fetch_int ();
int *t = in_end;
in_end = in_ptr + (bytes / 4);
int r = rpc_execute_answer (TLS, c, id);
if (r < 0) { return -1; }
assert (in_ptr == in_end);
in_end = t;
}
return 0;
}
static int work_new_session_created (struct tgl_state *TLS, struct connection *c, long long msg_id) {
struct tgl_session *S = TLS->net_methods->get_session (c);
struct tgl_dc *DC = TLS->net_methods->get_dc (c);
vlogprintf (E_NOTICE, "work_new_session_created: msg_id = %" INT64_PRINTF_MODIFIER "d, dc = %d\n", msg_id, DC->id);
assert (fetch_int () == (int)CODE_new_session_created);
fetch_long (); // first message id
fetch_long (); // unique_id
TLS->net_methods->get_dc (c)->server_salt = fetch_long ();
tglq_regen_queries_from_old_session (TLS, DC, S);
if (TLS->started && !(TLS->locks & TGL_LOCK_DIFF) && (TLS->DC_working->flags & TGLDCF_LOGGED_IN)) {
tgl_do_get_difference (TLS, 0, 0, 0);
}
return 0;
}
static int work_msgs_ack (struct tgl_state *TLS, struct connection *c, long long msg_id) {
vlogprintf (E_DEBUG, "work_msgs_ack: msg_id = %" INT64_PRINTF_MODIFIER "d\n", msg_id);
assert (fetch_int () == CODE_msgs_ack);
assert (fetch_int () == CODE_vector);
int n = fetch_int ();
int i;
for (i = 0; i < n; i++) {
long long id = fetch_long ();
vlogprintf (E_DEBUG + 1, "ack for %" INT64_PRINTF_MODIFIER "d\n", id);
tglq_query_ack (TLS, id);
}
return 0;
}
static int work_rpc_result (struct tgl_state *TLS, struct connection *c, long long msg_id) {
vlogprintf (E_DEBUG, "work_rpc_result: msg_id = %" INT64_PRINTF_MODIFIER "d\n", msg_id);
assert (fetch_int () == (int)CODE_rpc_result);
long long id = fetch_long ();
int op = prefetch_int ();
if (op == CODE_rpc_error) {
return tglq_query_error (TLS, id);
} else {
return tglq_query_result (TLS, id);
}
}
#define MAX_PACKED_SIZE (1 << 24)
static int work_packed (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == CODE_gzip_packed);
static int in_gzip;
static int buf[MAX_PACKED_SIZE >> 2];
assert (!in_gzip);
in_gzip = 1;
int l = prefetch_strlen ();
char *s = fetch_str (l);
int total_out = tgl_inflate (s, l, buf, MAX_PACKED_SIZE);
int *end = in_ptr;
int *eend = in_end;
//assert (total_out % 4 == 0);
in_ptr = buf;
in_end = in_ptr + total_out / 4;
int r = rpc_execute_answer (TLS, c, msg_id);
in_ptr = end;
in_end = eend;
in_gzip = 0;
return r;
}
static int work_bad_server_salt (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == (int)CODE_bad_server_salt);
long long id = fetch_long ();
fetch_int (); // seq_no
fetch_int (); // error_code
long long new_server_salt = fetch_long ();
TLS->net_methods->get_dc (c)->server_salt = new_server_salt;
tglq_query_restart (TLS, id);
return 0;
}
static int work_pong (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == CODE_pong);
fetch_long (); // msg_id
fetch_long (); // ping_id
return 0;
}
static int work_detailed_info (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == CODE_msg_detailed_info);
fetch_long (); // msg_id
fetch_long (); // answer_msg_id
fetch_int (); // bytes
fetch_int (); // status
return 0;
}
static int work_new_detailed_info (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == (int)CODE_msg_new_detailed_info);
fetch_long (); // answer_msg_id
fetch_int (); // bytes
fetch_int (); // status
return 0;
}
static int work_bad_msg_notification (struct tgl_state *TLS, struct connection *c, long long msg_id) {
assert (fetch_int () == (int)CODE_bad_msg_notification);
long long m1 = fetch_long ();
int s = fetch_int ();
int e = fetch_int ();
vlogprintf (E_NOTICE, "bad_msg_notification: msg_id = %" INT64_PRINTF_MODIFIER "d, seq = %d, error = %d\n", m1, s, e);
switch (e) {
// Too low msg id
case 16:
tglq_regen_query (TLS, m1);
break;
// Too high msg id
case 17:
tglq_regen_query (TLS, m1);
break;
// Bad container
case 64:
vlogprintf (E_NOTICE, "bad_msg_notification: msg_id = %" INT64_PRINTF_MODIFIER "d, seq = %d, error = %d\n", m1, s, e);
tglq_regen_query (TLS, m1);
break;
default:
vlogprintf (E_NOTICE, "bad_msg_notification: msg_id = %" INT64_PRINTF_MODIFIER "d, seq = %d, error = %d\n", m1, s, e);
break;
}
return -1;
}
static int rpc_execute_answer (struct tgl_state *TLS, struct connection *c, long long msg_id) {
int op = prefetch_int ();
switch (op) {
case CODE_msg_container:
return work_container (TLS, c, msg_id);
case CODE_new_session_created:
return work_new_session_created (TLS, c, msg_id);
case CODE_msgs_ack:
return work_msgs_ack (TLS, c, msg_id);
case CODE_rpc_result:
return work_rpc_result (TLS, c, msg_id);
case CODE_update_short:
case CODE_updates:
case CODE_update_short_message:
case CODE_update_short_chat_message:
case CODE_updates_too_long:
tglu_work_any_updates_buf (TLS);
return 0;
case CODE_gzip_packed:
return work_packed (TLS, c, msg_id);
case CODE_bad_server_salt:
return work_bad_server_salt (TLS, c, msg_id);
case CODE_pong:
return work_pong (TLS, c, msg_id);
case CODE_msg_detailed_info:
return work_detailed_info (TLS, c, msg_id);
case CODE_msg_new_detailed_info:
return work_new_detailed_info (TLS, c, msg_id);
case CODE_bad_msg_notification:
return work_bad_msg_notification (TLS, c, msg_id);
}
vlogprintf (E_WARNING, "Unknown message: %08x\n", op);
in_ptr = in_end; // Will not fail due to assertion in_ptr == in_end
return 0;
}
static struct mtproto_methods mtproto_methods;
void tgls_free_session (struct tgl_state *TLS, struct tgl_session *S);
/*
static char *get_ipv6 (struct tgl_state *TLS, int num) {
static char res[1<< 10];
if (TLS->test_mode) {
switch (num) {
case 1:
strcpy (res, TG_SERVER_TEST_IPV6_1);
break;
case 2:
strcpy (res, TG_SERVER_TEST_IPV6_2);
break;
case 3:
strcpy (res, TG_SERVER_TEST_IPV6_3);
break;
default:
assert (0);
}
} else {
switch (num) {
case 1:
strcpy (res, TG_SERVER_IPV6_1);
break;
case 2:
strcpy (res, TG_SERVER_IPV6_2);