forked from packetflinger/q2admin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathg_cloud.c
More file actions
1511 lines (1279 loc) · 38.2 KB
/
g_cloud.c
File metadata and controls
1511 lines (1279 loc) · 38.2 KB
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
/**
* The cloud admin client maintains a separate TCP connection to a remote
* management server. The client (q2 server) and the cloud admin server
* mutually authenticate via asymmetrically encrypted challenges. Once trusted,
* the client feeds the server game information (player data, chats, frags,
* etc) and will do as the cloud admin server instructs (enforcing bans/mutes,
* telling players about other servers, etc).
*
* Server operators can connect to a cloud admin server by registering using
* it's web interface, exchanging public keys, and obtaining a unique
* identifier used in the connection handshake.
*
* The tcp connection is encrypted using AES-CBC with keys rotating about once
* an hour. AES-GCM would normally be a better mode as it's more modern and has
* authentication built-in, but it's too vulnerable in the event of IV reuse.
*/
#include "g_local.h"
cloud_t cloud;
/**
* Sets up the cloud admin connection.
*/
void CA_Init() {
if (cloud.connection.socket) {
return;
}
ReadCloudConfigFile();
memset(&cloud, 0, sizeof(cloud));
maxclients = gi.cvar("maxclients", "64", CVAR_LATCH);
if (!cloud_enabled) {
gi.cprintf(NULL, PRINT_HIGH, "Cloud Admin is disabled in your config.\n");
return;
}
cloud.state = CA_STATE_DISCONNECTED;
CA_printf("init...\n");
if (!G_LoadKeys()) {
cloud.state = CA_STATE_DISABLED;
return;
}
cloud.connection.encrypted = cloud_encryption;
if (!cloud_address[0]) {
CA_dprintf("cloud_addr is not set, disabling\n");
cloud.state = CA_STATE_DISABLED;
return;
}
if (!cloud_port) {
CA_dprintf("cloud_port is not set, disabling\n");
cloud.state = CA_STATE_DISABLED;
return;
}
G_StartThread(&CA_LookupAddress, NULL);
// delay connection by a few seconds
cloud.connect_retry_frame = FUTURE_CA_FRAME(5);
}
/**
* Load config from disk. First load from q2 folder, then the mod folder.
*/
void ReadCloudConfigFile()
{
Q_snprintf(buffer, sizeof(buffer), "%s/%s", moddir, configfile_cloud->string);
readCfgFile(buffer);
readCfgFile(configfile_cloud->string);
}
/**
* getaddrinfo's returns a linked-list of struct addrinfo. Figure out which
* result is the one we want (IPv6/IPv4)
*/
static struct addrinfo *select_addrinfo(struct addrinfo *a)
{
static struct addrinfo *v4, *v6;
if (!a) {
return NULL;
}
// Just in case it's set blank in the config
if (!cloud_dns[0]) {
q2a_strcpy(cloud_dns, "64");
}
// Save the first one of each address family if more than 1. They'll be in
// random order.
for (; a != NULL; a = a->ai_next) {
if (!v4 && a->ai_family == AF_INET) {
v4 = a;
}
if (!v6 && a->ai_family == AF_INET6) {
v6 = a;
}
}
// select one based on preference
if (cloud_dns[0] == '6' && v6) {
return v6;
} else if (cloud_dns[0] == '4' && v4) {
return v4;
} else if (cloud_dns[1] == '6' && v6) {
return v6;
} else if (cloud_dns[1] == '4' && v4) {
return v4;
}
return NULL;
}
/**
* Do a DNS lookup for remote server. This is done in a dedicated thread to
* prevent blocking. Otherwise the server (and all current players) will
* freeze in place when new players connect until their PTR record is resolved.
*/
void CA_LookupAddress(void)
{
char str_address[40];
struct addrinfo hints, *res = 0;
q2a_memset(&hints, 0, sizeof(hints));
q2a_memset(&res, 0, sizeof(res));
hints.ai_family = AF_UNSPEC; // either v6 or v4
hints.ai_socktype = SOCK_STREAM; // TCP
hints.ai_protocol = 0;
hints.ai_flags = AI_ADDRCONFIG; // only for v6 addresses
errno = 0;
int err = getaddrinfo(cloud_address, va("%d",cloud_port), &hints, &res);
if (err != 0) {
CA_dprintf("DNS error\n");
cloud.state = CA_STATE_DISABLED;
return;
} else {
q2a_memset(&cloud.addr, 0, sizeof(struct addrinfo));
// getaddrinfo can return multiple mixed v4/v6 results
cloud.addr = select_addrinfo(res);
if (!cloud.addr) {
cloud.state = CA_STATE_DISABLED;
CA_dprintf("problems resolving server address, disabling\n");
return;
}
if (res->ai_family == AF_INET6) {
cloud.connection.ipv6 = qtrue;
}
if (cloud.addr->ai_family == AF_INET6) {
q2a_inet_ntop(
cloud.addr->ai_family,
&((struct sockaddr_in6 *) cloud.addr->ai_addr)->sin6_addr,
str_address,
sizeof(str_address)
);
} else {
q2a_inet_ntop(
cloud.addr->ai_family,
&((struct sockaddr_in *) cloud.addr->ai_addr)->sin_addr,
str_address,
sizeof(str_address)
);
}
CA_dprintf("server resolved to %s\n", str_address);
}
cloud.flags = cloud_flags;
cloud.state = CA_STATE_DISCONNECTED;
}
/**
* Only DNS lookups use this
*/
void G_StartThread(void *func, void *arg) {
#if _WIN32
DWORD tid;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, 0, 0, &tid);
#else
pthread_t dnsthread;
pthread_create(&dnsthread, 0, func, 0);
#endif
}
/**
* Output to the q2 server console (if flags agree)
*/
void debug_print(char *str)
{
if (!RFL(DEBUG)) {
return;
}
gi.cprintf(NULL, PRINT_HIGH, "%s\n", str);
}
/**
* Periodically ping the server to know if the connection is still open. I'm
* not 100% sure this is necessary. TCP has built-in mechanisms for maintaining
* a connection if when no data is flowing.
*/
void CA_Ping(void)
{
if (cloud.state < CA_STATE_CONNECTED) {
return;
}
// not time yet
if (cloud.ping.frame_next > CA_FRAME) {
return;
}
// there is already an outstanding ping
if (cloud.ping.waiting) {
if (cloud.ping.miss_count == PING_MISS_MAX) {
CA_DisconnectedPeer();
return;
}
cloud.ping.miss_count++;
}
// state stuff
cloud.ping.frame_sent = CA_FRAME;
cloud.ping.waiting = qtrue;
cloud.ping.frame_next = CA_FRAME + SECS_TO_FRAMES(PING_FREQ_SECS);
// send it
CA_WriteByte(CMD_PING);
}
/**
* Run once per server frame. The default tick rate is 10hz or once every 0.1
* seconds, but servers like q2pro support variable framerates (divisible by 10
* up to 60), so this could run much more frequently.
*/
void CA_RunFrame(void)
{
cloud.frame_number++;
if (cloud.state == CA_STATE_DISABLED) {
return;
}
if (cloud.state >= CA_STATE_CONNECTED) {
CA_SendMessages();
CA_ReadMessages();
}
if (cloud.state == CA_STATE_TRUSTED) {
CA_Ping();
}
// connection started already, check for completion
if (cloud.state == CA_STATE_CONNECTING) {
CA_CheckConnection();
}
if (cloud.state == CA_STATE_DISCONNECTED) {
CA_Connect();
}
}
/**
* Local q2 server is shutting down, inform the backend too
*/
void CA_Shutdown(void)
{
if (cloud.state == CA_STATE_DISABLED) {
return;
}
// We have to call CA_SendMessages() specifically here because there won't
// be another frame to send the buffered CMD_QUIT
CA_WriteByte(CMD_QUIT);
CA_SendMessages();
CA_Disconnect();
freeaddrinfo(cloud.addr);
}
/**
* TCP connection was broken, reset local state in preparation for reconnecting
*/
void CA_Disconnect(void)
{
if (cloud.state < CA_STATE_CONNECTED) {
return;
}
closesocket(cloud.connection.socket);
cloud.state = CA_STATE_DISCONNECTED;
}
/**
* Get the frame number at which we should try another connection. Increase the
* interval as attempts increase without a connection. The longer the
* connection is inactive, the more infrequently it tries to reconnect.
*/
static uint32_t next_connect_frame(void)
{
if (cloud.connection_attempts < 12) { // 2 minutes
return FUTURE_CA_FRAME(10);
} else if (cloud.connection_attempts < 20) { // 10 minutes
return FUTURE_CA_FRAME(30);
} else if (cloud.connection_attempts < 50) { // 30 minutes
return FUTURE_CA_FRAME(60);
} else {
return FUTURE_CA_FRAME(120);
}
}
/**
* Make the connection to the backend
*/
void CA_Connect(void)
{
int flags, ret;
if (cloud.frame_number < cloud.connect_retry_frame) {
return;
}
q2a_memset(&cloud.queue, 0, sizeof(message_queue_t));
q2a_memset(&cloud.queue_in, 0, sizeof(message_queue_t));
cloud.state = CA_STATE_CONNECTING;
cloud.connection_attempts++;
cloud.connection.socket = socket(
cloud.addr->ai_family,
cloud.addr->ai_socktype,
cloud.addr->ai_protocol
);
if (cloud.connection.socket == -1) {
perror("connect");
errno = 0;
cloud.connect_retry_frame = next_connect_frame();
return;
}
// Make it non-blocking.
// preferred method is using POSIX O_NONBLOCK, if available
#if defined(O_NONBLOCK)
flags = 0;
ret = fcntl(cloud.connection.socket, F_SETFL, flags | O_NONBLOCK);
#else
flags = 1;
ret = ioctlsocket(cloud.connection.socket, FIONBIO, (long unsigned int *) &flags);
#endif
if (ret == -1) {
CA_printf("error setting socket to non-blocking: (%d) %s\n", errno, strerror(errno));
cloud.state = CA_STATE_DISCONNECTED;
cloud.connect_retry_frame = FUTURE_CA_FRAME(30);
}
errno = 0;
ret = connect(cloud.connection.socket, cloud.addr->ai_addr, cloud.addr->ai_addrlen);
if (ret == -1) {
if (errno == EINPROGRESS) {
// expected
} else {
perror("[cloud] connect error");
errno = 0;
}
}
// Since we're non-blocking, the connection won't complete in this single
// server frame. We have to select() for it on a later runframe. See
// CA_CheckConnection()
}
/**
* Check to see if the connection initiated by RA_Connect() has finished
*/
void CA_CheckConnection(void)
{
ca_connection_t *c;
uint32_t ret;
qboolean connected = qfalse;
struct sockaddr_storage addr;
socklen_t len;
struct timeval tv;
tv.tv_sec = tv.tv_usec = 0;
c = &cloud.connection;
FD_ZERO(&c->set_w);
FD_ZERO(&c->set_e);
FD_SET(c->socket, &c->set_w);
FD_SET(c->socket, &c->set_e);
// check if connection is fully established
ret = select((int)c->socket + 1, NULL, &c->set_w, &c->set_e, &tv);
if (ret) {
#ifdef LINUX
uint32_t number;
socklen_t len;
len = sizeof(number);
getsockopt(c->socket, SOL_SOCKET, SO_ERROR, &number, &len);
if (number == 0) {
connected = qtrue;
}
#else
if (FD_ISSET(c->socket, &c->set_w)) {
connected = qtrue;
}
#endif
}
if (ret == -1) {
perror("CheckConnection");
CA_printf("connection unfinished: %s\n", strerror(errno));
closesocket(c->socket);
cloud.state = CA_STATE_DISCONNECTED;
cloud.connect_retry_frame = FUTURE_CA_FRAME(10);
return;
}
// we need to make sure it's actually connected
if (connected) {
errno = 0;
getpeername(c->socket, (struct sockaddr *)&addr, &len);
if (errno) {
cloud.connect_retry_frame = FUTURE_CA_FRAME(30);
cloud.state = CA_STATE_DISCONNECTED;
closesocket(c->socket);
} else {
CA_printf("connected\n");
cloud.state = CA_STATE_CONNECTED;
cloud.ping.frame_next = FUTURE_CA_FRAME(10);
cloud.connected_frame = CA_FRAME;
CA_SayHello();
}
}
}
/**
* Send the contents of our outgoing buffer to the server
*/
void CA_SendMessages(void)
{
if (cloud.state < CA_STATE_CONNECTING) {
return;
}
if (!cloud.queue.length) {
return;
}
uint32_t ret;
struct timeval tv;
tv.tv_sec = tv.tv_usec = 0;
ca_connection_t *c;
message_queue_t *q, e;
c = &cloud.connection;
q = &cloud.queue;
while (qtrue) {
FD_ZERO(&c->set_w);
FD_SET(c->socket, &c->set_w);
// see if the socket is ready to send data
ret = select((int) c->socket + 1, NULL, &c->set_w, NULL, &tv);
if (ret == -1) {
perror("send select");
errno = 0;
}
// socket write buffer is ready, send
if (ret) {
if (c->encrypted && c->have_keys && cloud.state == CA_STATE_TRUSTED) {
q2a_memset(&e, 0, sizeof(message_queue_t));
e.length = G_SymmetricEncrypt(e.data, q->data, q->length);
q2a_memset(q, 0, sizeof(message_queue_t));
q2a_memcpy(q->data, e.data, e.length);
q->length = e.length;
}
ret = send(c->socket, q->data, q->length, 0);
if (ret == -1) {
if (errno == EPIPE) {
gi.cprintf(NULL, PRINT_HIGH, "Remote side disconnected\n");
CA_DisconnectedPeer();
errno = 0;
break;
}
perror("send error");
errno = 0;
} else {
// shift off the data we just sent
q2a_memmove(q->data, q->data + ret, q->length - ret);
q->length -= ret;
}
} else {
break;
}
// processed the whole queue, we're done for now
if (!q->length) {
break;
}
}
}
/**
* Accept any incoming messages from the server
*/
void CA_ReadMessages(void)
{
uint32_t ret, packet_count;
byte iv[AES_IV_LEN], temp_iv[DIGEST_LEN];
struct timeval tv;
message_queue_t *in, dec;
if (cloud.state < CA_STATE_CONNECTING) {
return;
}
tv.tv_sec = tv.tv_usec = 0;
// save some typing
in = &cloud.queue_in;
while (qtrue) {
FD_ZERO(&cloud.connection.set_r);
FD_SET(cloud.connection.socket, &cloud.connection.set_r);
// see if there is data waiting in the buffer for us to read
ret = select(cloud.connection.socket + 1, &cloud.connection.set_r, NULL, NULL, &tv);
if (ret == -1) {
if (errno != EINTR) {
perror("select");
CA_DisconnectedPeer();
errno = 0;
return;
}
errno = 0;
}
// socket read buffer has data waiting in it
if (ret) {
ret = recv(cloud.connection.socket, in->data + in->length, QUEUE_SIZE - 1, 0);
if (ret == 0) {
CA_DisconnectedPeer();
return;
}
if (ret == -1) {
if (errno != EINTR) {
perror("recv");
CA_DisconnectedPeer();
return;
}
errno = 0;
}
in->length += ret;
// decrypt if necessary
if (cloud.connection.encrypted && cloud.connection.have_keys && cloud.state == CA_STATE_TRUSTED) {
q2a_memcpy(temp_iv, in->data, AES_IV_LEN);
q2a_memset(&dec, 0, sizeof(message_queue_t));
dec.length = G_SymmetricDecrypt(dec.data, in->data, in->length);
q2a_memset(in->data, 0, in->length);
q2a_memcpy(in->data, dec.data, dec.length);
in->length = dec.length;
q2a_memcpy(cloud.connection.initial_value, temp_iv, AES_IV_LEN);
}
} else {
// no data has been sent to read
break;
}
}
CA_ParseMessage();
}
/**
* The server has let us know we are trusted.
*/
void CA_Trusted(void)
{
CA_dprintf("connection trusted\n");
cloud.state = CA_STATE_TRUSTED;
}
/**
* Parse a newly received message and act accordingly
*/
void CA_ParseMessage(void)
{
message_queue_t *msg = &cloud.queue_in;
byte cmd;
if (cloud.state == CA_STATE_DISABLED) {
return;
}
if (!cloud.queue_in.length) {
return;
}
while (msg->index < msg->length) {
cmd = CA_ReadByte();
switch (cmd) {
case SCMD_PONG:
CA_ParsePong();
break;
case SCMD_COMMAND:
CA_ParseCommand();
break;
case SCMD_HELLOACK:
CA_VerifyServerAuth();
break;
case SCMD_TRUSTED: // we just connected and authed successfully
CA_Trusted();
CA_Map(cloud.mapname);
CA_PlayerList();
break;
case SCMD_ERROR:
CA_ParseError();
break;
case SCMD_SAYCLIENT:
CA_SayClient();
break;
case SCMD_SAYALL:
CA_SayAll();
break;
case SCMD_KEY:
CA_RotateKeys();
break;
case SCMD_GETPLAYERS:
CA_PlayerList();
break;
}
}
// reset queue back to zero
q2a_memset(&cloud.queue_in, 0, sizeof(message_queue_t));
}
/**
* Is a a digital signature valid?
*/
qboolean RSAVerifySignature( RSA* rsa,
unsigned char* MsgHash,
size_t MsgHashLen,
const char* Msg,
size_t MsgLen,
qboolean* Authentic) {
*Authentic = qfalse;
EVP_PKEY* pubKey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pubKey, rsa);
EVP_MD_CTX* m_RSAVerifyCtx = EVP_MD_CTX_new();
if (EVP_DigestVerifyInit(m_RSAVerifyCtx,NULL, EVP_sha256(),NULL,pubKey)<=0) {
return qfalse;
}
if (EVP_DigestVerifyUpdate(m_RSAVerifyCtx, Msg, MsgLen) <= 0) {
return qfalse;
}
int AuthStatus = EVP_DigestVerifyFinal(m_RSAVerifyCtx, MsgHash, MsgHashLen);
if (AuthStatus == 1) {
*Authentic = qtrue;
EVP_MD_CTX_free(m_RSAVerifyCtx);
return qtrue;
} else if (AuthStatus == 0) {
*Authentic = qfalse;
EVP_MD_CTX_free(m_RSAVerifyCtx);
return qtrue;
} else {
*Authentic = qfalse;
EVP_MD_CTX_free(m_RSAVerifyCtx);
return qfalse;
}
}
/**
* Authenticate the backend
*
* 1. Decrypt the nonce sent back from the server and check if it matches
* 2. If the encryption is requested, parse the AES 128 key and IV
* 3. Read the plaintext nonce from the server, encrypt and send back
* to auth the client
*/
qboolean CA_VerifyServerAuth(void)
{
ca_connection_t *c = &cloud.connection;
size_t dec_len; // Length of decrypted cleartext
size_t enc_len; // Length of encrypted ciphertext
byte response[RSA_LEN]; // Ciphertext
byte response_plain[RSA_LEN]; // Cleartext version of response
byte challenge_hash[DIGEST_LEN]; // The hash we calculate
byte response_hash[DIGEST_LEN]; // Message digest of a challenge
byte sv_challenge[CHALLENGE_LEN]; // The nonce sent from the server
uint8_t offset = 0; // Used to find the parts of
// server's auth response
q2a_memset(response, 0, sizeof(response));
CA_ReadData(response, CA_ReadShort());
q2a_memset(response_plain, 0, sizeof(response_plain));
dec_len = G_PrivateDecrypt(response_plain, response, sizeof(response));
if (dec_len == 0) {
CA_dprintf("zero bytes decrypted for server authentication\n");
return qfalse;
}
// this is our original nonce hashed by the server and sent back to us
q2a_memset(response_hash, 0, sizeof(response_hash));
q2a_memcpy(response_hash, response_plain + offset, sizeof(response_hash));
offset += sizeof(response_hash);
// random nonce generated by server (we hash it and send back)
q2a_memset(sv_challenge, 0, sizeof(sv_challenge));
q2a_memcpy(sv_challenge, response_plain + offset, sizeof(sv_challenge));
offset += sizeof(sv_challenge);
// transit will be encrypted so the keys will be next in the buffer
if (cloud_encryption) {
q2a_memset(c->session_key, 0, sizeof(c->session_key));
q2a_memcpy(c->session_key, response_plain + offset, sizeof(c->session_key));
offset += sizeof(c->session_key);
q2a_memset(c->initial_value, 0, sizeof(c->initial_value));
q2a_memcpy(c->initial_value, response_plain + offset, sizeof(c->initial_value));
c->have_keys = qtrue;
// reuse encrypt/decrypt contexts
c->e_ctx = EVP_CIPHER_CTX_new();
c->d_ctx = EVP_CIPHER_CTX_new();
}
// to compare with what server sent back to us
G_MessageDigest(challenge_hash, c->cl_nonce, CHALLENGE_LEN);
// if the hashes match, server is authenticated
if (q2a_memcmp(challenge_hash, response_hash, DIGEST_LEN) == 0) {
CA_dprintf("server authenticated\n");
// reuse response and challenge_hash for our auth to server
q2a_memset(response, 0, sizeof(response));
q2a_memset(challenge_hash, 0, sizeof(challenge_hash));
G_MessageDigest(challenge_hash, sv_challenge, sizeof(sv_challenge));
enc_len = G_PublicEncrypt(cloud.connection.server_key, response, challenge_hash, DIGEST_LEN);
// send our response to server's challenge
CA_WriteByte(CMD_AUTH);
CA_WriteShort(enc_len);
CA_WriteData(response, enc_len);
CA_SendMessages();
cloud.connection_attempts = 0;
cloud.connection.auth_fail_count = 0;
return qtrue;
} else {
CA_dprintf("server auth error: %s\n", ERR_error_string(ERR_get_error(), NULL));
cloud.connection.auth_fail_count++;
if (cloud.connection.auth_fail_count > AUTH_FAIL_LIMIT) {
CA_dprintf("too many auth failures, giving up\n");
cloud.state = CA_STATE_DISABLED;
}
return qfalse;
}
}
/**
* Server sent over a command. It unconditionally executes any command the
* backend sends over. Generally this is a bad, but since we can't get here
* unless the connection is authenticated, it's probably safe enough. Maybe
* add some sanity checks later.
*/
void CA_ParseCommand(void)
{
char *cmd;
if (cloud.state < CA_STATE_TRUSTED) {
return;
}
cmd = CA_ReadString();
gi.AddCommandString(cmd);
}
/**
* Backend responded to our PING
*/
void CA_ParsePong(void)
{
cloud.ping.waiting = qfalse;
cloud.ping.miss_count = 0;
}
/**
* The server sent us new symmetric encryption keys, parse them and
* start using them
*/
void CA_RotateKeys(void)
{
ca_connection_t *c;
c = &cloud.connection;
CA_ReadData(c->session_key, AESKEY_LEN);
CA_ReadData(c->initial_value, AESBLOCK_LEN);
}
/**
* There was a sudden disconnection mid-stream. Reconnect after an appropriate
* delay.
*/
void CA_DisconnectedPeer(void)
{
uint8_t secs;
if (cloud.state < CA_STATE_CONNECTED) {
return;
}
CA_printf("connection lost\n");
cloud.state = CA_STATE_DISCONNECTED;
cloud.connection.trusted = qfalse;
cloud.connection.have_keys = qfalse;
cloud.disconnect_count++;
memset(&cloud.connection.session_key[0], 0, AESKEY_LEN);
memset(&cloud.connection.initial_value[0], 0, AESBLOCK_LEN);
// try reconnecting a reasonably random amount of time later
srand((unsigned) time(NULL));
secs = rand() & 0xff;
cloud.connect_retry_frame = FUTURE_CA_FRAME(10) + secs;
CA_dprintf("trying to reconnect in %d seconds\n",
FRAMES_TO_SECS(cloud.connect_retry_frame - cloud.frame_number)
);
}
/**
* Send info about all the players connected. First send the number of players
* to follow, then for each: the player id followed by the userinfo and finally
* the version string for the client the player is using.
*/
void CA_PlayerList(void)
{
uint8_t count, i;
count = 0;
if (cloud.state < CA_STATE_TRUSTED) {
return;
}
for (i=0; i<cloud.maxclients; i++) {
if (proxyinfo[i].inuse) {
count++;
}
}
CA_WriteByte(CMD_PLAYERLIST);
CA_WriteByte(count);
for (i=0; i<cloud.maxclients; i++) {
if (proxyinfo[i].inuse) {
CA_WriteByte(i);
CA_WriteString("%s", proxyinfo[i].userinfo);
CA_WriteString("%s", proxyinfo[i].client_version);
}
}
}
/**
* Immediately after connecting, we have to say hi, giving the server our
* information. Once the server acknowledges we can start sending game data.
*
* The last section of data is a random nonce. The server will encrypt this
* and send it back to us. We then decrypt and check if it matches, if so,
* the server is who we think it is and is considered trusted.
*/
void CA_SayHello(void)
{
if (cloud.state == CA_STATE_TRUSTED) {
return;
}
// random data to challenge backend with
RAND_bytes(cloud.connection.cl_nonce, sizeof(cloud.connection.cl_nonce));
byte challenge[RSA_LEN];
q2a_memset(challenge, 0, sizeof(challenge));
G_PublicEncrypt(cloud.connection.server_key, challenge,
cloud.connection.cl_nonce, CHALLENGE_LEN);
CA_WriteLong(MAGIC_CLIENT);
CA_WriteByte(CMD_HELLO);
CA_WriteString(cloud_uuid);
CA_WriteLong(Q2A_REVISION);
CA_WriteShort(cloud.port);
CA_WriteByte(cloud.maxclients);
CA_WriteByte(cloud_encryption ? 1 : 0);
CA_WriteData(challenge, RSA_LEN);
}
/**
* The server replied negatively to something
*/
void CA_ParseError(void)
{
uint8_t client_id, reason_id;
char *reason;
gi.dprintf("parsing error\n");
client_id = CA_ReadByte(); // will be -1 if not player specific
reason_id = CA_ReadByte();
reason = CA_ReadString();
// Where to output the error msg
if (client_id == -1) {
gi.cprintf(NULL, PRINT_HIGH, "%s\n", reason);
} else {
gi.cprintf(NULL, PRINT_HIGH, "error msg here\n");
}
// serious enough to disconnect
if (reason_id >= 200) {
closesocket(cloud.connection.socket);
cloud.state = CA_STATE_DISABLED;
freeaddrinfo(cloud.addr);
}
}
/**
* q2pro uses "net_port" while most other servers use "port". This
* returns the value regardless.
*/
uint16_t getport(void) {
static cvar_t *port;
port = gi.cvar("port", "0", 0);
if ((int) port->value) {
return (int) port->value;
}
port = gi.cvar("net_port", "0", 0);
if ((int) port->value) {
return (int) port->value;
}
// fallback to default
port = gi.cvar("port", "27910", 0);
return (int) port->value;
}
/**
* Reset the outgoing message buffer to zero to start a new msg
*/
void CA_InitBuffer() {
q2a_memset(&cloud.queue, 0, sizeof(message_queue_t));
}
/**
* Read a single byte from the message buffer
*/
uint8_t CA_ReadByte(void)
{
unsigned char b = cloud.queue_in.data[cloud.queue_in.index++];
return b & 0xff;
}
/**
* Write a single byte to the message buffer
*/
void CA_WriteByte(uint8_t b)
{
cloud.queue.data[cloud.queue.length++] = b & 0xff;
}
/**
* Read a short (2 bytes) from the message buffer
*/
uint16_t CA_ReadShort(void)