forked from kavika13/RemCom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemCom.cpp
2189 lines (1737 loc) · 53.6 KB
/
RemCom.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
/*
Copyright (c) 2006-2012 Talha Tariq [ [email protected] ]
Luke Suchocki
Merlyn Morgan-Graham
Andres Ederra
All rights are reserved.
Permission to use, copy, modify, and distribute this software
for any purpose and without any fee is hereby granted,
provided this notice is included in its entirety in the
documentation and in the source files.
This software and any related documentation is provided "as is"
without any warranty of any kind, either express or implied,
including, without limitation, the implied warranties of
merchantability or fitness for a particular purpose. The entire
risk arising out of use or performance of the software remains
with you.
$Author: Talha Tariq [ [email protected] ]
uses some code from xCmd by Zoltan Csizmadia
$Revision: Talha Tariq [ [email protected] ]
$Revision: Luke Suchocki (patched rc)
$Revision: Merlyn Morgan-Graham (handle spaces in the filename)
$Revision: Andres Ederra (support for 64bits targets, send
remcom outout to stderr, support for longer
parameters, escape special characters in command
parameters, detailed error codes)
$Date: 2012/01/24 09:00:00 $
$Version History: $ - Refactored and Restructured Code - Deleted Unnecessary variables and Functions for Memory Consumption and Optimisation.
- Added Function StartLocalProcessAsUser for local user impersonation
- Added Start Local Process for launching external commands
- Added GetAdminSid, GetLocalSid, GetLogonSID, FreeLogonSid for getting tokens to pass on for logon impersonation
- Added IsLaunchedFromAdmin to get the local admin sid
- Added ExtractLocalBinaryResource to extract the local binary resource for local process impersonation
- Added ProcComs to implement local process functionality
- Added RemCom to implement remote process functionality
- Patched to give the correct return code
- Patched to handle spaces in the filename.
- Modified to handle longer command parameters
- Changed directory to copy executables to \\ADMIN$ instead of \\ADMIN$\system32 in order to support 64 bits targets
- Changed RemCom output to be sent to stderr while the remote command writes to stdout
- Allow to scape '/' character to use it as part of remote command and its parameters.
- Reclassified error return codes. Now RemCom returns its own return code, and the remote program return code is show at the stdout.
//Return Codes:
//
// (-1) Incorrect parameters
// (-2) Malformed credentials
// (-3) Invalid target name
// (-4) Bad credentials
// (-5) Could not connect to target
// (-6) Error copying executable
// (-7) Error copying service
// (-8) Error executing service
// (-9) Error connecting to remote service
- Patched to handle spaces in the filename (FIXED).
- Tested with: win2k, winxp(32bits), win2003(32&64), win2008R2(32&64), win7(32&64).
$TODO: - Add Getopt to parse command line parametres more effectively.
- Implemement cleanup and disconnect remote share command
$Description: $ - RemCom is RAT [Remote Administration Tool] that lets you execute processes on remote windows systems, copy files,
process there output and stream it back. It allows execution of remote shell commands directly with full interactive console
$Workfile: $ - RemCom.cpp
*/
#define _WIN32_WINNT 0x0500 //Will work only on W2K and above
#include "RemCom.h"
#define DESKTOP_ALL (DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | \
DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | \
DESKTOP_JOURNALPLAYBACK | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | \
DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_REQUIRED)
#define WINSTA_ALL (WINSTA_ENUMDESKTOPS | WINSTA_READATTRIBUTES | \
WINSTA_ACCESSCLIPBOARD | WINSTA_CREATEDESKTOP | WINSTA_WRITEATTRIBUTES | \
WINSTA_ACCESSGLOBALATOMS | WINSTA_EXITWINDOWS | WINSTA_ENUMERATE | \
WINSTA_READSCREEN | STANDARD_RIGHTS_REQUIRED)
#define GENERIC_ACCESS (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL)
// Constant Definitions
#define SIZEOF_BUFFER 0x500
// Local Machine Settings
TCHAR szThisMachine[SIZEOF_BUFFER] = _T("");
TCHAR szPassword[SIZEOF_BUFFER] = _T("");
TCHAR szArguments[SIZEOF_BUFFER] = _T("");
TCHAR szConsoleTitle[SIZEOF_BUFFER] = _T("");
TCHAR szLocalBinPath[_MAX_PATH] = _T("");
// Windows Default Windows Path
LPCTSTR lpszSystemRoot = "%SystemRoot%";
LPCTSTR lpszLocalMachine = "\\\\localhost";
LPCTSTR lpszLocalIP = "\\\\127.0.0.1";
// Remote Parameters
LPCTSTR lpszMachine = NULL;
LPCTSTR lpszPassword = NULL;
LPCTSTR lpszUser = NULL;
LPCTSTR lpszDomain = NULL;
LPCTSTR lpszCommandExe = NULL;
// Named Pipes for Input and Output
HANDLE hCommandPipe = INVALID_HANDLE_VALUE;
HANDLE hRemoteOutPipe = INVALID_HANDLE_VALUE;
HANDLE hRemoteStdInputPipe = INVALID_HANDLE_VALUE;
HANDLE hRemoteErrorPipe = INVALID_HANDLE_VALUE;
//Method Declarations
BOOL AddAceToWindowStation(HWINSTA hwinsta, PSID psid);
BOOL AddAceToDesktop(HDESK hdesk, PSID psid);
// Show the last error's description
DWORD ShowLastError()
{
LPVOID lpvMessageBuffer;
DWORD rc = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
rc,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpvMessageBuffer,
0,
NULL
);
//Error( _T("Error code = %d.\n", rc) );
//_ftprintf( stderr, "Error code = %d.\n", rc);
Error( (LPCTSTR)lpvMessageBuffer );
Error( _T("\n") );
LocalFree (lpvMessageBuffer);
//ExitProcess(GetLastError());
return rc;
}
//Gets the SID for Admin
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 ) )
ShowLastError();
return psid;
}
// Gets the SID for System Account
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 ) )
ShowLastError();
return psid;
}
// Checks if the launching process parent is local administrator
BOOL IsLaunchedFromAdmin()
{
bool bIsAdmin = false;
HANDLE hToken = 0;
if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &hToken ) ){
ShowLastError();
}
DWORD cb = 0;
GetTokenInformation( hToken, TokenGroups, 0, 0, &cb );
TOKEN_GROUPS* pTokenGroups = (TOKEN_GROUPS*)malloc( cb );
if ( !pTokenGroups )
ShowLastError();
if ( !GetTokenInformation( hToken, TokenGroups, pTokenGroups, cb, &cb ) )
ShowLastError();
void* pAdminSid = GetAdminSid();
SID_AND_ATTRIBUTES* const end = pTokenGroups->Groups + pTokenGroups->GroupCount;
SID_AND_ATTRIBUTES* it;
for ( it = pTokenGroups->Groups; end != it; ++it )
if ( EqualSid( it->Sid, pAdminSid ) )
break;
bIsAdmin = end != it;
FreeSid( pAdminSid );
free( pTokenGroups );
CloseHandle( hToken );
return bIsAdmin;
}
bool IsLocalSystem()
{
bool bIsLocalSystem = false;
HANDLE htok = 0;
if ( !OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &htok ) )
ShowLastError();
BYTE userSid[256];
DWORD cb = sizeof userSid;
if ( !GetTokenInformation( htok, TokenUser, userSid, cb, &cb ) )
ShowLastError();
TOKEN_USER* ptu = (TOKEN_USER*)userSid;
void* pLocalSystemSid = GetLocalSystemSid();
bIsLocalSystem = EqualSid( pLocalSystemSid, ptu->User.Sid ) ? true : false;
FreeSid( pLocalSystemSid );
CloseHandle( htok );
return bIsLocalSystem;
}
VOID FreeLogonSID (PSID *ppsid)
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
}
BOOL GetLogonSID (HANDLE hToken, PSID *ppsid)
{
BOOL bSuccess = FALSE;
DWORD dwIndex;
DWORD dwLength = 0;
PTOKEN_GROUPS ptg = NULL;
// Verify the parameter passed in is not NULL.
if (NULL == ppsid)
goto Cleanup;
// Get required buffer size and allocate the TOKEN_GROUPS buffer.
if (!GetTokenInformation(
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
0, // size of buffer
&dwLength // receives required buffer size
))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
goto Cleanup;
ptg = (PTOKEN_GROUPS)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
if (ptg == NULL)
goto Cleanup;
}
// Get the token group information from the access token.
if (!GetTokenInformation(
hToken, // handle to the access token
TokenGroups, // get information about the token's groups
(LPVOID) ptg, // pointer to TOKEN_GROUPS buffer
dwLength, // size of buffer
&dwLength // receives required buffer size
))
{
goto Cleanup;
}
// Loop through the groups to find the logon SID.
for (dwIndex = 0; dwIndex < ptg->GroupCount; dwIndex++)
if ((ptg->Groups[dwIndex].Attributes & SE_GROUP_LOGON_ID)
== SE_GROUP_LOGON_ID)
{
// Found the logon SID; make a copy of it.
dwLength = GetLengthSid(ptg->Groups[dwIndex].Sid);
*ppsid = (PSID) HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwLength);
if (*ppsid == NULL)
goto Cleanup;
if (!CopySid(dwLength, *ppsid, ptg->Groups[dwIndex].Sid))
{
HeapFree(GetProcessHeap(), 0, (LPVOID)*ppsid);
goto Cleanup;
}
break;
}
bSuccess = TRUE;
Cleanup:
// Free the buffer for the token groups.
if (ptg != NULL)
HeapFree(GetProcessHeap(), 0, (LPVOID)ptg);
return bSuccess;
}
// Check the command line arguments
BOOL IsCmdLineParameter( LPCTSTR lpszParam )
{
for( int i = 1; i < __argc; i++ )
{
if ( __targv[i][0] == _T('\\') )
continue;
else
{
if ( __targv[i][0] == _T('/') )
{
if ( _tcsicmp( __targv[i] + 1, lpszParam ) == 0 )
return TRUE;
}
else
return FALSE;
}
}
return FALSE;
}
LPCTSTR GetParamValue( LPCTSTR lpszParam )
{
DWORD dwParamLength = _tcslen( lpszParam );
for( int i = 1; i < __argc; i++ ){
if ( __targv[i][0] == _T('\\') || __targv[i][0] == _T('.'))
continue;
else{
if ( __targv[i][0] == _T('/') )
{
if ( _tcsnicmp( __targv[i] + 1, lpszParam, dwParamLength ) == 0 )
return __targv[i] + dwParamLength + 1;
}
else
return NULL;
}
}
return NULL;
}
LPCTSTR GetNthParameter( DWORD n, DWORD& argvIndex )
{
DWORD index = 0;
for( int i = 1; i < __argc; i++ )
{
DWORD dwParamLength = _tcslen( __targv[i] );
bool bIsEscaped=false;
if ( __targv[i][0] != _T('/') ){
index++;
}else{
if( dwParamLength > 1 && ( __targv[i][1] == _T('/') ) ){
bIsEscaped=true;
index++;
}
}
if ( index == n )
{
argvIndex = i;
return bIsEscaped ? ( __targv[i] + sizeof(__targv[i][0]) ) : __targv[i];
}
}
return NULL;
}
// Gets the arguments parameter
void GetRemoteCommandArguments( LPTSTR lpszCommandArguments )
{
DWORD dwIndex = 0;
lpszCommandArguments[0] = _T('\0');
if ( GetNthParameter( 3, dwIndex ) != NULL )
for( int i = dwIndex; i < __argc; i++ )
{
DWORD dwParamLen = _tcslen( __targv[i] );
if ( (__targv[i][0] == '/') && (dwParamLen>1 && __targv[i][1] == '/') ){
_tcscat( lpszCommandArguments, __targv[i]+sizeof(__targv[i][0]) );
}else{
_tcscat( lpszCommandArguments, __targv[i] );
}
if ( i + 1 < __argc )
_tcscat( lpszCommandArguments, _T(" ") );
}
}
// Gets the remote machine parameter
LPCTSTR GetRemoteMachineName()
{
DWORD dwIndex = 0;
LPCTSTR lpszMachine = GetNthParameter( 1, dwIndex );
if ( lpszMachine == NULL )
// return NULL;
return lpszLocalIP;
if ( _tcsnicmp( lpszMachine, _T(" "), 2 ) == 0 )
return lpszLocalIP;
if ( _tcsnicmp( lpszMachine, _T("\\\\"), 2 ) == 0 )
return lpszMachine;
// If a dot is entered we take it as localhost
if ( _tcsnicmp( lpszMachine, _T("."), 2 ) == 0 )
return lpszLocalIP;
return NULL;
}
// Turns off the echo on a console input handle - Used for hiding password typing
BOOL EnableEcho( HANDLE handle, BOOL bEcho )
{
DWORD mode;
if ( !GetConsoleMode( handle, &mode ) )
return FALSE;
if ( bEcho )
mode |= ENABLE_ECHO_INPUT;
else
mode &= ~ENABLE_ECHO_INPUT;
return SetConsoleMode( handle, mode );
}
// Gets the password
BOOL PromptForPassword( LPTSTR lpszPwd )
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
DWORD dwRead = 0;
Out( _T("Enter Password: ") );
// Turn off echo
if ( EnableEcho( hInput, FALSE ) )
{
// Read password from console
::ReadConsole( hInput, lpszPwd, SIZEOF_BUFFER, &dwRead, NULL );
// Ignore ENTER (0x0D0A)
lpszPwd[max( dwRead-2, 0 )] = _T('\0');
// Turn echo on
EnableEcho( hInput, TRUE );
Out( _T("\n\n") );
}
else
{
//Console input doesn't support echo on/off
Out( _T("\n") );
Error( _T("Couldn't turn off echo to hide password chars.\n") );
}
return TRUE;
}
BOOL SetConnectionCredentials( BOOL bPromptForPassword )
{
// Check the command line
lpszPassword = GetParamValue( _T("pwd:") );
lpszUser = GetParamValue( _T("user:") );
if ( lpszUser != NULL && lpszPassword != NULL && !bPromptForPassword )
if ( _tcscmp( lpszPassword, _T("*") ) == 0 )
// We found user name, and * as password, which means prompt for password
bPromptForPassword = TRUE;
if ( bPromptForPassword )
{
// We found user name, and * as password, which means prompt for password
lpszPassword = szPassword;
if ( !PromptForPassword( szPassword ) )
return FALSE;
}
return TRUE;
}
// Establish Connection to Remote Machine
BOOL EstablishConnection( LPCTSTR lpszRemote, LPCTSTR lpszResource, BOOL bEstablish )
{
TCHAR szRemoteResource[_MAX_PATH];
DWORD rc;
// Remote resource, \\remote\ipc$, remote\admin$, ...
_stprintf( szRemoteResource, _T("%s\\%s"), lpszRemote, lpszResource );
//
// disconnect or connect to the resource, based on bEstablish
//
if ( bEstablish )
{
NETRESOURCE nr;
nr.dwType = RESOURCETYPE_ANY;
nr.lpLocalName = NULL;
nr.lpRemoteName = (LPTSTR)&szRemoteResource;
nr.lpProvider = NULL;
//Establish connection (using username/pwd)
rc = WNetAddConnection2( &nr, lpszPassword, lpszUser, FALSE );
switch( rc )
{
case ERROR_ACCESS_DENIED:
case ERROR_INVALID_PASSWORD:
case ERROR_LOGON_FAILURE:
case ERROR_SESSION_CREDENTIAL_CONFLICT:
// Prompt for password if the default(NULL) was not good
if ( lpszUser != NULL && lpszPassword == NULL )
{
Out( _T("Invalid password\n\n") );
SetConnectionCredentials( TRUE );
Out( _T("Connecting to remote service ... ") );
//Establish connection (using username/pwd) again
rc = WNetAddConnection2( &nr, lpszPassword, lpszUser, FALSE );
}
break;
}
}
else
// Disconnect
rc = WNetCancelConnection2( szRemoteResource, 0, NULL );
if ( rc == NO_ERROR )
return TRUE; // indicate success
SetLastError( rc );
return FALSE;
}
// Copies the command's exe file to remote machine (\\remote\ADMIN$)
// This function called, if the /c option is used
BOOL CopyBinaryToRemoteSystem()
{
if ( !IsCmdLineParameter(_T("c")) )
return TRUE;
TCHAR drive[_MAX_DRIVE];
TCHAR dir[_MAX_DIR];
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
TCHAR szRemoteResource[_MAX_PATH];
// Gets the file name and extension
_tsplitpath( lpszCommandExe, drive, dir, fname, ext );
_stprintf( szRemoteResource, _T("%s\\ADMIN$\\%s%s"), lpszMachine, fname, ext );
// Copy the Command's exe file to \\remote\ADMIN$
return CopyFile( lpszCommandExe, szRemoteResource, FALSE );
}
// Copies the Local Process Launcher Executable from Self Resource -> Copies to Current Path
BOOL ExtractLocalBinaryResource()
{
DWORD dwWritten = 0;
HMODULE hInstance = ::GetModuleHandle(NULL);
// Find the binary file in resources
HRSRC hLocalBinRes = ::FindResource(
hInstance,
MAKEINTRESOURCE(IDR_ProcComs),
_T("ProcComs") );
HGLOBAL hLocalBinary = ::LoadResource(
hInstance,
hLocalBinRes );
LPVOID pLocalBinary = ::LockResource( hLocalBinary );
if ( pLocalBinary == NULL )
return FALSE;
DWORD dwLocalBinarySize = ::SizeofResource(
hInstance,
hLocalBinRes );
GetCurrentDirectory(MAX_PATH , szLocalBinPath);
_stprintf( szLocalBinPath, _T("%s\\%s"), szLocalBinPath, ProcComs );
HANDLE hFileLocalBinary = CreateFile(
szLocalBinPath,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( hFileLocalBinary == INVALID_HANDLE_VALUE )
return FALSE;
WriteFile( hFileLocalBinary, pLocalBinary, dwLocalBinarySize, &dwWritten, NULL );
// Out( _T("File Written ...\n") );
// Sleep(10000);
CloseHandle( hFileLocalBinary );
return dwWritten == dwLocalBinarySize;
}
// Extracts the Service Executable from Self Resource -> Pushes to the remote machine
BOOL CopyServiceToRemoteMachine()
{
DWORD dwWritten = 0;
HMODULE hInstance = ::GetModuleHandle(NULL);
// Find the binary file in resources
HRSRC hSvcExecutableRes = ::FindResource(
hInstance,
MAKEINTRESOURCE(IDR_RemComSVC),
_T("RemComSVC") );
HGLOBAL hSvcExecutable = ::LoadResource(
hInstance,
hSvcExecutableRes );
LPVOID pSvcExecutable = ::LockResource( hSvcExecutable );
if ( pSvcExecutable == NULL )
return FALSE;
DWORD dwSvcExecutableSize = ::SizeofResource(
hInstance,
hSvcExecutableRes );
TCHAR szSvcExePath[_MAX_PATH];
_stprintf( szSvcExePath, _T("%s\\ADMIN$\\System32\\%s"), lpszMachine, RemComSVCEXE );
// Copy binary file from resources to \\remote\ADMIN$\System32
HANDLE hFileSvcExecutable = CreateFile(
szSvcExePath,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( hFileSvcExecutable == INVALID_HANDLE_VALUE )
return FALSE;
WriteFile( hFileSvcExecutable, pSvcExecutable, dwSvcExecutableSize, &dwWritten, NULL );
CloseHandle( hFileSvcExecutable );
return dwWritten == dwSvcExecutableSize;
}
// Installs and starts the remote service on remote machine
BOOL InstallAndStartRemoteService()
{
// Open remote Service Manager
SC_HANDLE hSCM = ::OpenSCManager( lpszMachine, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL)
return FALSE;
// Maybe it's already there and installed, let's try to run
SC_HANDLE hService =::OpenService( hSCM, SERVICENAME, SERVICE_ALL_ACCESS );
// Creates service on remote machine, if it's not installed yet
if ( hService == NULL )
hService = ::CreateService(
hSCM, SERVICENAME, LONGSERVICENAME,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
_T("%SystemRoot%\\system32\\")RemComSVCEXE,
NULL, NULL, NULL, NULL, NULL );
if (hService == NULL)
{
::CloseServiceHandle(hSCM);
return FALSE;
}
// Start service
if ( !StartService( hService, 0, NULL ) )
return FALSE;
::CloseServiceHandle(hService);
::CloseServiceHandle(hSCM);
return TRUE;
}
// Connects to the remote service
BOOL ConnectToRemoteService( DWORD dwRetry, DWORD dwRetryTimeOut )
{
TCHAR szPipeName[_MAX_PATH] = _T("");
// Remote service communication pipe name
_stprintf( szPipeName, _T("%s\\pipe\\%s"), lpszMachine, RemComCOMM );
SECURITY_ATTRIBUTES SecAttrib = {0};
SECURITY_DESCRIPTOR SecDesc;
InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&SecDesc, TRUE, NULL, TRUE);
SecAttrib.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttrib.lpSecurityDescriptor = &SecDesc;;
SecAttrib.bInheritHandle = TRUE;
// Connects to the remote service's communication pipe
while( dwRetry-- )
{
if ( WaitNamedPipe( szPipeName, 5000 ) )
{
hCommandPipe = CreateFile(
szPipeName,
GENERIC_WRITE | GENERIC_READ,
0,
&SecAttrib,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
break;
}
else
// Try Again
Sleep( dwRetryTimeOut );
}
return hCommandPipe != INVALID_HANDLE_VALUE;
}
// Fill the communication message structure
// This structure will be transferred to remote machine
BOOL BuildMessageStructure( RemComMessage* pMsg )
{
LPCTSTR lpszWorkingDir = GetParamValue( _T("d:") );
// Info
pMsg->dwProcessId = GetCurrentProcessId();
_tcscpy( pMsg->szMachine, szThisMachine );
// Cmd
if ( !IsCmdLineParameter(_T("c")) )
_stprintf( pMsg->szCommand, _T("%s %s"), lpszCommandExe, szArguments );
else
{
TCHAR drive[_MAX_DRIVE];
TCHAR dir[_MAX_DIR];
TCHAR fname[_MAX_FNAME];
TCHAR ext[_MAX_EXT];
_tsplitpath( lpszCommandExe, drive, dir, fname, ext );
_stprintf( pMsg->szCommand, _T("%s%s %s"), fname, ext, szArguments );
}
// Priority
if ( IsCmdLineParameter( _T("realtime") ) )
pMsg->dwPriority = REALTIME_PRIORITY_CLASS;
else
if ( IsCmdLineParameter( _T("high") ) )
pMsg->dwPriority = HIGH_PRIORITY_CLASS;
else
if ( IsCmdLineParameter( _T("idle") ) )
pMsg->dwPriority = IDLE_PRIORITY_CLASS;
else
pMsg->dwPriority = NORMAL_PRIORITY_CLASS; // default
// No wait
pMsg->bNoWait = IsCmdLineParameter( _T("nowait") );
if ( lpszWorkingDir != NULL )
_tcscpy( pMsg->szWorkingDir, lpszWorkingDir );
// Console Title
_stprintf( szConsoleTitle, _T("%s : %s"), lpszMachine, pMsg->szCommand );
SetConsoleTitle( szConsoleTitle );
return TRUE;
}
// Listens the remote stdout pipe
// Remote process will send its stdout to this pipe
void ListenRemoteOutPipeThread(void*)
{
HANDLE hOutput = GetStdHandle( STD_OUTPUT_HANDLE );
TCHAR szBuffer[SIZEOF_BUFFER];
DWORD dwRead;
for(;;)
{
if ( !ReadFile( hRemoteOutPipe, szBuffer, SIZEOF_BUFFER, &dwRead, NULL ) ||
dwRead == 0 )
{
DWORD dwErr = GetLastError();
if ( dwErr == ERROR_NO_DATA)
break;
}
// Handle CLS command, just for fun :)
switch( szBuffer[0] )
{
case 12: //cls
{
DWORD dwWritten;
COORD origin = {0,0};
CONSOLE_SCREEN_BUFFER_INFO sbi;
if ( GetConsoleScreenBufferInfo( hOutput, &sbi ) )
{
FillConsoleOutputCharacter(
hOutput,
_T(' '),
sbi.dwSize.X * sbi.dwSize.Y,
origin,
&dwWritten );
SetConsoleCursorPosition(
hOutput,
origin );
}
}
continue;
break;
}
szBuffer[ dwRead / sizeof(TCHAR) ] = _T('\0');
// Send it to our stdout
Out( szBuffer );
}
CloseHandle( hRemoteOutPipe );
hRemoteOutPipe = INVALID_HANDLE_VALUE;
::ExitThread(0);
}
// Listens the remote stderr pipe
// Remote process will send its stderr to this pipe
void ListenRemoteErrorPipeThread(void*)
{
TCHAR szBuffer[SIZEOF_BUFFER];
DWORD dwRead;
for(;;)
{
if ( !ReadFile( hRemoteErrorPipe, szBuffer, SIZEOF_BUFFER, &dwRead, NULL ) ||
dwRead == 0 )
{
DWORD dwErr = GetLastError();
if ( dwErr == ERROR_NO_DATA)
break;
}
szBuffer[ dwRead / sizeof(TCHAR) ] = _T('\0');
// Write it to our stderr
Error( szBuffer );
}
CloseHandle( hRemoteErrorPipe );
hRemoteErrorPipe = INVALID_HANDLE_VALUE;
::ExitThread(0);
}
// Listens our console, and if the user types in something,
// we will pass it to the remote machine.
// ReadConsole return after pressing the ENTER
void ListenRemoteStdInputPipeThread(void*)
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
TCHAR szInputBuffer[SIZEOF_BUFFER] = _T("");
DWORD nBytesRead;
DWORD nBytesWrote;
for(;;)
{
// Read our console input
if ( !ReadConsole( hInput, szInputBuffer, SIZEOF_BUFFER, &nBytesRead, NULL ) )
{
DWORD dwErr = GetLastError();
if ( dwErr == ERROR_NO_DATA)
break;
}
// Send it to remote process' stdin
if ( !WriteFile( hRemoteStdInputPipe, szInputBuffer, nBytesRead, &nBytesWrote, NULL ) )
break;
}
CloseHandle( hRemoteStdInputPipe );
hRemoteStdInputPipe = INVALID_HANDLE_VALUE;
::ExitThread(0);
}
// Start listening stdout, stderr and stdin
void ListenToRemoteNamedPipes()
{
// StdOut
_beginthread( ListenRemoteOutPipeThread, 0, NULL );
// StdErr
_beginthread( ListenRemoteErrorPipeThread, 0, NULL );
// StdIn
_beginthread( ListenRemoteStdInputPipeThread, 0, NULL );
}
// Connects to the remote processes stdout, stderr and stdin named pipes
BOOL ConnectToRemotePipes( DWORD dwRetryCount, DWORD dwRetryTimeOut )
{
TCHAR szStdOut[_MAX_PATH];
TCHAR szStdIn[_MAX_PATH];
TCHAR szStdErr[_MAX_PATH];
SECURITY_ATTRIBUTES SecAttrib = {0};
SECURITY_DESCRIPTOR SecDesc;
InitializeSecurityDescriptor(&SecDesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&SecDesc, TRUE, NULL, FALSE);
SecAttrib.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttrib.lpSecurityDescriptor = &SecDesc;;
SecAttrib.bInheritHandle = TRUE;
hRemoteOutPipe = INVALID_HANDLE_VALUE;
hRemoteStdInputPipe = INVALID_HANDLE_VALUE;
hRemoteErrorPipe = INVALID_HANDLE_VALUE;
// StdOut pipe name
_stprintf( szStdOut, _T("%s\\pipe\\%s%s%d"),
lpszMachine,
RemComSTDOUT,
szThisMachine,
GetCurrentProcessId() );
// StdErr pipe name
_stprintf( szStdIn, _T("%s\\pipe\\%s%s%d"),
lpszMachine,
RemComSTDIN,
szThisMachine,
GetCurrentProcessId() );
// StdIn pipe name
_stprintf( szStdErr, _T("%s\\pipe\\%s%s%d"),
lpszMachine,
RemComSTDERR,
szThisMachine,
GetCurrentProcessId() );