-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
1021 lines (819 loc) · 31.3 KB
/
Copy pathserver.cpp
File metadata and controls
1021 lines (819 loc) · 31.3 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
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <Aclapi.h>
#include <Sddl.h>
#include <Mswsock.h>
#define PORT (555)
#define MAX_CLIENTS (100)
void ServClient(DWORD idx);
#pragma comment (lib, "ws2_32.lib")
#pragma comment (lib, "mswsock.lib")
#pragma warning(disable : 4996)
int count_client = 0;
struct client_ctx
{
int socket;
/*unsigned*/ char buf_recv[1024]; // Áóôåð ïðèåìà
unsigned int sz_recv; // Ïðèíÿòî äàííûõ
/*unsigned*/ char buf_send[1024]; // Áóôåð îòïðàâêè
unsigned int sz_send_total; // Äàííûõ â áóôåðå îòïðàâêè
unsigned int sz_send; // Äàííûõ îòïðàâëåíî
HCRYPTKEY hSessionKey;
// Ñòðóêòóðû OVERLAPPED äëÿ óâåäîìëåíèé î çàâåðøåíèè
OVERLAPPED overlap_recv;
OVERLAPPED overlap_send;
OVERLAPPED overlap_cancel;
DWORD flags_recv; // Ôëàãè äëÿ WSARecv
};
// Ïðîñëóøèâàþùèé ñîêåò è âñå ñîêåòû ïîäêëþ÷åíèÿ õðàíÿòñÿ
// â ìàññèâå ñòðóêòóð (âìåñòå ñ overlapped è áóôåðàìè)
struct client_ctx g_ctxs[1 + MAX_CLIENTS];
int g_accepted_socket;
HANDLE g_io_port;
// Ôóíêöèÿ ñòàðòóåò îïåðàöèþ ÷òåíèÿ èç ñîêåòà
void schedule_read(DWORD idx)
{
WSABUF buf;
buf.buf = g_ctxs[idx].buf_recv + g_ctxs[idx].sz_recv;
buf.len = sizeof(g_ctxs[idx].buf_recv) - g_ctxs[idx].sz_recv;
memset(&g_ctxs[idx].overlap_recv, 0, sizeof(OVERLAPPED));
g_ctxs[idx].flags_recv = 0;
WSARecv(g_ctxs[idx].socket, &buf, 1, NULL, &g_ctxs[idx].flags_recv,
&g_ctxs[idx].overlap_recv, NULL);
}
void schedule_write(DWORD idx)
{
WSABUF buf;
buf.buf = g_ctxs[idx].buf_send + g_ctxs[idx].sz_send;
buf.len = g_ctxs[idx].sz_send_total - g_ctxs[idx].sz_send;
memset(&g_ctxs[idx].overlap_send, 0, sizeof(OVERLAPPED));
WSASend(g_ctxs[idx].socket, &buf, 1, NULL, 0, &g_ctxs[idx].overlap_send, NULL);
}
void help_for_write(DWORD idx, char * buf, int size)
{
memcpy(g_ctxs[idx].buf_send, buf, size);
g_ctxs[idx].sz_send_total = size;
g_ctxs[idx].sz_send = 0;
schedule_write(idx);
}
// Ôóíêöèÿ äîáàâëÿåò íîâîå ïðèíÿòîå ïîäêëþ÷åíèå êëèåíòà
void add_accepted_connection()
{
DWORD i;
// Ïîèñê ìåñòà â ìàññèâå g_ctxs äëÿ âñòàâêè íîâîãî ïîäêëþ÷åíèÿ
for (i = 0; i < sizeof(g_ctxs) / sizeof(g_ctxs[0]); i++)
{
if (g_ctxs[i].socket == 0)
{
unsigned int ip = 0;
struct sockaddr_in* local_addr = 0, *remote_addr = 0;
int local_addr_sz, remote_addr_sz;
GetAcceptExSockaddrs(g_ctxs[0].buf_recv, g_ctxs[0].sz_recv,
sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
(struct sockaddr **) &local_addr, &local_addr_sz, (struct sockaddr **)
&remote_addr, &remote_addr_sz);
if (remote_addr)
ip = ntohl(remote_addr->sin_addr.s_addr);
printf(" connection %u created, remote IP: %u.%u.%u.%u\n",
i, (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, (ip)& 0xff
);
g_ctxs[i].socket = g_accepted_socket;
// Bind socket with IOCP port. We use array index as the key.
if (NULL == CreateIoCompletionPort((HANDLE)g_ctxs[i].socket, g_io_port, i,
0))
{
printf("CreateIoCompletionPort error: %x\n", GetLastError());
return;
}
HCRYPTPROV hProv;
HCRYPTKEY hKey;
HCRYPTKEY hPubKey;
HCRYPTKEY hPrivKey;
HCRYPTKEY hSessionKey;
/*
MS_ENHANCED_PROV:
The Microsoft Enhanced Cryptographic Provider,
called the Enhanced Provider,
supports the same capabilities as the Microsoft Base Cryptographic Provider,
called the Base Provider. The Enhanced Provider supports stronger security
through longer keys and additional algorithms.
It can be used with all versions of CryptoAPI.
PROV_RSA_FULL:
The PROV_RSA_FULL provider type supports both digital signatures and data encryption.
It is considered a general purpose CSP.
The RSA public key algorithm is used for all public key operations.
*/
if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0))
{
printf("Can't create a context\n");
}
if (!CryptGenKey(hProv, AT_KEYEXCHANGE, 1024 << 16, &hKey)) // generate 1024-bit key
{
printf("Can't to create a RSA key for exchange\n");
//success = FALSE;
}
else
{
printf("RSA key successfully created\n");
}
if (!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hPubKey)) // get public user key
{
printf("Can't get the public key from container\n");
CryptReleaseContext(hProv, 0);
}
DWORD pubLen = 0;
//export public key
//get array len for export key, len in publen
if (!CryptExportKey(hPubKey, 0, PUBLICKEYBLOB, 0, NULL, &pubLen))
std::cout << "CryptExportKey error\n" << std::endl;
// Init the array used for export the key.
//BYTE * pubdata = static_cast<BYTE*>(malloc(pubLen));
BYTE * pubdata = (BYTE*)(malloc(pubLen));
ZeroMemory(pubdata, pubLen);
char sessdata[1024];
char size[1024];
char buf[1024];
int len;
// Export the decryption key.
if (!CryptExportKey(hPubKey, 0, PUBLICKEYBLOB, 0, (BYTE*)pubdata, &pubLen)) // The data consist our key.
{
std::cout << "CryptExportKey error\n" << std::endl;
}
else
{
std::cout << "The public key successfully exported\n" << std::endl;
}
itoa((int)pubLen, size, 10);
memcpy(g_ctxs[i].buf_send, (char*)size, sizeof(size));
g_ctxs[i].sz_send_total = sizeof(size);
g_ctxs[i].sz_send = 0;
//Send the length of the key.
schedule_write(i);
memcpy(g_ctxs[i].buf_send, (char*)pubdata, pubLen);
g_ctxs[i].sz_send_total = pubLen;
g_ctxs[i].sz_send = 0;
//Send the public key to the client.
schedule_write(i);
Sleep(1000);
//Get the session key from client.
schedule_read(i);
//sprintf(buf, "%s", g_ctxs[i].buf_recv);
memcpy(buf, g_ctxs[i].buf_recv, sizeof(g_ctxs[i].buf_recv));
//recv(my_sock, (char *)&buf, sizeof(buf), 0);
len = atoi(buf);
//Get encrypted session key.
schedule_read(i);
memcpy(sessdata, g_ctxs[i].buf_recv, sizeof(g_ctxs[i].buf_recv));
//sprintf(sessdata, "%s", g_ctxs[i].buf_recv);
//recv(my_sock, (char *)&sessdata, len, 0);
if (!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hPrivKey)) //Get the private user key.
{
std::cout << "Can't get the private key from container\n" << std::endl;
CryptReleaseContext(hProv, 0);
}
if (!CryptImportKey(hProv, (BYTE*)sessdata, len, hPrivKey, 0, &hSessionKey)) //Decrypted the session key.
{
std::cout << "CryptImportKey error" << std::endl;
}
else
{
//memcpy((HCRYPTKEY*)g_ctxs[i].hSessionKey, (HCRYPTKEY*)hSessionKey, sizeof(hSessionKey));
g_ctxs[i].hSessionKey = hSessionKey;
std::cout << "Session key was successfully importes" << std::endl;
}
//Waiting the data from socket.
schedule_read(i);
return;
}
}
//The server doesnt fount any connection for client. Couldnt accept.
closesocket(g_accepted_socket);
g_accepted_socket = 0;
}
//The function started the acception connection.
void schedule_accept()
{
// Ñîçäàíèå ñîêåòà äëÿ ïðèíÿòèÿ ïîäêëþ÷åíèÿ (AcceptEx íå ñîçäàåò ñîêåòîâ)
g_accepted_socket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
memset(&g_ctxs[0].overlap_recv, 0, sizeof(OVERLAPPED));
// Ïðèíÿòèå ïîäêëþ÷åíèÿ.
// Êàê òîëüêî îïåðàöèÿ áóäåò çàâåðøåíà - ïîðò çàâåðøåíèÿ ïðèøëåò óâåäîìëåíèå.
// Ðàçìåðû áóôåðîâ äîëæíû áûòü íà 16 áàéò áîëüøå ðàçìåðà àäðåñà ñîãëàñíî äîêóìåíòàöèè ðàçðàáîò÷èêà ÎÑ
AcceptEx(g_ctxs[0].socket, g_accepted_socket, g_ctxs[0].buf_recv, 0,
sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16, NULL,
&g_ctxs[0].overlap_recv);
}
int init()
{
#ifdef _WIN32
// Äëÿ Windows ñëåäóåò âûçâàòü WSAStartup ïåðåä íà÷àëîì èñïîëüçîâàíèÿ ñîêåòîâ
WSADATA wsa_data;
return (0 == WSAStartup(MAKEWORD(2, 2), &wsa_data));
#endif
}
void deinit()
{
#ifdef _WIN32
// Äëÿ Windows ñëåäóåò âûçâàòü WSACleanup â êîíöå ðàáîòû
WSACleanup();
#endif
}
int sock_err(const char* function, int s)
{
int err;
#ifdef _WIN32
err = WSAGetLastError();
#endif
fprintf(stderr, "%s: socket error: %d\n", function, err);
return -1;
}
void s_close(int s)
{
#ifdef _WIN32
closesocket(s);
#endif
}
void GetOSVersion(char * ver)
{
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
if (bOsVersionInfoEx)
{
if (osvi.dwMajorVersion == 5)
{
if (osvi.dwMinorVersion == 0)
strcpy(ver, "Microsoft Windows 2000 ");
if (osvi.dwMinorVersion == 1)
strcpy(ver, "Microsoft Windows XP");
if (osvi.dwMinorVersion == 2 && osvi.wProductType == VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows XP Professional x64 Edition ");
if (osvi.dwMinorVersion == 2 && GetSystemMetrics(SM_SERVERR2) != 0)
strcpy(ver, "Microsoft Server 2003 R2");
if (osvi.dwMinorVersion == 2 && GetSystemMetrics(SM_SERVERR2) == 0)
strcpy(ver, "Microsoft Server 2003 ");
if (osvi.dwMinorVersion == 2 && osvi.wSuiteMask & VER_SUITE_WH_SERVER)
strcpy(ver, "Microsoft Windows Home Server");
}
else if (osvi.dwMajorVersion == 6)
{
if (osvi.dwMinorVersion == 0 && osvi.wProductType == VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows Vista");
if (osvi.dwMinorVersion == 0 && osvi.wProductType != VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows Server 2008 ");
if (osvi.dwMinorVersion == 1 && osvi.wProductType != VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows Server 2008 R2 ");
if (osvi.dwMinorVersion == 1 && osvi.wProductType == VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows 7 ");
if (osvi.dwMinorVersion == 2 && osvi.wProductType != VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows Server 2012 ");
if (osvi.dwMinorVersion == 2 && osvi.wProductType == VER_NT_WORKSTATION)
strcpy(ver, "Microsoft Windows 8 ");
if (osvi.dwMinorVersion == 3 && osvi.wProductType != VER_NT_WORKSTATION)
strcpy(ver, "Windows Server 2012 R2 ");
if (osvi.dwMinorVersion == 3 && osvi.wProductType == VER_NT_WORKSTATION)
strcpy(ver, "Windows Server 8.1 ");
}
else if (osvi.dwMajorVersion == 10)
{
if (osvi.dwMinorVersion == 0)
strcpy(ver, "Microsoft Windows 10 ");
}
if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
strcat(ver, " Home Edition ");
else
strcat(ver, " Professional ");
}
}
void io_serv()
{
init();
struct sockaddr_in addr;
// Ñîçäàíèå ñîêåòà ïðîñëóøèâàíèÿ
SOCKET s = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
// Ñîçäàíèå ïîðòà çàâåðøåíèÿ
g_io_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
if (NULL == g_io_port)
{
printf("CreateIoCompletionPort error: %x\n", GetLastError());
return;
}
// Îáíóëåíèå ñòðóêòóðû äàííûõ äëÿ õðàíåíèÿ âõîäÿùèõ ñîåäèíåíèé
memset(g_ctxs, 0, sizeof(g_ctxs));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
if (bind(s, (struct sockaddr*) &addr, sizeof(addr)) < 0 || listen(s, 1) < 0)
{
printf("error bind() or listen()\n");
return;
}
printf("Listening: %hu\n", ntohs(addr.sin_port));
// Ïðèñîåäèíåíèå ñóùåñòâóþùåãî ñîêåòà s ê ïîðòó io_port.
//  êà÷åñòâå êëþ÷à äëÿ ïðîñëóøèâàþùåãî ñîêåòà èñïîëüçóåòñÿ 0
if (NULL == CreateIoCompletionPort((HANDLE)s, g_io_port, 0, 0))
{
printf("CreateIoCompletionPort error: %x\n", GetLastError());
return;
}
g_ctxs[0].socket = s;
// Ñòàðò îïåðàöèè ïðèíÿòèÿ ïîäêëþ÷åíèÿ.
schedule_accept();
// Áåñêîíå÷íûé öèêë ïðèíÿòèÿ ñîáûòèé î çàâåðøåííûõ îïåðàöèÿõ
while (1)
{
DWORD transferred;
ULONG_PTR key;
OVERLAPPED* lp_overlap;
// Îæèäàíèå ñîáûòèé â òå÷åíèå 1 ñåêóíäû
BOOL b = GetQueuedCompletionStatus(g_io_port, &transferred, &key, &lp_overlap,
INFINITE);
if (b)
{
// Ïîñòóïèëî óâåäîìëåíèå î çàâåðøåíèè îïåðàöèè
if (key == 0) // êëþ÷ 0 - äëÿ ïðîñëóøèâàþùåãî ñîêåòà
{
g_ctxs[0].sz_recv += transferred;
// Ïðèíÿòèå ïîäêëþ÷åíèÿ è íà÷àëî ïðèíÿòèÿ ñëåäóþùåãî
add_accepted_connection();
schedule_accept();
}
else
{
// Èíà÷å ïîñòóïèëî ñîáûòèå ïî çàâåðøåíèþ îïåðàöèè îò êëèåíòà.
// Êëþ÷ key - èíäåêñ â ìàññèâå g_ctxs
if (&g_ctxs[key].overlap_recv == lp_overlap)
{
int len;
char buffer;
buffer = g_ctxs[key].buf_recv[0];
if (buffer == '1')
{
printf("Type and version of OS...\n");
char version[1024];
GetOSVersion(version);
DWORD count = strlen(version) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)version, &count, count))
{
printf("Encrypt: ERROR!\n");
}
help_for_write(key, version, count);
//send(g_ctxs[key].socket, version, count, 0);
//schedule_write(key);
buffer = '0';
//g_ctxs[key].buf_recv[0] = '\0';
schedule_read(key);
}
else if (buffer == '2')
{
printf("Current OS time...\n");
time_t t;
struct tm * local_t;
char clock[256];
t = time(0);
local_t = localtime(&t);
strftime(clock, 256, "%d:%m:%Y %H:%M:%S\n", local_t);
DWORD count = strlen(clock) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)clock, &count, count))
{
printf("Encrypt: ERROR!\n");
}
//send(my_sock, clock, count, 0);
//send(g_ctxs[key].socket, clock, count, 0);
//schedule_write(key);
help_for_write(key, clock, count);
buffer = '0';
schedule_read(key);
}
else if (buffer == '3')
{
printf("Time since OS started...\n");
char time[256];
DWORD t = GetTickCount();
_itoa(int(t), time, 10);
DWORD count = strlen(time) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)time, &count, count))
{
printf("Encrypt: ERROR!\n");
}
//send(g_ctxs[key].socket, time, count, 0);
help_for_write(key, time, count);
buffer = '0';
schedule_read(key);
}
else if (buffer == '4')
{
/// https://msdn.microsoft.com/ru-ru/library/windows/desktop/aa366589(v=vs.85).aspx
printf("Information about using memory...\n");
char out_buf[8192];
ZeroMemory(&out_buf, sizeof(out_buf));
MEMORYSTATUSEX statex;
char answer[1024];
//GlobalMemoryStatusEx(&statex);
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
_itoa((int)statex.dwMemoryLoad, answer, 10);
strcat(out_buf, "Percent of memory in use: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullTotalPhys / (1024 * 1024), answer, 10);
strcat(out_buf, "Total MB of physical memory: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullAvailPhys / (1024 * 1024), answer, 10);
strcat(out_buf, "Free MB of physical memory: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullTotalPageFile / (1024 * 1024), answer, 10);
strcat(out_buf, "Total MB of paging file: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullAvailPageFile / (1024 * 1024), answer, 10);
strcat(out_buf, "Free MB of paging file: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullTotalVirtual / (1024 * 1024), answer, 10);
_i64toa(statex.ullAvailPageFile / (1024 * 1024), answer, 10);
strcat(out_buf, "Total MB of virtual memory: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
_i64toa(statex.ullAvailVirtual / (1024 * 1024), answer, 10);
strcat(out_buf, "Free MB of virtual memory: ");
strcat(out_buf, answer);
strcat(out_buf, "\n");
ZeroMemory(&answer, sizeof(answer));
DWORD count = strlen(out_buf) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)out_buf, &count, count))
{
printf("Encrypt: ERROR!\n");
}
//send(g_ctxs[key].socket, out_buf, count, 0);
help_for_write(key, out_buf, count);
buffer = '0';
schedule_read(key);
}
else if (buffer == '5')
{
printf("Free space in local disks...\n");
char temp[1024];
char answer5[1024] = "";
char *name_disk[] = { "C:", "D:", "E:", "F:", "G:", "H:", "I:", "J:", "K:", "L:",
"M:", "N:", "O:", "P:", "Q:", "R:", "S:", "T:", "U:", " V:",
"W:", "X:", "Y:", "Z:" };
_int64 TotalNumberOfFreeBytes;
strcpy(answer5, "Disks:\n");
int flag;
for (int i = 0; i < 24; i++)
{
wchar_t* wString = new wchar_t[4096];
MultiByteToWideChar(CP_ACP, 0, name_disk[i], -1, wString, 4096);
flag = GetDriveType(wString);
if (flag == 3)
{
strcat(answer5, name_disk[i]);
strcat(answer5, " - FIXED\n");
TotalNumberOfFreeBytes = 0;
GetDiskFreeSpaceEx(wString,
(PULARGE_INTEGER)&TotalNumberOfFreeBytes, NULL, NULL);
_itoa(TotalNumberOfFreeBytes / 1024 / 1024 / 1024, temp, 10);
strcat(answer5, "Free ");
strcat(answer5, temp);
strcat(answer5, " Gb\n");
}
else if (flag == 2)
{
strcat(answer5, name_disk[i]);
strcat(answer5, " - REMOVABLE\n");
TotalNumberOfFreeBytes = 0;
GetDiskFreeSpaceEx(wString,
(PULARGE_INTEGER)&TotalNumberOfFreeBytes, NULL, NULL);
_itoa(TotalNumberOfFreeBytes / 1024 / 1024 / 1024, temp, 10);
strcat(answer5, "Free ");
strcat(answer5, temp);
strcat(answer5, " Gb\n");
}
else if (flag == 4)
{
strcat(answer5, name_disk[i]);
strcat(answer5, " - REMOTE\n");
TotalNumberOfFreeBytes = 0;
GetDiskFreeSpaceEx(wString,
(PULARGE_INTEGER)&TotalNumberOfFreeBytes, NULL, NULL);
_itoa(TotalNumberOfFreeBytes / 1024 / 1024 / 1024, temp, 10);
strcat(answer5, "Free ");
strcat(answer5, temp);
strcat(answer5, " Gb\n");
}
else if (flag == 6)
{
strcat(answer5, name_disk[i]);
strcat(answer5, " - RAMDISK\n");
TotalNumberOfFreeBytes = 0;
GetDiskFreeSpaceEx(wString,
(PULARGE_INTEGER)&TotalNumberOfFreeBytes, NULL, NULL);
_itoa(TotalNumberOfFreeBytes / 1024 / 1024 / 1024, temp, 10);
strcat(answer5, "Free ");
strcat(answer5, temp);
strcat(answer5, " Gb\n");
}
else if (flag == 5)
{
strcat(answer5, name_disk[i]);
strcat(answer5, " - CDROM\n");
TotalNumberOfFreeBytes = 0;
GetDiskFreeSpaceEx(wString,
(PULARGE_INTEGER)&TotalNumberOfFreeBytes, NULL, NULL);
_itoa(TotalNumberOfFreeBytes / 1024 / 1024 / 1024, temp, 10);
strcat(answer5, "Free ");
strcat(answer5, temp);
strcat(answer5, " Gb\n");
}
}
DWORD count = strlen(answer5) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)answer5, &count, count))
{
printf("Encrypt: ERROR!\n");
}
//send(g_ctxs[key].socket, answer5, count, 0);
help_for_write(key, answer5, count);
ZeroMemory(&answer5, sizeof(answer5));
buffer = '0';
schedule_read(key);
}
else if (buffer == '6')
{
printf("Get Access rights...\n");
char domain[256];
char user[256];
ACL_SIZE_INFORMATION acl_size;
ACCESS_ALLOWED_ACE * pACE;
PACL dacl;
PSID pOwnerSID;
char type;
char buf;
char path[128] = { 0 };
char out_buf[8192];
ZeroMemory(&out_buf, sizeof(out_buf));
LPSTR SID_string;
if (recv(g_ctxs[key].socket, &buf, sizeof(buf), 0) == 0) // f d k receive
{
strcat(out_buf, "GET_TYPE_OBJECT: ERROR!\n");
printf("GET_TYPE_OBJECT: ERROR!\n");
}
else
{
if (buf == 'f') type = SE_FILE_OBJECT;
if (buf == 'd') type = SE_FILE_OBJECT;
if (buf == 'k') type = SE_REGISTRY_KEY;
}
if (recv(g_ctxs[key].socket, (char *)&path, sizeof(path), 0) == 0) //Get path
{
strcat(out_buf, "GET_PATH_OBJECT: ERROR!\n");
printf("GET_PATH_OBJECT: ERROR!\n");
}
if (GetNamedSecurityInfoA(path, (SE_OBJECT_TYPE)type, DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, NULL, &pOwnerSID) != ERROR_SUCCESS) {
strcat(out_buf, "ACCESS ERROR!\n");
printf("ACCESS ERROR!\n");
}
else
{
memset(out_buf, 0, 8192);
GetAclInformation(dacl, &acl_size, sizeof(acl_size), AclSizeInformation);
for (int i = 0; i < acl_size.AceCount; i++)
{
memset(domain, 0, 256);
memset(user, 0, 256);
DWORD userlen = sizeof(user);
DWORD domlen = sizeof(domain);
SID_NAME_USE sid_name;
PSID pSID;
LPSTR strSid = 0;
GetAce(dacl, i, (PVOID *)&pACE);
pSID = (PSID)(&(pACE->SidStart));
SECURITY_INFORMATION si = GROUP_SECURITY_INFORMATION &
LABEL_SECURITY_INFORMATION &
DACL_SECURITY_INFORMATION &
LABEL_SECURITY_INFORMATION &
OWNER_SECURITY_INFORMATION;
if (LookupAccountSidA(NULL, pSID, user, &userlen, domain, &domlen, &sid_name))
{
strcat(out_buf, "\nAccount: ");
strcat(out_buf, domain);
strcat(out_buf, "\\");
strcat(out_buf, user);
strcat(out_buf, " \n");
strcat(out_buf, "Account's SID: ");
ConvertSidToStringSidA(pSID, &SID_string);
strcat(out_buf, SID_string);
strcat(out_buf, " \n");
strcat(out_buf, "ACE type: ");
switch (pACE->Header.AceType)
{
case ACCESS_DENIED_ACE_TYPE:
strcat(out_buf, "ACCESS: Denied\n");
break;
case ACCESS_ALLOWED_ACE_TYPE:
strcat(out_buf, "ACCESS: Allowed\n");
break;
default:
strcat(out_buf, "Audit\n");
}
/*strcat(out_buf, "Access mask: ");
for (j = 0; j < 32; j++)
out_buf[strlen(out_buf)] = '0' + pACE->Mask / (1 << (31 - j)) % 2;*/
strcat(out_buf, "Generic rights: \n");
// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/access-mask
//generic rights
//You can also specify the folowing generic access rights. these also apply to all types of executive objects.
if ((pACE->Mask & 1)) { strcat(out_buf, "GENERIC_READ\n"); } //the caller can perform normal read operations on the object
if ((pACE->Mask & 2)) { strcat(out_buf, "GENERIC_WRITE\n"); } //the caller can perform normal write operations on the object
if ((pACE->Mask & 4)) { strcat(out_buf, "GENERIC_EXECUTE\n"); } //the caller can execute the object
//standart rights
strcat(out_buf, "Standard rights: \n");
if ((pACE->Mask & SYNCHRONIZE)) { strcat(out_buf, "SYNCHRONIZE\n"); } //the caller can perform a wait operation on the object
if ((pACE->Mask & WRITE_OWNER)) { strcat(out_buf, "WRITE_OWNER\n"); } //the caller can change the ownership information for the file
if ((pACE->Mask & WRITE_DAC)) { strcat(out_buf, "WRITE_DAC\n"); } //the caller can change the DACL
if ((pACE->Mask & READ_CONTROL)) { strcat(out_buf, "READ_CONTROL\n"); } //caller can read the ACL
if ((pACE->Mask & DELETE)) { strcat(out_buf, "DELETE\n"); } //the caller can delete the object
if (type == SE_FILE_OBJECT)
{
if (buf == 'f')
{
strcat(out_buf, "Specific rights for file:\n");
if ((pACE->Mask & FILE_READ_DATA)) { strcat(out_buf, "FILE_READ_DATA\n"); }
if ((pACE->Mask & FILE_WRITE_DATA)) { strcat(out_buf, "FILE_WRITE_DATA\n"); }
if ((pACE->Mask & FILE_APPEND_DATA)) { strcat(out_buf, "FILE_APPEND_DATA\n"); }
if ((pACE->Mask & FILE_READ_EA)) { strcat(out_buf, "FILE_READ_EA\n"); }
if ((pACE->Mask & FILE_WRITE_EA)) { strcat(out_buf, "FILE_WRITE_EA\n"); }
if ((pACE->Mask & FILE_EXECUTE)) { strcat(out_buf, "FILE_EXECUTE\n"); }
if ((pACE->Mask & FILE_READ_ATTRIBUTES)) { strcat(out_buf, "FILE_READ_ATTRIBUTES\n"); }
if ((pACE->Mask & FILE_WRITE_ATTRIBUTES)) { strcat(out_buf, "FILE_WRITE_ATTRIBUTES\n"); }
}
if (buf == 'd')
{
strcat(out_buf, "Specific rights for directory:\n");
if ((pACE->Mask & FILE_LIST_DIRECTORY)) { strcat(out_buf, "FILE_LIST_DIRECTORY\n"); }
if ((pACE->Mask & FILE_ADD_FILE)) { strcat(out_buf, "FILE_ADD_FILE\n"); }
if ((pACE->Mask & FILE_ADD_SUBDIRECTORY)) { strcat(out_buf, "FILE_ADD_SUBDIRECTORY\n"); }
if ((pACE->Mask & FILE_READ_EA)) { strcat(out_buf, "FILE_READ_EA\n"); }
if ((pACE->Mask & FILE_WRITE_EA)) { strcat(out_buf, "FILE_WRITE_EA\n"); }
if ((pACE->Mask & FILE_TRAVERSE)) { strcat(out_buf, "FILE_TRAVERSE\n"); }
if ((pACE->Mask & FILE_DELETE_CHILD)) { strcat(out_buf, "FILE_DELETE_CHILD\n"); }
if ((pACE->Mask & FILE_READ_ATTRIBUTES)) { strcat(out_buf, "FILE_READ_ATTRIBUTES\n"); }
if ((pACE->Mask & FILE_WRITE_ATTRIBUTES)) { strcat(out_buf, "FILE_WRITE_ATTRIBUTES\n"); }
}
}
// https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms724878(v=vs.85).aspx
if (type == SE_REGISTRY_KEY)
{
strcat(out_buf, "Registry key rights:\n ");
if ((pACE->Mask & KEY_CREATE_SUB_KEY)) // Required to create a subkey of a registry key.
{
strcat(out_buf, "KEY_CREATE_SUB_KEY\n ");
}
if (pACE->Mask & KEY_ENUMERATE_SUB_KEYS) //Required to enumerate the subkeys of a registry key.
{
strcat(out_buf, "KEY_ENUMERATE_SUB_KEYS\n ");
}
if (pACE->Mask & KEY_NOTIFY) //Required to request change notifications for a registry key or for subkeys of a registry key.
{
strcat(out_buf, "KEY_NOTIFY\n ");
}
if (pACE->Mask & KEY_QUERY_VALUE) //Required to query the values of a registry key.
{
strcat(out_buf, "KEY_QUERY_VALUE\n ");
}
if (pACE->Mask & KEY_SET_VALUE) //Required to create, delete, or set a registry value.
{
strcat(out_buf, "KEY_SET_VALUE\n ");
}
}
}
}
}
DWORD count = strlen(out_buf) + 1;
if (!CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)out_buf, &count, count))
{
printf("Encrypt: ERROR!\n");
}
//send(g_ctxs[key].socket, out_buf, count, 0);
help_for_write(key, out_buf, count);
buffer = '0';
count = 0;
schedule_read(key);
}
else if (buffer == '7')
{
printf("Get file owner...\n");
char stack[1024];
ZeroMemory(&stack, sizeof(stack));
DWORD dwRes = 0;
PSID pOwnerSID;
char path[128] = { 0 };
char buf = { 0 };
char sid[1024] = { 0 };
PSECURITY_DESCRIPTOR pSecDescr;
recv(g_ctxs[key].socket, &buf, sizeof(buf), 0);
recv(g_ctxs[key].socket, (char *)&path, sizeof(path), 0);
//wchar_t* wString = new wchar_t[4096];
//MultiByteToWideChar(CP_ACP, 0, path, -1, wString, 4096);
if (buf == 'f')
{// ïî ïóòè ê ïàïêå èëè ôàéëó èçâêëåêàåì åãî SID
dwRes = GetNamedSecurityInfoA(path, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION, &pOwnerSID, NULL, NULL, NULL, &pSecDescr);
}
else
{
dwRes = GetNamedSecurityInfoA(path, SE_REGISTRY_KEY,
OWNER_SECURITY_INFORMATION, &pOwnerSID, NULL, NULL, NULL, &pSecDescr);
}
//HANDLE hFile = CreateFileA(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (dwRes != ERROR_SUCCESS)
{
printf("Can't to take owner's SID %i\n", GetLastError());//error
LocalFree(pSecDescr);
}
char szOwnerName[256] = { 0 };
char szDomainName[256] = { 0 };
DWORD dwUserNameLength = sizeof(szOwnerName);
DWORD dwDomainNameLength = sizeof(szDomainName);
SID_NAME_USE sidUse;
/*Ôóíêöèÿ LookupAccountSid ïðèíèìàåò èäåíòèôèêàòîð áåçîïàñíîñòè (SID) â êà÷åñòâå âõîäíûõ äàííûõ. Îí èçâëåêàåò èìÿ ó÷åòíîé çàïèñè äëÿ ýòîãî SID è èìÿ ïåðâîãî äîìåíà, íà êîòîðîì ýòîò èäåíòèôèêàòîð íàéäåí.*/
dwRes = LookupAccountSidA(NULL, pOwnerSID, szOwnerName, &dwUserNameLength,
szDomainName, &dwDomainNameLength, &sidUse);
if (dwRes == 0)
{
printf("ERROR!\n");
//error
}
else
{
//printf("Owner name = %s\t Domain = %s\n", szOwnerName, szDomainName);
strcat(stack, "Owner name: ");
strcat(stack, szOwnerName);
strcat(stack, "\n");
strcat(stack, "Domain: ");
strcat(stack, szDomainName);
strcat(stack, "\n");
LPWSTR SID = NULL;
char name[1024];
ZeroMemory(&name, sizeof(name));
BOOL flag = ConvertSidToStringSid(pOwnerSID, &SID);
WideCharToMultiByte(CP_ACP, 0, SID, -1, name, sizeof(name), 0, 0);
strcpy(sid, name);
strcat(stack, "SID: ");
strcat(stack, sid);
strcat(stack, "\n");
DWORD count = strlen(stack) + 1;
CryptEncrypt(g_ctxs[key].hSessionKey, 0, true, 0, (BYTE *)stack, &count, count);
//send(g_ctxs[key].socket, stack, count, 0); // HKEY_CURRENT_USER\Control Panel\Colors
help_for_write(key, stack, count);
}
buffer = '0';
schedule_read(key);
}
else if (buffer == '8')
{
printf("Client close the connection\n");
//closesocket(my_sock);
// Äàííûå îòïðàâëåíû ïîëíîñòüþ, ïðåðâàòü âñå îììóíèêàöèè,
// äîáàâèòü â ïîðò ñîáûòèå íà çàâåðøåíèå ðàáîòû
CancelIo((HANDLE)g_ctxs[key].socket);
PostQueuedCompletionStatus(g_io_port, 0, key,
&g_ctxs[key].overlap_cancel);
//printf("Îòêëþ÷èëñÿ êëèåíò...\n");
closesocket(g_ctxs[key].socket);
count_client--;
//printf("Êëèåíòîâ: %d\n", count_client);
schedule_read(key);