Talking about Win2K's service (original: refdom)

zhaozj2021-02-16  56

Original: Refdom (Refdom) Source: www.opengram.com Author: RefDomemail: refDom@263.nethomepage: www.opengram.com2002 / 7/25

I, summary II, about Win2K service III, service launch and closing basic procedure IV, service programming V, security VI for service, service management VII, ending

I, the service under Win NT is similar to the daemon below * NIX, and now more and more software begins to design a service form, after the XP is launched, it is very good to achieve multi-user switching, etc. Role. From the security perspective to watch WIN's service, there is therefore there are many topics, such as run permissions, running time, etc. This article introduces and talks about some things in WIN services, limited by level, and the content is not exquisite.

II, about Win2K service

Win32 Services consists of three parts: Service Application, Service Control Program (SCP), and Service Control Manager (SCM).

First, service control manager

Service Control Manager: Start when the system is started, is part of the WIN system, which is a remote procedure call (RPC) server. This is also the core of the WIN service system. SCM is primarily responsible for the following: • Maintaining the installed service database • Start service and drive service when system start or have commands • Enumerate installation services and drive • Maintain the service and drive status · Transmission control request Running service • Lock and unlock the service database SCM maintains the service database in the registry, located in: hkey_local_machine / system / currentcontrolset / services. The subkey under this is the installed service and driver service. The name of each subkey is the service name, specified by the CREATSERVICE function of the service security program when the installation is installed.

When the system is installed, the original database was created. This database contains device drivers when the system starts. Each service and driver in the database include: • Service type. Service execution is your own or other service sharing, whether it is a core driver or a file system driver. · Start type. The service or the drive service is automatically started when the system is started or whether it is started by the SCM to accept the control request. The start type also indicates whether the service is disabled. · Error control level. Indicates if the service or drive service starts failed error handling. · Execute the full path to the file. · Additional dependency information determines the correct order of startup. For services, this information includes the specified service that SCM needs to start before the service startup, the service belongs to the name of the load order group, and the service is started in the group. For driver services, this information includes a specified drive that needs to be started before the drive startup. · For services, there are additional account names and passwords. If you do not specify an account, the service uses the localsystem account. • For drivers, additional driver object names for I / 0 system loading device drivers. If the object name is not specified, the I / O system creates a default name on the driver name.

Second, the service control program

The Service Control Program (SCP) is a functional block for control a service application and a bridge between the service application with the Service Manager (SCM). The service control program can complete these actions: • If the service start type is Service_Demand_Start, then the service control program to start the service · Send control request to the service running service · The current status of the service of the query runs these actions to open a service object handle . · Service Start To start a service, the service control program uses the StartService function. If the database is locked, the StartService function will fail. If this is encountered, the service control program needs to wait and recall the startservice. You can query the status of the service database through QueryServiceLockStatus.

When the service control program starts a service, you can specify parameters passed to the service servicemain function via the startService function. When you create a new thread to perform servicemain, StartService is returned. The service control program can query the status of the activated service through the QueryServiceStatus function. DWCURrentState should be Service_Start_pend in the service_status structure initialization, and dwwaithint is a time interval of milliseconds, indicating that the service control program should wait for the QueryServiceStatus. When the initialization is completed, the service will change the status dwcurrentState to Service_Running.

If the service is in 80 seconds, the service control manager determines that the service has stopped responding and stopped the service.

If the program is starting the drive service, StartService will return after the device driver is complete.

· Service control request

The service control program sends a service that controls the request to be run through ControlService. This function specifies the HandleRex function that the control value passes to the specified service. This control value can be a user-defined code, or the following basic control code: • Stop service: service_control_stop • Suspension service: service_control_pause · Restore Service: Service_Control_Continue • Return to the Update Status Information: Service_Control_Interrogate

Each service can specify the control value it receives and processes. To determine which basic control value is received by the service, you can use the QueryServiceStatus function or specify service_control_interrogate to call the ControlService function. The DWControlsAccepted in the service_status structure returns whether the service can be stopped, paused, and recovered. All services can receive Service_Control_Interrogate.

The QueryServiceStatus function returns the most recent state of the specified service without obtaining the status of the service itself. Use service_control_interrogate control to call the ControlService function to determine if the status is current information.

Third, the service application

The service application is a server's main program, which is an executable code for one or more services. This will explain in detail in the programming program.

Basic processes of III, service start and close

When the system is started, the SCM starts all automatic start-up services and services dependent on these services. This service will also be started automatically if the service depends on the service depends on "Manual" (requires command to start). The loading order of the service is determined by these aspects: 1. Sequence of the group 2. Load order in a group 3. Each service relies on the service that the system executes the launch confirmation program (by the registry) when the service is completed. HKEY_LOCAL_MACHINE / System / CURRENTCONTROLSET / CONTROL BootVerificationProgram Value specified, this value is not available by default.). When the first user is logged in, the system will simply report successful startup. You can separately provide a startup confirmation program to check system issues and report launch status to SCM, use the NotifyBootconfigStatus function.

When the system is successfully launched, the system is cloned to save a database backup as a Last-KNown-Good (LKG) configuration. If the currently used database causes the system to start failed, you can use a backup to recover. The backed up database is saved in: HKEY_LOCAL_MACHINE / System / ControlSetxxx / Services. The xxx value is also saved in: hkey_local_machine / system / select / lastknowngood.

If the service_error_critical error is available when the service is automatically started, the SCM will restart the machine and use the LKG configuration. If the LKG configuration has been used, the startup will fail.

The ErrorControl value of the service in the registry represents how the SCM handles the service error. If the value is service_error_ignore (0) or not specified, the SCM only ignores the error and continues the boot of the service. If serivce_error_normal (1), the error reason is recorded in the event log. If the error is controlled for serivce_error_severe (2) or serivce_error_critical (3), the service reports the launch error. SCM records the event log, and calls the function SCREVERTOLASTKNOWNGOOD to switch the system registration to the LKG version, and then call the NTSHUTDOWNSYSTEM to restart the system. If the system has already used the LKG version, you will be directly restarted.

The LKG version is generated: SCM is required to determine this LKG configuration after the system startup phase is launched. By default, a successful launch includes successful launch of all services and a user's login. This is the failed startup if the serivce_error_severe (2) or serivce_error_critical (3) error exists in the service phase. If the SCM successfully completes the startup of the service, when a user is logged in, Winlogon calls the NotifyBootConfigStatus function Send a message to the SCM. In successfully launch all services, and receive NTINITIALIZEREGISTRY, SCM calls NtinitializeRegistry to save the current startup configuration information.

The third party can replace Winlogon's confirmation with its own definition, which can be determined by the program in the registry: KHLM / SYSTEM / CURRENTCONTROLSET / Control / BootVerificationProgam, which can be used to join the definition of the system successfully started. Start authentication programs By setting the HKLM / Software / Microsoft / Windows NT / CurrentVersion / WinLogon / ReportBootok for 0 to prohibit WinlifyBootConfigStatus calls. In this way, after the SCM starts the service, wait for this verification program to call the NotifyBootConfigStatus function to notify the login success, and then save the LKG configuration. The execution file of the SCM is: WINN / System32 / Service.exe, running in the console mode, the Winlogon process starts the SCM early in the system. Svcctrlmain is running next to the screen to blank, and runs before Winlogon load graphic identity and displays the login interface Gina.

SvcctrlMain first creates a synchronization event initialized by nonsignaled_A3752DX. After completing the steps that are ready to accept the SCP, the SCM sets this event to the Signaled state. The SCP confirms the SCM through the OpenSCManager function, which prevents SCM from touching the SCM before SCM initialization is completed by waiting for SVCCTRLEVENT_A3752DX.

SVCCTRLMAIN then calls the sccreateServicedb function to establish a SCM service database. It first reads the registry: HKLM / System / CurrentControlSet / Control / ServiceGrouporder / List content, list the service group name and their boot order, then search for HKLM / System / CurrentControlSet / Services, for each primary key Create an entry in the database database. The SCM itself belongs to the self-service and device driver, and labeled boot start and system boot drivers, that is, all marked as boot drivers and system boot drivers will be loaded before the SCM starts, and executes when the user mode process When starting, the Win32ExitWindowsEx function sends a message to the system process CSRSS, calls the CSRSS closure routine. CSRSS Traversal All Process Comrade They are shut down. Before the next process, the CSRSS waits for exiting each system process other than the SCM, waiting time is: hklm / .default / controlpanel / desktop / waittokillapptimeout, default for 20 seconds. When the CSRSS encounters the SCM process, it is notified that the SCM system is being closed and waits for the timeout specified for the SCM. When the system is initialized, the SCM registers its process ID to CSRSS through the RegisterServicesProcess function, and CSRSS recognizes SCM by using SCM's process ID. The timeout value of the SCM is: HKLM / System / CurrentControlSet / Control / WaitTokillServentimeout, default for 20 seconds.

SCM's Close Processor Send Close Notification Notifications When you apply to close a notification, you need to turn off the notification. SCM's SCSHUTDOWNALLSERVICES traverses the SCM database to find the service that requests to turn off the notification, and send closing notifications while recording waiting delay. After sending the closing notification, the service that SCM waits for notification exits or waits for timeout. If the service timeout does not exit, the SCM determines whether one or more services waiting to be exited have sent a message to the SCM, this message is to tell the SCM service progress in the closing process. If at least one service has progressed, SCM is waiting once within the latency waiting range. The SCM continues to wait for the loop until all services exit, or do not receive the progress of the service within the waiting delay range. When the SCM notifies the service relationship and wait for the service to exit, the CSRSS waits for SCM to exit. If the CSRSS waits for timeout, the SCM has not exited, and the CSRSS continues to close the process, so when the system is turned off, the service that is not successfully closed in the specified time is simply executed with the SCM.

IV, service programming

The service program is an executable code for one or more services. Service_win32_oen_process type created service can only be a service executable. The service can be configured to perform an account relationship with the local, main domain, or trust domain. A number of services can be included in the service code of the service_win32_share_process type.

A service must contain main, servicemain, and control processing functions

· Main function

Service is usually a console program, the entry point is the main function, and the main function gets parameters from the ImagePath value served in the registry. When the SCM starts the serving program, wait for the StartServiceCtrLDispatcher function. The rule is: • Service_win32_oen_process type service will call the StartServiceCtrldispatcher function from the main thread. You can fully initialize after the service is started. Service_win32_share_process type service, in the program, can be initialized in the main thread before the startServiceCtrldispatcher function call, as long as it takes less than 30 seconds. Otherwise, when the main thread calls StartServiceCtrldispatcher, you must create another thread to complete the public initialization. You can do separate initialization of each service in the servicemain function.

The StartServiceCtrlDispatcher function gets a service_table_entry structure for each service in the process. Each structure specifies the entry point of the service name and service. If the StartServiceCtrldispatcher function call is successful, the calling thread will not return until all the processes of all running services are terminated. SCM controls the request of this thread by named pipe. This thread is like a reporter (scheduler), completes the following tasks: • When the new service starts, create a new thread to call the appropriate entry • Call the appropriate handle function to operate service control request

When the SCM starts a service process, the StartServiceCtrLDispatcher function is called, which receives a single entry for a list of service portals or a single service process, and each entry point is identified by the service name of the entry communication. After suggesting that a named pipe is communicated with SCM, this function is in a loop waiting for the SCM command from the pipe. SCM sends a service launch command when the service is started. Every time the StartServiceCtrldispatcher function creates a service thread to call the service to call the service loop command. The StartServiceCtrlDispatcher function waits for commands from the SCM, stopping the power of the process after all processes of service threads and allowing process to clear the resource when leaving, will control the main function of the process. Service serviceMain function

The ServiceMain function is the entry point of the service.

When the service control program requires a new service, the SCM launches the service and sends a start request to the scheduler. The scheduler creates a servicemain function for a new thread executes the service. The servicemain function completes the following tasks: • Turn the registerServiceCtrlHandleRex function to the handle control request of the registration service, the return value is the status handle of the service, which can be used to notify the SCM service. · Complete initialization. If the initialization code is performed very short (less than 1 second), the initialization can be done directly in the servicemain function; if the initialization time is longer than 1 second, then call the setServiceStatus function, specify the service_start_pending service status and wait time in the service_status structure. When the initialization continues, the service should call SetServiceStatus to report progress. • When the initialization is completed, setServiceStatus is called, and the service status is used in the service_status structure to be service_running. · Complete service tasks, or, if there is no unresolved task, return. All status changes, all call setServiceStatus to report. • If an error occurs during the initialization or running of the service, the service should call setServiceStatus, specify the service_stop_pending status, if the clearance process is relatively long. Once cleared, set SetServiceStatus from the last termination thread, specify the service_stopped status. Be sure to specify DWSERVICESPECIFICEXITCODE and DWWIN32Exitcode to determine this error in the service_status structure.

· Service control processing function

Each service has a control process function: Handlerex function, which is controlled by the sender, and this function is executed when the service process accepts a control request. Whenever handlerex is called, the service must call the setServiceStatus function to report the service status to the SCM, regardless of whether the status of the service is changed.

The service control program can send a control request using the ControlService function. All services must accept and process the service_control_interrogate control code. You can agree or prohibit acceptance of other controls by SetServiceStatus. To receive the service_control_deviceevent control code, you must call the RegisterDeviceNotification function. The service can handle the user-defined control code. Control processing must return within 30 seconds, otherwise the SCM will return an error. If the service needs to complete a long task, you should create a new thread to complete this long task and return. This prevents the service from being hindered by control. When the user turns off the system, all control processing is to call the setServiceStatus Settings the service_accept_shutdown control code to receive the service_control_shutdown control code, which will be notified in sequence in the service database. By default, a service is usually about 20 seconds before the system is turned off. After the time is over, the system will turn off the process, regardless of whether the service is complete. Note that if the system stays in the shutdown status (not Restarted and Powered Down), the service is still running.

If the service takes time to clear, it can send a stop_pending status message, along with a wait time, so that the service controller knows how long it should be long before reporting the system service, no matter what, there is a service controller to wait Time to prevent service from staying in the shutdown status. To change this time limit, you can modify the waitTokillServentImeout value in HKEY_LOCAL_MACHINE / SYSTEM / CURRENTCONTROLSET / Control. V, the security of the service

Many of the characteristics of services have caused special care of it: Most services running security levels are logsystems that are higher than the administrator power; a service existence is usually caused by system crash, rights improvement, etc., such as DDE service issues; service Run by the system before the account is logged in, which is also the way you like Trojan. And many services provided are also particularly loved: Telnet service, Task service, remote registry operation, SNMP service, etc.

Security issues from the service come from these aspects:

1. The problem of the service application itself This security problem is caused by the service program itself, because most services run the accounts to localsystem, so these problems can usually be enhanced. For example: the permission of NetDDE service enhances the vulnerability; the privilege of Telnet service upgrades the vulnerability; processing buffer overflow in the SNMP service, allows the attacker to execute the command remotely with the System account permission. Some services are network services, listen to a TCP port, such as Telnet service, can make remote vulnerability, but some services are only local services, and they cannot be remotely utilized. They need to have a local account and then enhance the permissions.

2, the launch problem of the service is in service management, there are three ways to activate, automatic, manual and disable. The manual and prohibited start-up mode will not start the service directly. When needed, you need to manually start them. This is a very common understanding. But there are some problems here. Manual and prohibition methods do not completely ban a service run. If the service that is started in both ways is dependent on the service that is running automatically, then these services will be automatically run. This can be obtained from the startup process of the SCM above. And the service of the prohibition method can also operate manually. The SC tool provides the ability to delete the service, which can completely disable the existence of a service, but it needs to be used with caution. 3, the service account problem, because the service's Localsystem account has made the service have received a lot of care, so some security configurations describe the runtime permission of the service, run the service using other accounts. When the service is installed, specify the username and password through the CREATSERVICE function. The account content can be changed via ChangeServiceConfig. You can also get the username of the service object through QueryServiceConfig. When the service is started, SCM logs in with the service account. If the login is successful, the system will generate an access token to give the service process. The token will be interactively interactively obtained later. For example, a service is trying to open the pipe handle, the system is compared the service token and the security descriptor of the pipeline. The items in the registry contain a key ObjectName, which specifies the service run account. If you use other accounts to run the service, then in the registry: HKEY_LOCAL_MACHINE / Security / Policy / Secrets / _SC_ (Service Name) The password hash, which is the password with the account itself. The column is exactly the same. The things you can do here are more. The SCM does not maintain the password of the service user account. When the system changes the password, the SCM will not notify the SCM to change the password. If the password expires, or the password changes, the login fails, the service startup will fail.

4, the management problem of the service is very important in the application, and some services are dependent on each other, and many administrators are difficult to determine which services are needed. Which services can be turned off and disabled, from the simple introduction of services It is difficult to discriminate what work actually do. And now there is no ready-made service management. If the error is closed, it may cause the system to stop the system. Because the service management is not so easy, so it is convenient for some Trojans to make a service form to confuse victims.

VI, service management

It is difficult to determine their true use from the description of the service. For example, Storage Groveler Services, described as: "Scans Single Instancestorage (SIS) Volumes for Duplicate Files, and Points Duplicates Files To One Data Storage Point, Conservation Disk Space" What does it do? However, it is only used by the language remote installation service ( RIS), if you don't need to install it, you don't need this service.

To determine what this service is true, try this:

* Check more description details, in Microsoft TechNet's Windows 2000 Services (http://www.microsoft.com/technet/prodtechnol/windows/WIN2KSVC.ASP) * Check file description, by right-click the file and select Version View * Check the service's dependency * Check the port of the service open · How to know the file used by a service?

Understand a service, you need to understand the files used in this service. Typically, you can decide whether this service is needed by viewing the file it run. This batch file can come to view the file properties, which uses the Windows Resource Kit tool: reg.exe and dependends.exe:

@set imagePath = @ for / f "tokens = 3" %% a in ('REG Query HKLM / SYSTEM / CURRENTCONTROLSET / SERVICES /% 1 / V ImagePath 2 ^> NUL ^ | Find "ImagePath") Do @set ImagePath = %% a @ if defined imagePath (@echo dependencies for% imagePath%: @ call depends / a0f1c /oc:@cdep.tmp "% imagePath%" @ for / f "tokens = 1 delims =, Skip = 1"% % B in ('type ~ svcdep.tmp ^ | FindSTR / B / C: "," ^ | FINDSTR / V / C: "? ^ | sort') do @echo %% b @ del ~ svcdep.tmp 2 > NUL) Else (@echo '% 1' is not installed or is not a value)

Save the above content as svcdep.bat, then use the service name (short name) to start as a parameter, such as check the Replication service, enter svcdep.bat ntfrs:

You can see: dependencies for% systemroot% / system32 / ntfrs.exe: "c: /winnt/system32/dbghelp.dll" C: /winnt/system32/dnsapi.dll "C: / WinNT / System32 / Esent. "C: /Winnt/System32/gdi32.dll" "C: /Winnt/System32/kernel32.dll" "c: /winnt/system32/msvcrt.dll" "c: /winnt/system32/netapi32.dll" "c: /winnt/system32/netrap.dll" "c: /winnt/system32/NTDLL.DLL" "C: /Winnt/System32/NTDSAPI.DLL" "C: /Winnt/System32/NTFRS.EXE" "C : /Winnt/system32/rpcrt4.dll "" c: /winnt/system32/samlib.dll "" c: /winnt/system32/secur32.dll "c: /winnt/system32/user32.dll" "C: / Winnt / System32 / WLDAP32.DLL "" C: /Winnt/System32/ws2_32.dll "" C: /Winnt/System32/ws2help.dll "" c: /winnt/system32/wsock32.dll "can see it using it DNS (DNSAPI.DLL), Winsock (ws * .dll) and Remote Procedure Call (rpcrt4.dll) library, not only let you know what the service will do, but also let you know what it needs.

Nowadays, many software, especially security software, began to register into services. For example, Norton will write a lot of services, in addition to understanding a service actual work, maintaining a service list is also very important. Regularly check the service list, what changes are there, is a good idea. SC is a good tool, there is also a similar program (including source code) on my home page www.opengram.com. To know the specific management of the service, you can go to the Microsoft website to see, you can go here: http://www.plasma-online.de/index.html? Content = http% 3A // www.plasma-online.de / ENGLISH / HELP / SOLUTIONS / NT4_SERVICES.HTML

It is not impossible to use this service without a service. For example, for Telnet services, I used to write it before opentelnet that turned it when the service was forbidden. To completely ban the service, it is best to delete it directly, or replace the service application.

VII, end

Although there are so many, in fact, control services are basically required. Therefore, manage your own administrator is an important aspect of maintaining service security.

(Finally completed the length of this entrained copy, translation, and leisurely lengthy eight shares, shit.)

转载请注明原文地址:https://www.9cbs.com/read-20995.html

New Post(0)