-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathExecAs.cpp
1574 lines (1370 loc) · 65.4 KB
/
ExecAs.cpp
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
/////////////////////////////////////////////////////////////
// ExecAs.cpp
//
// Command line utility that executes a command (plaintext or encryted) as another user account or
// under specified user session by temporarily installing itself as a service.
//
//
/*
MIT License (MIT)
Copyright © 2018 Noël Martinon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//
// Based on Valery Pryamikov's CreateProcessAsUser utility written in 1999
// which was based on Keith Brown's AsLocalSystem utility
// (see http://read.pudn.com/downloads178/sourcecode/windows/829566/CreateProcessAsUser.cpp__.htm)
// No license or restriction was found with that source code so, unless otherwise
// specified by Valery Pryamikov, code and binaries are released under the MIT License.
//
// Upgraded by Noël Martinon (2018) :
// Code in pure C++/Win32 (bcc & gcc compatible)
// Wait option added (wait for passed command to terminate and return its errorlevel)
// Hide option added (hide the window create by command)
// RunAS option added (like runas.exe but password is a parameter, no admin rights needed, no service used)
// Command line parameters can be encrypted into a string
// Multi-instance execution (unique service name based on timestamp, especially necessary when using wait option)
// Interactif mode is using current active user session either console or remote desktop session
// Windows 7 and Windows 10 32/64bits supported (service deleted after ensure it's stopped)
//
//
// /!\ NOT SECURE /!\
// Since this source code is public it's easy to use the decrypt() function to get
// the plaintext from encrypted string and potentially retrieve a password passed as an argument !
//
// So modify the 2 functions encrypt() and decrypt() to your own code to increase security (get password from workgroup, change checksum size...)
// /!\ NOT SECURE /!\
//
//
// ExecAs.exe - Version 1.1.0
// MIT License / Copyright (C) 2018 Noël Martinon
//
// Use:
// ExecAs.exe [-c[rypt]] [-n[oconsole]] [-i[nteractive]|-e[xclusive]]|-s[ystem]] |
// [[-r[unas]] -u"UserName" -d"DomainName" -p"Password"] | [-a"AppID"] [-w[ait]] [-h[ide]] Command | Encrypted_Parameters
//
// -c encrypt the arguments into an 'Encrypted_Parameters' string copied
// to clipboard that can be passed as single command parameter
// -n hide the console window associated with ExecAs.exe (NOT
// AVAILABLE WITH '-c' PARAMETER). Useful in a shortcut;)
// -i process will be launched under credentials of the
// \"Interactive User\" if it exists otherwise as local system
// -e process will be launched under credentials of the
// \"Interactive User\" ONLY if it exists
// -a process will be launched under credentials of the user
// specified in \"RunAs\" parameter of AppID
// -s process will be launched as local system
// -u -d -p process will be launched on the result token session of the
// authenticated user according to userName,domainName,password
// -r -u -d -p process will be launched as RUNAS command in the current
// session according to userName,domainName,password
// -w wait for Command to terminate
// -h hide window created by launched process (THIS IS NOT
// AVAILABLE WITH '-s' PARAMETER)
// Command must begin with the process (path to the exe file) to launch
// Either (-s) or (-i) or (-e) or (-a) or (-u -d -p) or (-r -u -d -p) with optional (-c)(-n)(-w)(-h) parameters or single 'Encrypted_Parameters' must supplied
//
// Only (-c) and (-r) parameters do not need admin permissions to run ExecAs.exe
//
// If using (-c) parameter then it must be the first argument
//
// If using (-n) parameter then it must be the first argument or the one that follows (-c)
//
// 'Encrypted_Parameters' can be a path to a text file that strickly contains the encrypted command
//
// Examples:
// ExecAs.exe -s prog.exe
// ExecAs.exe -i -w prog.exe arg1 arg2
// ExecAs.exe -e cmd /c "dir c: && pause"
// ExecAs.exe -c -e prog.exe arg
// ExecAs.exe NnRMNy8zTEHq0vv/csDxVZ1gsiqGUIGuppzB12K3HnfYvPue6+UcM/lLsGjRmdt0BmXfETUy5IaIVQliK1UOa74zuXwzi687
// ExecAs.exe encrypted_cmd.txt
// ExecAs.exe -r -u"user1" -p"pass1" -d prog.exe arg1
// ExecAs.exe -a"{731A63AF-2990-11D1-B12E-00C04FC2F56F}" prog.exe
// ExecAs.exe -c -n -r -uadministrator -padminpasswd -ddomain -w -h wmic product where \"name like 'Java%'\" call uninstall /nointeractive
// ExecAs.exe -i -w -h ExecAs.exe -r -u"user1" -p"pass1" -d prog.exe arg1
//
//
/////////////////////////////////////////////////////////////
#define APP_VERSION "1.1.0"
#define _WIN32_WINNT 0x0A00
#include <windows.h>
#include <userenv.h>
#include <ntsecapi.h>
#include <wtsapi32.h>
#include <ntstatus.h>
#include "common.hpp"
#include "Base64.hpp"
#include "Rijndael.hpp"
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "userenv.lib")
#pragma comment(lib, "wtsapi32.lib")
#define E_OBJ_IS_A_SERVICE 0x80040500 //-2147220224
#define E_NO_RUN_AS_DATA 0x80040501 //-2147220223
#define E_RUN_AS_INTERACTIVE 0x80040502 //-2147220222
#define E_NO_INTERACTIVE_SESSION 0x80040503 //-2147220221
#define E_SHELL_NOT_FOUND 0x80040504 //-2147220220 0x80040504(hex) = 2147747076(dec)
// => dword to int (returned value) : 2147747076 - 2^32 = -2147220220
#define GUIDSTR_MAX 38
#define MAX_TASKS 256
#define MAX_CMD_LEN 8192
#define SERVICE_NAME "ProcessAU" // Process As User
// Encryption used is AES-128-CBC :
// - For CBC mode, the initialization vector (IV) is the size of a block, which for AES is 16 bytes (128 bits)
// - The key size is 16 bytes (128 bits) for AES-128-CBC
#define BLOCK_SIZE 16
#define IV_SIZE 16
#define KEY_SIZE 16
#define CHECK_SIZE 8
int argc_dynamic = 0;
char **argv_dynamic = NULL;
LPCTSTR g_servicename;
SERVICE_STATUS_HANDLE g_hss;
SERVICE_STATUS g_ss;
void DeleteDynamic();
HRESULT GrantDesktopAccess(HANDLE hToken);
//---------------------------------------------------------------------------
HRESULT GetProcessToken(DWORD dwProcessID, LPHANDLE token, DWORD nUserNameMax, LPSTR szUserName, DWORD nUserDomainMax, LPSTR szUserDomain)
{
HANDLE hProcess=OpenProcess(PROCESS_DUP_HANDLE|PROCESS_QUERY_INFORMATION,TRUE,dwProcessID);
HRESULT retval = S_OK;
if(hProcess) {
HANDLE hToken = INVALID_HANDLE_VALUE;
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) retval = HRESULT_FROM_WIN32(GetLastError());
else {
BYTE buf[MAX_PATH]; DWORD dwRead = 0;
if (!GetTokenInformation(hToken, TokenUser, buf, MAX_PATH, &dwRead)) retval = HRESULT_FROM_WIN32(GetLastError());
else {
TOKEN_USER *puser = reinterpret_cast<TOKEN_USER*>(buf);
SID_NAME_USE eUse;
if (!LookupAccountSid(NULL, puser->User.Sid, szUserName, &nUserNameMax, szUserDomain, &nUserDomainMax, &eUse))
retval = HRESULT_FROM_WIN32(GetLastError());
}
if (FAILED(retval)) return retval;
if (!DuplicateTokenEx(hToken,
TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE,
NULL, SecurityImpersonation, TokenPrimary,token))
retval = HRESULT_FROM_WIN32(GetLastError());
else retval = S_OK;
CloseHandle(hToken);
}
CloseHandle(hProcess);
} else retval = HRESULT_FROM_WIN32(GetLastError());
return retval;
}
//---------------------------------------------------------------------------
DWORD GetCurrentUserSessionId_RemoteDesktop()
{
int dwSessionId = 0;
PWTS_SESSION_INFO pSessionInfo = 0;
DWORD dwCount = 0;
// Get the list of all terminal sessions
WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1,
&pSessionInfo, &dwCount);
// look over obtained list in search of the active session
for (DWORD i = 0; i < dwCount; ++i)
{
WTS_SESSION_INFO si = pSessionInfo[i];
if (WTSActive == si.State)
{
// If the current session is active store its ID
dwSessionId = si.SessionId;
break;
}
}
WTSFreeMemory(pSessionInfo);
return dwSessionId;
}
//---------------------------------------------------------------------------
HRESULT GetInteractiveUserToken(LPHANDLE token, DWORD nUserNameMax, LPSTR szUserName, DWORD nUserDomainMax, LPSTR szUserDomain)
{
DWORD session_id = WTSGetActiveConsoleSessionId();
DWORD explorer_pid = 0xFFFFFFFF;
DWORD rdp_session_id = GetCurrentUserSessionId_RemoteDesktop();
bool bShellFound = false;
PROCESSENTRY32 proc_entry = { 0 };
HANDLE snap = INVALID_HANDLE_VALUE;
snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE)
return HRESULT_FROM_WIN32(GetLastError());
proc_entry.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(snap, &proc_entry))
return HRESULT_FROM_WIN32(GetLastError());
do
{
if (stricmp(proc_entry.szExeFile, "explorer.exe") == 0)
{
// winlogon process found...make sure it's running in the console session
DWORD explorer_session_id = 0;
bShellFound = true;
if (ProcessIdToSessionId(proc_entry.th32ProcessID, &explorer_session_id) &&
(explorer_session_id == session_id || explorer_session_id == rdp_session_id))
{
explorer_pid = proc_entry.th32ProcessID;
break;
}
}
} while (Process32Next(snap, &proc_entry));
CloseHandle(snap);
if (!bShellFound)
return E_SHELL_NOT_FOUND;
if (0xFFFFFFFF == explorer_pid)
return E_NO_INTERACTIVE_SESSION;
return GetProcessToken(explorer_pid, token, nUserNameMax, szUserName, nUserDomainMax, szUserDomain);
}
//---------------------------------------------------------------------------
HRESULT GetRunAsPassword (LPSTR AppID, int nPasswordMax, LPSTR szPassword, int nUserNameMax, LPSTR szUserName, int nUserDomainMax, LPSTR szUserDomain)
{
LSA_OBJECT_ATTRIBUTES objectAttributes;
HANDLE policyHandle = NULL;
LSA_UNICODE_STRING lsaKeyString;
PLSA_UNICODE_STRING lsaPasswordString;
char key [4 + GUIDSTR_MAX + 1];
ULONG returnValue;
char keyName [MAX_PATH+1];
HKEY registryKey;
sprintf (keyName, "AppID\\%s", AppID);
returnValue = RegOpenKeyEx (HKEY_CLASSES_ROOT, keyName, 0, KEY_READ, ®istryKey);
if (returnValue == ERROR_SUCCESS) {
DWORD valueType;
DWORD valueSize = 0;
returnValue = RegQueryValueEx (registryKey, "LocalService", NULL, &valueType, NULL, &valueSize);
if (returnValue == ERROR_SUCCESS || returnValue == ERROR_MORE_DATA) return RegCloseKey (registryKey), E_OBJ_IS_A_SERVICE;
char principal[MAX_PATH+1];
valueSize = (MAX_PATH+1)*sizeof(CHAR);
returnValue = RegQueryValueEx(registryKey, "RunAs", NULL, &valueType, (BYTE*)principal, &valueSize);
RegCloseKey (registryKey);
if (returnValue != ERROR_SUCCESS) return E_NO_RUN_AS_DATA;
if (stricmp(principal, "Interactive User") == 0) return E_RUN_AS_INTERACTIVE;
char *ptmp = strchr(principal, '\\');
if (ptmp == 0) {
memset(szUserDomain, 0, nUserDomainMax);
strncpy(szUserName, principal, nUserNameMax);
} else {
memset(szUserDomain, 0, nUserDomainMax);
strncpy(szUserDomain, principal, min(nUserDomainMax, ptmp-principal));
strncpy(szUserName, ptmp+1, nUserNameMax);
}
} else return E_NO_RUN_AS_DATA;
strcpy (key, "SCM:");
strcat (key, AppID);
const size_t cSize = strlen(key)+1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs (wc, key, cSize);
lsaKeyString.Length = (USHORT) ((strlen (key) + 1) * sizeof (CHAR));
lsaKeyString.MaximumLength = (GUIDSTR_MAX + 5) * sizeof (CHAR);
lsaKeyString.Buffer = wc;
//
// Open the local security policy
//
memset (&objectAttributes, 0x00, sizeof (LSA_OBJECT_ATTRIBUTES));
objectAttributes.Length = sizeof (LSA_OBJECT_ATTRIBUTES);
returnValue = LsaOpenPolicy (NULL,
&objectAttributes,
POLICY_GET_PRIVATE_INFORMATION,
&policyHandle);
if (returnValue != ERROR_SUCCESS)
return returnValue;
//
// Read the user's password
//
returnValue = LsaRetrievePrivateData (policyHandle,
&lsaKeyString,
&lsaPasswordString);
if (returnValue != ERROR_SUCCESS)
{
LsaClose (policyHandle);
return returnValue;
}
const size_t cwSize = wcslen(lsaPasswordString->Buffer)+1;
char *str_lsaPasswordString_Buffer = new char[cwSize];
wcstombs(str_lsaPasswordString_Buffer, lsaPasswordString->Buffer, cwSize);
LsaClose (policyHandle);
strncpy (szPassword, str_lsaPasswordString_Buffer, nPasswordMax);
LsaFreeMemory(lsaPasswordString->Buffer);
return ERROR_SUCCESS;
}
//---------------------------------------------------------------------------
void Quit( const char *pszMsg, int nExitCode = 1 )
{
DeleteDynamic();
if (pszMsg) {
CharToOem((LPCSTR)pszMsg, (LPSTR)pszMsg);
printf ( "%s\n", pszMsg );
}
exit( nExitCode );
}
//---------------------------------------------------------------------------
void DisplayError(LPCSTR pszMsg=NULL, DWORD dwExitCode = GetLastError())
{
LPVOID lpMsgBuf;
//if ( dwExitCode==0xC000013A) dwExitCode=1; // the application has been terminated by closing command prompt window
//if ( dwExitCode==0xFF) dwExitCode=1; // the application has been terminated by user's keyboard input CTRL+C or CTRL+Break
DWORD IsFormatted = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwExitCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL );
if (IsFormatted) {
CharToOem((LPCSTR)lpMsgBuf, (LPSTR)lpMsgBuf);
if (pszMsg && dwExitCode>1) printf( "%s - Err %lu: %s", pszMsg, dwExitCode, (LPCTSTR)lpMsgBuf );
else if (dwExitCode>1) printf ( "Err %lu: %s", dwExitCode, (LPCTSTR)lpMsgBuf );
else printf ( "%s", (LPCTSTR)lpMsgBuf );
LocalFree( lpMsgBuf );
}
else if (pszMsg && dwExitCode>0) printf( "%s - Err %lu\n", pszMsg, dwExitCode );
else if (dwExitCode>0) printf( "Err %lu\n", dwExitCode );
Quit( NULL, dwExitCode);
}
//---------------------------------------------------------------------------
void PrintUsageAndQuit()
{
Quit( "ExecAs.exe - Version "
APP_VERSION
"\nMIT License / Copyright (C) 2018 Noël Martinon\n\n"
"Use:\n"
"ExecAs.exe [-c[rypt]] [-n[oconsole]] [-i[nteractive]|-e[xclusive]]|-s[ystem]] | "
"[[-r[unas]] -u\"UserName\" -d\"DomainName\" -p\"Password\"] | [-a\"AppID\"] [-w[ait]] [-h[ide]] Command | Encrypted_Parameters\n\n"
"-c encrypt the arguments into an 'Encrypted_Parameters' string copied\n"
" to clipboard that can be passed as single command parameter\n"
"-n hide the console window associated with ExecAs.exe (NOT\n"
" AVAILABLE WITH '-c' PARAMETER). Useful in a shortcut;)\n"
"-i process will be launched under credentials of the\n"
" \"Interactive User\" if it exists otherwise as local system\n"
"-e process will be launched under credentials of the\n"
" \"Interactive User\" ONLY if it exists\n"
"-a process will be launched under credentials of the user\n"
" specified in \"RunAs\" parameter of AppID\n"
"-s process will be launched as local system\n"
"-u -d -p process will be launched on the result token session of the\n"
" authenticated user according to userName,domainName,password\n"
"-r -u -d -p process will be launched as RUNAS command in the current\n"
" session according to userName,domainName,password\n"
"-w wait for Command to terminate\n"
"-h hide option created by launched process (NOT AVAILABLE\n"
" WITH '-s' PARAMETER)\n"
"Command must begin with the process (path to the exe file) to launch\n"
"\nEither (-s) or (-i) or (-e) or (-a) or (-u -d -p) or (-r -u -d -p) with optional (-c)(-n)(-w)(-h) parameters or single 'Encrypted_Parameters' must supplied\n"
"\nOnly (-c) and (-r) parameters do not need admin permissions to run ExecAs.exe\n"
"\nIf using (-c) parameter then it must be the first argument\n"
"\nIf using (-n) parameter then it must be the first argument or the one that follows (-c)\n"
"\n'Encrypted_Parameters' can be a path to a text file that strickly contains the encrypted command\n"
"\nExamples:\n"
"ExecAs.exe -s prog.exe\n"
"ExecAs.exe -i -w prog.exe arg1 arg2\n"
"ExecAs.exe -e cmd /c \"dir c: && pause\"\n"
"ExecAs.exe -c -e prog.exe arg\n"
"ExecAs.exe NnRMNy8zTEHq0vv/csDxVZ1gsiqGUIGuppzB12K3HnfYvPue6+UcM/lLsGjRmdt0BmXfETUy5IaIVQliK1UOa74zuXwzi687\n"
"ExecAs.exe encrypted_cmd.txt\n"
"ExecAs.exe -r -u\"user1\" -p\"pass1\" -d prog.exe arg1\n"
"ExecAs.exe -a\"{731A63AF-2990-11D1-B12E-00C04FC2F56F}\" prog.exe\n"
"ExecAs.exe -c -n -r -uadministrator -padminpasswd -ddomain -w -h wmic product where \\\"name like 'Java%'\\\" call uninstall /nointeractive\n"
"ExecAs.exe -i -w -h ExecAs.exe -r -u\"user1\" -p\"pass1\" -d prog.exe arg1");
}
//---------------------------------------------------------------------------
void* GetAdminSid()
{
SID_IDENTIFIER_AUTHORITY ntauth = SECURITY_NT_AUTHORITY;
void* psid = 0;
if ( !AllocateAndInitializeSid( &ntauth, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &psid ) )
DisplayError( "AllocateAndInitializeSid" );
return psid;
}
//---------------------------------------------------------------------------
void* GetLocalSystemSid()
{
SID_IDENTIFIER_AUTHORITY ntauth = SECURITY_NT_AUTHORITY;
void* psid = 0;
if ( !AllocateAndInitializeSid( &ntauth, 1,
SECURITY_LOCAL_SYSTEM_RID,
0, 0, 0, 0, 0, 0, 0, &psid ) )
DisplayError( "AllocateAndInitializeSid" );
return psid;
}
//---------------------------------------------------------------------------
bool IsAdmin()
{
bool bIsAdmin = false;
HANDLE htok = 0;
if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &htok ) )
DisplayError( "OpenProcessToken" );
DWORD cb = 0;
GetTokenInformation( htok, TokenGroups, 0, 0, &cb );
TOKEN_GROUPS* ptg = (TOKEN_GROUPS*)malloc( cb );
if ( !ptg )
DisplayError( "malloc" );
if ( !GetTokenInformation( htok, TokenGroups, ptg, cb, &cb ) )
DisplayError( "GetTokenInformation" );
void* pAdminSid = GetAdminSid();
SID_AND_ATTRIBUTES* const end = ptg->Groups + ptg->GroupCount;
SID_AND_ATTRIBUTES* it;
for ( it = ptg->Groups; end != it; ++it )
if ( EqualSid( it->Sid, pAdminSid ) )
break;
bIsAdmin = end != it;
FreeSid( pAdminSid );
free( ptg );
CloseHandle( htok );
return bIsAdmin;
}
//---------------------------------------------------------------------------
bool IsLocalSystem()
{
bool bIsLocalSystem = false;
HANDLE htok = 0;
if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &htok ) )
DisplayError( "OpenProcessToken" );
BYTE userSid[256];
DWORD cb = sizeof userSid;
if ( !GetTokenInformation( htok, TokenUser, userSid, cb, &cb ) )
DisplayError( "GetTokenInformation" );
TOKEN_USER* ptu = (TOKEN_USER*)userSid;
void* pLocalSystemSid = GetLocalSystemSid();
bIsLocalSystem = EqualSid( pLocalSystemSid, ptu->User.Sid ) ? true : false;
FreeSid( pLocalSystemSid );
CloseHandle( htok );
return bIsLocalSystem;
}
//---------------------------------------------------------------------------
void StartAsService( int argc, const char *argv[] )
{
char szModuleFileName[MAX_PATH];
GetModuleFileName( 0, szModuleFileName, sizeof szModuleFileName / sizeof *szModuleFileName );
// come up with unique name for this service
SC_HANDLE hscm = OpenSCManager( 0, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CREATE_SERVICE );
if ( !hscm )
DisplayError( "OpenSCManager" );
SC_HANDLE hsvc = 0;
for ( int nRetry = 0; nRetry < 2; ++nRetry )
{
hsvc = CreateService( hscm,
g_servicename,
g_servicename,
SERVICE_START | SERVICE_QUERY_STATUS | DELETE,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
szModuleFileName,
0, 0,
0,
0, 0 );
if ( hsvc )
break;
else if ( ERROR_SERVICE_EXISTS == GetLastError() )
{
SC_HANDLE hsvc = OpenService( hscm, g_servicename, DELETE );
DeleteService( hsvc );
CloseServiceHandle( hsvc );
hsvc = 0;
}
else break;
}
if ( !hsvc )
DisplayError( "CreateService" );
if ( !StartService( hsvc, argc, argv ) ) {
DeleteService( hsvc );
CloseServiceHandle( hsvc );
CloseServiceHandle( hscm );
DisplayError( "StartService" );
}
SERVICE_STATUS _ss;
do {
QueryServiceStatus (hsvc, &_ss);
Sleep(100);
}
while ( _ss.dwCurrentState != SERVICE_STOPPED );
DeleteService( hsvc );
CloseServiceHandle( hsvc );
CloseServiceHandle( hscm );
}
//---------------------------------------------------------------------------
void WINAPI Handler( DWORD )
{
SetServiceStatus( g_hss, &g_ss );
}
//---------------------------------------------------------------------------
void WINAPI ServiceMain( DWORD argc, char *argv[] )
{
char szCurrentDirectory[MAX_PATH];
GetModuleFileName( 0, szCurrentDirectory, sizeof szCurrentDirectory / sizeof *szCurrentDirectory );
char *pc=strrchr(szCurrentDirectory,'\\');
*pc = '\0';
g_servicename = argv[argc-1];
g_ss.dwCurrentState = SERVICE_RUNNING;
g_ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS;
g_hss = RegisterServiceCtrlHandler( g_servicename, Handler );
SetServiceStatus( g_hss, &g_ss );
bool fAsSystem = false;
bool fAsAppID = false;
bool fAsInteractive = false;
bool fRunWithoutSession = false;
bool fEqualToInteractive = false;
bool fWaitToTerminate = false;
bool fShowWindow = true;
for (int i = 1; i < argc && i <=2; i++) {
if (strnicmp(argv[i], "-s", 2)==0) fAsSystem = true;
else if (strnicmp(argv[i], "-w", 2)==0) fWaitToTerminate = true;
else break;
}
DWORD dwExitCode = 0;
HANDLE hptoken = INVALID_HANDLE_VALUE;
DWORD dwErr = 0;
LPCSTR szDescr = NULL;
do {
if (!fAsSystem) {
LPSTR szcUser = NULL;
LPSTR szcDomain = NULL;
LPSTR szcPassword = NULL;
LPSTR szcAppID = NULL;
char szPassword[MAX_PATH], szUserName[MAX_PATH], szUserDomain[MAX_PATH];
memset(szPassword,0,sizeof(szPassword));
memset(szUserName,0,sizeof(szUserName));
memset(szUserDomain,0,sizeof(szUserDomain));
for (DWORD i = 1; i < argc; i++) {
if (strnicmp(argv[i], "-d",2)==0) szcDomain = argv[i]+2;
else if (strnicmp(argv[i], "-u", 2)==0) szcUser = argv[i]+2;
else if (strnicmp(argv[i], "-p", 2)==0) szcPassword = argv[i]+2;
else if (strnicmp(argv[i], "-a", 2)==0) szcAppID = argv[i]+2;
else if (strnicmp(argv[i], "-i", 2)==0) {fAsInteractive = true; fRunWithoutSession = true;}
else if (strnicmp(argv[i], "-e", 2)==0) fAsInteractive = true;
else if (strnicmp(argv[i], "-w", 2)==0) fWaitToTerminate = true;
else if (strnicmp(argv[i], "-h", 2)==0) fShowWindow = false;
else break;
}
if (szcAppID) {
fAsAppID = true;
if (FAILED(dwErr = GetRunAsPassword(szcAppID, MAX_PATH, szPassword, MAX_PATH, szUserName, MAX_PATH, szUserDomain))) {
if (E_RUN_AS_INTERACTIVE == dwErr) {
fAsAppID = false;
fAsInteractive = true;
} else {szDescr = "Failed to retrieve AppID data"; break;}
} else {
szcUser = szUserName;
szcDomain = szUserDomain;
szcPassword = szPassword;
}
}
if (!fAsInteractive && !fAsAppID) {
strcpy(szUserName,szcUser);
strcpy(szUserDomain, szcDomain);
strcpy(szPassword, szcPassword);
}
if (fAsInteractive) {
if (FAILED(dwErr = GetInteractiveUserToken(&hptoken, MAX_PATH, szUserName, MAX_PATH, szUserDomain))) {
if (fRunWithoutSession) {
dwErr = 0;
} else { szDescr = "Failed to retrieve interactive session"; break; }
}
} else {
if (!LogonUser(szcUser,szcDomain,szcPassword,
LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, &hptoken)) {
dwErr = GetLastError(), szDescr = "LogonUser failed"; break; }
HANDLE htmp;
memset(szPassword, 0, sizeof(szPassword));
szcUser = szPassword;
szcDomain = szPassword + MAX_PATH/2;
if (FAILED(dwErr = GetInteractiveUserToken(&htmp, MAX_PATH/2, szcUser, MAX_PATH/2, szcDomain))) {
szDescr = "Failed to retrieve interactive session"; break;}
CloseHandle(htmp);
fEqualToInteractive = (stricmp(szcUser, szUserName) == 0 && stricmp(szcDomain, szUserDomain) == 0);
}
}
char cmd[MAX_CMD_LEN];
char *dst = cmd;
char *dstEnd = cmd + sizeof cmd / sizeof *cmd;
char **it = argv + ((fAsSystem ||fAsAppID||fAsInteractive)?2:7) + ((fWaitToTerminate)?1:0) + ((fShowWindow)?0:1);
char **const end = argv + argc -1; // -1 because last argv (service_name) is ignored
while ( end != it )
{
// add whitespace between args
if ( dst != cmd )
*dst++ = ' ';
// watch for overflow
const int cch = lstrlen( *it );
if ( dst + cch + 2 > dstEnd )
break;
// concatenate args
lstrcpy( dst, *it );
dst += cch;
++it;
}
*dst = '\0';
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
if (!fAsInteractive && !fEqualToInteractive && !fAsSystem && hptoken!=INVALID_HANDLE_VALUE && (dwErr = GrantDesktopAccess(hptoken))!=S_OK)
szDescr = "GrantDesktopAccess failed";
// Get all necessary environment variables of logged in user
// to pass them to the process (only used by console application)
char* lpEnvironment = NULL;
DWORD dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
if (CreateEnvironmentBlock((void**)&lpEnvironment, hptoken, TRUE))
dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
if (!fShowWindow)
{
dwCreationFlags |= CREATE_NO_WINDOW;
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
}
if (INVALID_HANDLE_VALUE != hptoken) {
if ( CreateProcessAsUser(hptoken, 0, cmd, 0, 0, FALSE, dwCreationFlags, lpEnvironment, szCurrentDirectory, &si, &pi ) ) {
if (fWaitToTerminate) {
WaitForSingleObject( pi.hProcess, INFINITE );
GetExitCodeProcess( pi.hProcess, &dwExitCode );
}
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
} else dwErr = GetLastError(), szDescr = "CreateProcessAsUser failed";
hptoken = (CloseHandle(hptoken), INVALID_HANDLE_VALUE);
} else if ( CreateProcess( 0, cmd, 0, 0, FALSE, 0, 0, szCurrentDirectory, &si, &pi ) ) {
if (fWaitToTerminate) {
WaitForSingleObject( pi.hProcess, INFINITE );
GetExitCodeProcess( pi.hProcess, &dwExitCode );
}
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
} else dwErr = GetLastError(), szDescr = "CreateProcess failed";
if (lpEnvironment != NULL) DestroyEnvironmentBlock(lpEnvironment);
} while(false);
char sFileMap[MAX_PATH];
sprintf(sFileMap, "Global\\filemap_%s", g_servicename);
HANDLE hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,0x4000,sFileMap);
int* mData = (int*)MapViewOfFile(hFileMap,FILE_MAP_ALL_ACCESS,0,0,0);
*mData = dwExitCode;
if ( dwExitCode==0 && dwErr ) *mData = dwErr;
UnmapViewOfFile(mData);
CloseHandle(hFileMap);
if (dwErr) {
HANDLE h;
if (hptoken != INVALID_HANDLE_VALUE) hptoken = (CloseHandle(hptoken), INVALID_HANDLE_VALUE);
h = RegisterEventSource(NULL, SERVICE_NAME);
LPSTR lpszStrings[1];
char szErrMsg[512];
char szMsg[1024];
if ( FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, 0, dwErr, 0, szErrMsg, sizeof szErrMsg / sizeof *szErrMsg, 0 ))
sprintf ( szMsg, "%s : %s", szDescr, szErrMsg );
else sprintf ( szMsg, "%s", szDescr);
lpszStrings[0] = szMsg;
if (h != NULL) {
ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, dwErr, NULL, (szDescr)?1:0, 0, (szDescr)?(LPCSTR*)&lpszStrings[0]:NULL,NULL);
DeregisterEventSource(h);
}
}
g_ss.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus( g_hss, &g_ss );
}
//---------------------------------------------------------------------------
HRESULT RetrieveLogonSid(HANDLE hToken,PSID *pLogonSid)
{
PTOKEN_GROUPS ptgGroups = NULL;
DWORD cbBuffer = 0;
DWORD dwSidLength;
UINT i;
HRESULT hr=S_OK;
try {
*pLogonSid = NULL;
GetTokenInformation(hToken, TokenGroups, ptgGroups, cbBuffer, &cbBuffer);
if (cbBuffer && !(ptgGroups = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbBuffer))) { hr = E_OUTOFMEMORY; goto return_RetrieveLogonSid; }
if (!GetTokenInformation(hToken,TokenGroups,ptgGroups,cbBuffer,&cbBuffer)) { hr = GetLastError(); goto return_RetrieveLogonSid; }
// Get the logon Sid by looping through the Sids in the token
for(i = 0 ; i < ptgGroups->GroupCount ; i++) {
if (ptgGroups->Groups[i].Attributes & SE_GROUP_LOGON_ID) {
if (!IsValidSid(ptgGroups->Groups[i].Sid)) { hr = E_FAIL; goto return_RetrieveLogonSid; }
dwSidLength=GetLengthSid(ptgGroups->Groups[i].Sid);
if((*pLogonSid = (PSID)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwSidLength)) == NULL) { hr = E_OUTOFMEMORY; goto return_RetrieveLogonSid; }
if (!CopySid(dwSidLength,*pLogonSid,ptgGroups->Groups[i].Sid)) { hr = GetLastError(); goto return_RetrieveLogonSid; }
hr = S_OK;
goto return_RetrieveLogonSid;
}
}
hr = E_INVALIDARG;
return_RetrieveLogonSid:
if (hr != S_OK) {
if(*pLogonSid != NULL) {
HeapFree(GetProcessHeap(), 0, *pLogonSid);
*pLogonSid = NULL;
}
}
if (ptgGroups != NULL) HeapFree(GetProcessHeap(), 0, ptgGroups);
return hr;
} catch(...){
if (hr != S_OK) {
if(*pLogonSid != NULL) {
HeapFree(GetProcessHeap(), 0, *pLogonSid);
*pLogonSid = NULL;
}
}
if (ptgGroups != NULL) HeapFree(GetProcessHeap(), 0, ptgGroups);
}
return E_UNEXPECTED;
}
//---------------------------------------------------------------------------
HRESULT InsertSidInAcl(PSID pSid,PACL pAclSource,PACL *pAclDestination,DWORD AccessMask,bool bAddSid,bool bFreeOldAcl)
{
ACL_SIZE_INFORMATION AclInfo;
DWORD dwNewAclSize;
LPVOID pAce;
DWORD AceCounter;
HRESULT hr=S_OK;
try {
if (pAclSource == NULL) {
*pAclDestination = NULL;
return S_OK;
}
if (!IsValidSid(pSid)) { hr = E_FAIL; goto return_InsertSidInAcl; }
if (!GetAclInformation(pAclSource,&AclInfo,sizeof(ACL_SIZE_INFORMATION),AclSizeInformation)) { hr = GetLastError(); goto return_InsertSidInAcl; }
// Compute size for new ACL, based on addition or subtraction of ACE
if (bAddSid) dwNewAclSize = AclInfo.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(pSid) - sizeof(DWORD);
else dwNewAclSize = AclInfo.AclBytesInUse - sizeof(ACCESS_ALLOWED_ACE) - GetLengthSid(pSid) + sizeof(DWORD);
*pAclDestination = (PACL) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwNewAclSize);
if (*pAclDestination == NULL) { hr = E_OUTOFMEMORY; goto return_InsertSidInAcl; }
if (!InitializeAcl(*pAclDestination, dwNewAclSize, ACL_REVISION)) { hr = GetLastError(); goto return_InsertSidInAcl; }
// copy existing ACEs to new ACL
for(AceCounter = 0 ; AceCounter < AclInfo.AceCount ; AceCounter++) {
if (!GetAce(pAclSource, AceCounter, &pAce)) { hr = GetLastError(); goto return_InsertSidInAcl; }
if (!bAddSid) {
// we only care about ACCESS_ALLOWED ACEs
if ((((PACE_HEADER)pAce)->AceType) == ACCESS_ALLOWED_ACE_TYPE) {
PSID pTempSid=(PSID)&((PACCESS_ALLOWED_ACE)pAce)->SidStart;
if (EqualSid(pSid, pTempSid)) continue;
}
}
if (!AddAce(*pAclDestination,ACL_REVISION,0,pAce,((PACE_HEADER)pAce)->AceSize)) { hr = GetLastError(); goto return_InsertSidInAcl; }
}
if (bAddSid && !AddAccessAllowedAce(*pAclDestination,ACL_REVISION,AccessMask,pSid)) { hr = GetLastError(); goto return_InsertSidInAcl; }
hr = S_OK;
return_InsertSidInAcl:
if (hr != S_OK) {
if(*pAclDestination != NULL) HeapFree(GetProcessHeap(), 0, *pAclDestination);
} else if (bFreeOldAcl) HeapFree(GetProcessHeap(), 0, pAclSource);
return hr;
} catch(...){
if (hr != S_OK) {
if(*pAclDestination != NULL) HeapFree(GetProcessHeap(), 0, *pAclDestination);
} else if (bFreeOldAcl) HeapFree(GetProcessHeap(), 0, pAclSource);
}
return E_UNEXPECTED;
}
//---------------------------------------------------------------------------
HRESULT AdjustWinstaDesktopSecurity(HWINSTA hWinsta, HDESK hDesktop, PSID pLogonSid, bool bGrant, HANDLE hToken)
{
SECURITY_INFORMATION si = DACL_SECURITY_INFORMATION;
PSECURITY_DESCRIPTOR sdDesktop = NULL;
PSECURITY_DESCRIPTOR sdWinsta = NULL;
SECURITY_DESCRIPTOR sdNewDesktop;
SECURITY_DESCRIPTOR sdNewWinsta;
DWORD sdDesktopLength = 0; /* allocation size */
DWORD sdWinstaLength = 0; /* allocation size */
PACL pDesktopDacl; /* previous Dacl on Desktop */
PACL pWinstaDacl; /* previous Dacl on Winsta */
PACL pNewDesktopDacl = NULL; /* new Dacl for Desktop */
PACL pNewWinstaDacl = NULL; /* new Dacl for Winsta */
BOOL bDesktopDaclPresent;
BOOL bWinstaDaclPresent;
BOOL bDaclDefaultDesktop;
BOOL bDaclDefaultWinsta;
HRESULT hr = S_OK;
PSID pUserSid = NULL;
try {
GetUserObjectSecurity(hDesktop, &si, sdDesktop, sdDesktopLength, &sdDesktopLength);
if (sdDesktopLength) sdDesktop = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sdDesktopLength);
if (!GetUserObjectSecurity(hDesktop,&si,sdDesktop,sdDesktopLength,&sdDesktopLength)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
GetUserObjectSecurity(hWinsta,&si,sdWinsta,sdWinstaLength,&sdWinstaLength);
if (sdWinstaLength) sdWinsta = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sdWinstaLength);
if (!GetUserObjectSecurity(hWinsta,&si,sdWinsta,sdWinstaLength,&sdWinstaLength)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
if (!GetSecurityDescriptorDacl(sdDesktop,&bDesktopDaclPresent, &pDesktopDacl, &bDaclDefaultDesktop)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
if (!GetSecurityDescriptorDacl(sdWinsta,&bWinstaDaclPresent,&pWinstaDacl,&bDaclDefaultWinsta)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
// Create new DACL with Logon and User Sid for Desktop
if(bDesktopDaclPresent && (hr = InsertSidInAcl(pLogonSid,pDesktopDacl,&pNewDesktopDacl,
GENERIC_READ | GENERIC_WRITE | READ_CONTROL | DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW |
DESKTOP_CREATEMENU | DESKTOP_SWITCHDESKTOP | DESKTOP_ENUMERATE, bGrant,false)) != S_OK) goto return_AdjustWinstaDesktopSecurity;
// Create new DACL with Logon and User Sid for Window station
if(bWinstaDaclPresent && (hr = InsertSidInAcl(pLogonSid,pWinstaDacl,&pNewWinstaDacl,
GENERIC_READ | GENERIC_WRITE | READ_CONTROL
| WINSTA_ACCESSGLOBALATOMS | WINSTA_ENUMDESKTOPS | WINSTA_READATTRIBUTES |
WINSTA_ACCESSCLIPBOARD | WINSTA_ENUMERATE | WINSTA_EXITWINDOWS, bGrant, false)) != S_OK) goto return_AdjustWinstaDesktopSecurity;
// Initialize the target security descriptor for Desktop
if (bDesktopDaclPresent && !InitializeSecurityDescriptor(&sdNewDesktop, SECURITY_DESCRIPTOR_REVISION)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
// Initialize the target security descriptor for Window station
if(bWinstaDaclPresent && !InitializeSecurityDescriptor(&sdNewWinsta,SECURITY_DESCRIPTOR_REVISION)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
// Apply new ACL to the Desktop security descriptor
if(bDesktopDaclPresent && !SetSecurityDescriptorDacl(&sdNewDesktop,TRUE,pNewDesktopDacl,bDaclDefaultDesktop)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
// Apply new ACL to the Window station security descriptor
if(bWinstaDaclPresent && !SetSecurityDescriptorDacl(&sdNewWinsta, TRUE, pNewWinstaDacl, bDaclDefaultWinsta)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
// Apply security descriptors with new DACLs to Desktop and Window station
if (bDesktopDaclPresent && !SetUserObjectSecurity(hDesktop, &si,&sdNewDesktop)) { hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
if(bWinstaDaclPresent && !SetUserObjectSecurity(hWinsta,&si,&sdNewWinsta)) {hr = GetLastError(); goto return_AdjustWinstaDesktopSecurity; }
hr = S_OK;
return_AdjustWinstaDesktopSecurity:
if (sdDesktop != NULL) HeapFree(GetProcessHeap(), 0, sdDesktop);
if (sdWinsta != NULL) HeapFree(GetProcessHeap(), 0, sdWinsta);
if (pNewDesktopDacl != NULL) HeapFree(GetProcessHeap(), 0, pNewDesktopDacl);
if (pNewWinstaDacl != NULL) HeapFree(GetProcessHeap(), 0, pNewWinstaDacl);
return hr;
} catch(...){
if (sdDesktop != NULL) HeapFree(GetProcessHeap(), 0, sdDesktop);
if (sdWinsta != NULL) HeapFree(GetProcessHeap(), 0, sdWinsta);
if (pNewDesktopDacl != NULL) HeapFree(GetProcessHeap(), 0, pNewDesktopDacl);
if (pNewWinstaDacl != NULL) HeapFree(GetProcessHeap(), 0, pNewWinstaDacl);
}
return E_UNEXPECTED;
}
//---------------------------------------------------------------------------
HRESULT GrantDesktopAccess(HANDLE hToken)
{
HWINSTA hWinsta = NULL;
HDESK hDesktop = NULL;
PSID pLogonSid = NULL;
HRESULT hr = E_FAIL;
try {
if ((hr = RetrieveLogonSid(hToken, &pLogonSid))!=S_OK) return hr;
hWinsta=GetProcessWindowStation();
hDesktop=GetThreadDesktop(GetCurrentThreadId());
if (!SetHandleInformation(hDesktop, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { hr = GetLastError(); goto return_GrantDesktopAccess; }
if (!SetHandleInformation(hWinsta, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { hr = GetLastError(); goto return_GrantDesktopAccess; }
hr = AdjustWinstaDesktopSecurity(hWinsta, hDesktop, pLogonSid, true, hToken);
return_GrantDesktopAccess:
if(pLogonSid != NULL) HeapFree(GetProcessHeap(), 0, pLogonSid);
return hr;
} catch(...){
if(pLogonSid != NULL)
HeapFree(GetProcessHeap(), 0, pLogonSid);
}
return E_UNEXPECTED;
}
//---------------------------------------------------------------------------
bool CopyToClipBoard(char *text)
{
if (!text | !text[0]) return false;
DWORD len;
HGLOBAL hgbl;
char temp[MAX_PATH];
char *pmem;
len = strlen(text);
hgbl = GlobalAlloc(GHND, len + 1);
if(!hgbl) return false;
pmem = (char*)GlobalLock(hgbl);
strcpy(pmem,text);
GlobalUnlock(hgbl);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_TEXT, hgbl);
CloseClipboard();
return true;
}
//---------------------------------------------------------------------------
char *Encrypt(char *data, int length)
{
char *ret_encrypted;
char IV[33]; // 16, 24 or 32
char KEY[33]; // 16, 24 or 32
char *p_dataIn;
char *p_dataOut;
int block_num;
int totalbytes;