Service control manager windows 2003 server

After you install Windows Server 2003 Service Pack 1, non-administrators have limited access to the Service Control Manager.

Symptoms

After you install Microsoft Windows Server 2003 Service Pack 1 (SP1), non-administrators cannot remotely access the Service Control Manager.

Cause

Windows Server 2003 SP1 changes the Service Control Manager default security settings.

Resolution

To resolve this issue, use version 5.2.3790.1830 of the Sc.exe tool. This tool is located in the %windir%System32 folder. To do this, follow these steps:

  1. Click Start, click Run, type cmd, and then click OK.

  2. Type the following command at the command prompt, and then press ENTER:

    sc sdset SCMANAGER D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

Need more help?

If you have been previously operating a Windows NT Server-based network and make the plunge to Windows Server 2003, you will find that the two network operating systems are very different from each other. These differences are more than just the underlying architecture and the new features in the newer operating system. The entire way you’re used to do doing things in Windows NT has changed as well. Here’s how you can accomplish some of the more common administrative tasks in Windows 2003, as opposed to the methods used to accomplish the same task in Windows 2000.

User Manager for Domains
In a Windows NT Server environment, one of the most heavily used tools is the User Manager for Domains. While Windows NT uses this tool to create, edit, and delete user accounts, the tool simply does not exist in Windows Server 2003. Remember that Windows Server 2003 is Active Directory based. Since all user information is stored in the Active Directory, you must use a completely different set of tools for working with user accounts.

In Windows Server 2003, the tool that’s used for working with user accounts is called Active Directory Users And Computers. Besides managing user accounts, this tool has other uses that I will discuss later on.

You can access the Active Directory Users And Computers console by clicking the Start button and selecting the All Programs | Administrative Tools | Active Directory Users And Computers commands. When the console opens, expand the container designated by your domain name and, beneath it, you will find a Users container. If you select the Users container, you will see a list of all of the user accounts and security groups for the domain.

The biggest thing to remember when working with user management in Windows Server 2003 is that the right mouse button plays a much more important role than it did in Windows NT. Practically all of the user management functions involve the right mouse button. For example, if you right-click on the Users container, you will see a shortcut menu. One of the commands on this menu is New. You can use this command to create a new user or group.

If you wish to delete a user, select the actual user account or accounts that you want to delete, click the right mouse button and select the Delete command from the resulting shortcut menu.

The shortcut menu for a user account contains many other handy functions. For example, you can use it to enable, disable, or rename the account. If you need to reset a password, you must also right-click on a user account, and select the Reset Password command from the resulting shortcut menu. Another cool shortcut menu command is the Move command. In Windows NT, there was no easy way to move user accounts or groups from one domain to another. However, using the Move command, you can move users and groups between domains or organizational units.

As you can see, most of the Windows NT user account management features are accessible through a simple right click. However, if you want more detailed control over a user or group, right-click on the desired user or group and select the Properties command from the shortcut menu. This will open the user or group’s properties sheet. If you look at the properties sheet for a user, you’ll have access to everything from the user’s personal information (name, phone number, etc.) to the user’s group memberships to the user’s terminal services and remote control settings.

Server manager
In Windows NT, Server Manager is used primarily for viewing which computers are a part of the domain, seeing which resources within the domain are in use, and promoting BDCs. As you might have already guessed, though, Server Manager doesn’t exist in Windows Server 2003.

First, let’s address the PDC / BDC issue. In a Windows Server 2003 environment, there is no such thing as a PDC or a BDC. While it’s true that one server in each domain functions as a PDC emulator and that server roles make some domain controllers a little more important than others, there is no all powerful PDC.

Instead, Windows Server 2003 simply has domain controllers and member servers. You can use the DCPROMO command to turn a member server into a domain controller or to turn a domain controller into a member server. In Windows NT, if you wanted to make such a switch, you had to reinstall Windows.

Windows Server 2003 uses what’s known as multimaster replication. This means that when someone makes an Active Directory level change, such as creating a user account, the change doesn’t have to be written to the PDC. The change can be written to any domain controller and is then replicated to the other domain controllers at a later time.

Another server function that has changed since Windows NT is setting up computer accounts. In Windows NT, you would either manually create a computer account through Server Manager or you would join the domain when installing Windows NT workstation. In Windows Server 2003, a computer can still join the domain during Windows installation, so long as the workstation is running Windows NT, 2000, or XP.

If you want to manually create a computer account, though, you must return to the Active Directory Users And Computers console. To create a computer account, simply right-click on the Computer container beneath the domain and then select the New | Computer commands. Windows will then prompt you for the name of the computer and will create the computer account in the Computers container. You can also create a computer account within an Organizational Unit (OU) if you so desire.

Still another function of Server Manager is to allow you to see shared resources, sessions, and open files. In Windows Server 2003, this task is accomplished through the Computer Management console. This console is found on the server’s Administrative Tools menu. When the console opens, navigate through the console tree to System Tools | Shared Folders. If you expand the Shared Folders container, you will see sub containers named Shares, Sessions, and Open Files. These containers display the same type of information as the Windows NT Server Manager does. Keep in mind, though, that the information that you are viewing is static. If you want to refresh the information, you must click the Refresh icon or press the [F5] key.

In Windows NT, the Server Manager allowed you to view usage information for any computer in the domain, assuming that you had the appropriate rights. By default though, the Windows Server 2003 Computer Management console displays only the share and usage information for the local machine. If you want to view this information for other computers, you must right-click on the Computer Management (Local) container in the console tree, and then select the Connect To Another Computer command from the resulting shortcut menu.

Trust relationships
Another function that has changed greatly since Windows NT is trust relationships. In Windows NT, if you wanted for one domain to trust another, you would have to go into User Manager for Domains and create a trust relationship between the domains.

In Windows NT, the trusts could be confusing because you could have a one-way trust and two-way trust, and there was no such thing as an implicit trust. If you had a hundred domains and you wanted all of them to trust each other, you would have to create thousands of trusts.

In Windows Server 2003, though, this has changed. All Active Directory domains are organized into a forest. All domains within a forest trust every other domain in the forest automatically. The only way that you would ever have to manually create a trust relationship in Windows Server 2003 is if you wanted to create a trust between forests.

Creating a trust between forests is similar to creating a trust between Windows NT domains. You can create either a one-way or a two-way trust and there is no such thing as an implicit trust relationship between multiple forests.

If you wanted to create a trust relationship between forests, you would use a tool called Active Directory Domains And Trusts. However, creating a trust between forests is an involved procedure that requires a lot of planning. The procedure is beyond the scope of this article.

System policies
In Windows NT, there are three basic types of system policies. First, there are the user policies. These involve user names and passwords. Second, there are trust relationship policies, which I just discussed. The third type of policy is an audit policy. Audit policies allow you to compile a security log of specific user actions.

Security auditing still exists within Windows Server 2003, and as with Windows NT, you can read the security logs through the Event viewer. However, the method used to create an audit policy differs widely between Windows NT and Windows Server 2003.

Windows Server 2003 makes use of something called group policies. Group policies are a huge collection of security settings, of which audit policies are only a tiny part. Group policies allow you to define events for auditing, but they also allow you to do things like control the minimum password length or which applications that a user is allowed to run.

Group policies are a huge topic, and it would be possible to write an entire book on them. I do want to take a moment and show you basically how they work, though, particularly as they relate to auditing.

The first thing that you need to know about group policies is that they are hierarchical in nature. Group policies can be applied at a variety of levels. The lowest level is the policy that applies to the local machine. From there, additional policies may be applied at various levels of the Active Directory, such as at the site level, OU level, and domain level. Therefore, it’s possible that several policies will apply to a single user or computer. Because of this, the various applicable policies are rolled into a single policy known as the Resultant Set of Policy. This process resolves conflicts between the various policies and establishes the final security policy for the user or the computer. (Policies can be applied to a user, computer, or both).

To access the group policies, you must open the Group Policy Editor. Normally, you would do this by entering the MMC command at the Run prompt. This will open an empty Microsoft Management Console. Next, select the Add / Remove Snap In command from the console’s File menu to reveal the Add / Remove Snap In dialog box. When this dialog box appears, click the Add button and you will see a list of available snap-ins. Select the Group Policy Object Editor, and click Add. Windows will now prompt you as to which group policy object you wish to edit. Make your selection and click Finish, Close, and OK.

You will now see the Group Policy that you have selected. The first thing that you will notice as you navigate through the console is that there are distinct sections for Computer Settings and for User Settings. There are Audit-related policy elements scattered throughout the group policy. If you want to see one, though, navigate through the console tree to Computer Policy | Windows Settings | Security Settings | Local Policies | Audit Policy. This section allows you to audit things like logon events and account management. Keep in mind, though, that these settings apply at the computer level. There is an entirely different group of settings for the user level configuration.

Outside of the Group Policies, you can also audit objects, such as files and folders (assuming that the files exist on an NTFS partition). To do so, right-click on a file and select the Properties command from the resulting shortcut menu. When you see the file’s properties sheet, select the Security tab and click the Advanced button. This will cause Windows to display the Advanced Security Settings properties sheet for the file. You can use this properties sheet’s Auditing tab to configure auditing for the file or printer.

System Properties
The System Properties sheet has also really evolved since Windows NT. In Windows NT, if you right-click on the My Computer icon and select the Properties command from the resulting shortcut menu, you will see the System Properties sheet. In Windows Server 2003, you still access the System Properties sheet in the same manner, but the sheet has changed considerably.

In Windows NT, the System Properties sheet had six tabs; Startup / Shutdown, Hardware Profiles, User Profiles, General, Performance, and Environment.

In Windows Server 2003, the General tab still exists and is almost identical to its Windows NT counterpart. In Windows NT, the Performance tab contains settings that allow you to adjust application performance and virtual memory. In Windows 2003, though, you must go to the Advanced tab, click the Settings button in the Performance section, and then select the Advanced tab found on the Performance Options properties sheet. As you might have guessed, there have been a lot of other performance modification mechanisms added as well.

The Windows NT Environment tab contains a listing of your environment variables. To access this same information in Windows 2003, you must click the Environment Variables button at the bottom of the Advanced tab.

In Windows NT, there is a Hardware Profiles tab that allows you to view any hardware profiles present on the machine. In Windows Server 2003, there is an entire Hardware tab, of which Hardware Profiles is only a small part. This tab also contains the Device Manager, the Add Hardware Wizard, and a button for driver signing.

The Windows NT User Profiles tab allows you to see any user profiles that are currently available. In Windows Server 2003, these profiles are available through the User Profiles section of the Advanced tab.

Finally, the Startup / Shutdown tab allows you to control the various Windows boot options and what happens when the system crashes. These settings are found in the Startup and Recovery sections of Windows 2003’s Advanced tab.

Service Control Manager
Although not really an administrative tool, I wanted to take a moment and mention the Service Control Manager. In Windows NT Server, the Service Control Manager is used to stop and start system services. If you wanted to access the Service Control Manager, you would simply go into the Control Panel and double-click the Services icon and Windows would launch the Service Control Manager.

The Service Control Manager still exists in Windows Server 2003, but has evolved over time. Now, the Services icon is on the Administrative Tools menu instead of being a part of the Control Panel.

If you open the Service Control Manager, you will find that like just about everything else in Windows 2003, it is console based. The column to the right contains a list of available services and their current status. You can right-click on a service to access a shortcut menu that allows the service to be started or stopped. The menu also contains a Properties command. Selecting the Properties command displays a service properties sheet. This properties sheet displays all of the service’s dependencies—something that would have been nice to have had in Windows NT.

Everything’s constant but change
As you can see, Windows NT differs significantly from Windows Server 2003. You can almost forget everything you knew about administering a Windows NT network when administering Windows Server 2003. However, once you figure out what tasks are done with the new tools, you’ll quickly become as efficient with Windows Server 2003 as you were with Windows NT.

Рассмотрим особенности предоставления прав удаленного доступа к списку служб, запущенных на сервере, доменным пользователем, у которых отсутствуют права локальных администраторов. По сути задача сводится к предоставлению доступа на удаленное подключение к интерфейсу диспетчера управления службами — Service Control Manager (SCManager).

Как выглядит проблема. Допустим, мы хотим, чтобы удаленный пользователь / или система мониторинга могли опрашивать состояние служб на некоем сервере. По понятным причинам этот удаленный пользователь не имеет прав административных права и права на локальный вход на сервер.

При попытке подключиться и получить список служб на удаленном компьютере с помощью консоли services.msc, пользователь получает ошибку:

Windows was unable to open service control manager database on computer_name

Error 5: Access is denied.

Windows was unable to open service control manager database on computer_name Error 5: Access is denied.Если же попробовать вывести список служб на удаленном сервере с помощью утилиты sc.exe, ошибка такая:

C:Windowssystem32>sc \obts-01 query

[SC] OpenSCManager FAILED 5:
Access is denied.

[SC] OpenSCManager FAILED 5: Access is denied.Возможность получить доступ к списку служб контролируется дескриптором безопасности базы данных Service Control Manager, удаленный доступ к которой для пользователей “Authenticated Users” был ограничен еще в Windows 2003 SP1 (что, в общем-то, логично). Права на удаленный доступ к данной службе есть только у членов группы локальных администраторов.

Рассмотрим, как предоставить удаленный доступ к диспетчеру Service Control Manager для получения списка служб сервера и возможность получения их статусов обычным пользователям (без прав администратора) на примере Windows Server 2012 R2.

Текущие разрешения менеджера сервисов (SCM) можно получить с помощью утилиты sc.exe, выполнив в командной строке, запущенной с правами администратора:

sc sdshow scmanager

Команда вернет примерно такую SDDL строку:

D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)(A;;CC;;;AC)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

sc sdshow scmanagerВ данном случае видно, что по умолчанию группе Authenticated Users (AU) разрешено только подключаться в SCM, но не опрашивать (LC) службы. Скопируйте строку в окно любого тестового редактора.

Следующий этап – получение SID пользователя или группы, которой мы хотим предоставить удаленный доступ к SCM (Как получить SID пользователя по имени). К примеру, получим SID AD группы msk-hd так:

Get-ADgroup -Identity 'msk-hd' | select SID

SID
---
S-1-5-21-2470146451-3958456388-2988885117-23703978

В текстовом редакторе в SDDL строке нужно скопировать блок (A;;CCLCRPRC;;;IU) – (IU – означает Interactive Users)), заменить в скопированном блоке IU на SID пользователя/группы и вставить полученную строку перед S:.

В нашем случае получилась такая строка:

D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)(A;;CC;;;AC)(A;;CCLCRPRC;;;S-1-5-21-2470146451-3958456388-2988885117-23703978)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

А теперь с помощью sc.exe изменим параметры дескриптора безопасности Service Control Manager:

sc sdset scmanager “D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)(A;;CC;;;AC)(A;;CCLCRPRC;;;S-1-5-21-2470146451-3958456388-2988885117-23703978)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)“

sc sdset scmanagerСтрока [SC] SetServiceObjectSecurity SUCCESS говорит о том, что новые параметры безопасности успешно применены, и мы выдали пользователю правам, аналогичные права локально аутентифицированных пользователей: SC_MANAGER_CONNECT, SC_MANAGER_ENUMERATE_SERVICE, SC_MANAGER_QUERY_LOCK_STATUS и STANDARD_RIGHTS_READ.

Проверим, что теперь удаленный пользователь может получать список служб и их статус с помощью консоли управления службами (services.msc) и с помощью запроса sc \server-name1 query

Удаленное подключение к списку службПрава на управление запущенными службами при этом, естественно, отсутствуют, т.к. доступ к каждой службе контролируется индивидуальной ACL. Чтобы предоставить пользователю права на запуск/остановку служб сервера нужно воспользоваться инструкциями из статьи Предоставление прав пользователю на управление (запуск, остановку, перезапуск) службами Windows.

Совет. При назначении прав на SCManager, отличных от стандартных, они сохраняются в ветке HKLMSYSTEMCurrentControlSetControlServiceGroupOrderSecurity. И если при формировании SDDL строки была допущена ошибка, сбросить текущие разрешения на дефолтные можно простым удалением этой ветки и перезагрузкой.HKLMSYSTEMCurrentControlSetControlServiceGroupOrderSecurity

Allowing non-administrators rights for service control sounds deceptively simple, but unfortunately it’s not. After Windows Server 2003 SP1, the default rights are very focused on administrator-only access for service control.

This post describes how to view and modify the security descriptor for the Service Control Manager (SCM) and individual services as required.

Show the descriptor for SCM:
sc sdshow SCMANAGER

D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

In this case, the output shows that by default, Authenticated Users (AU) only have connect, but not enumerate (LC) for SCM.

If you want to allow a non-administrator to connect to the Service Control Manager and enumerate the services, you can modify the security descriptor by using something like the following command to add enumerate, read control and query lock status for Authenticated Users with SCM:
sc sdset SCMANAGER

D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)

This allows connecting to the SCM and enumerating services. However, if the DACL on the individual services only allows administrators access to the services, then they still won’t be accessible. You’ll need to run specific ‘sc sdset’ commands against particular services, or use subinacl to change all services with one command.

Note that the sc.exe version with XP does not support this syntax – use the sc.exe on 2003 server.

For individual services, you could then allow query and interrogate with the following command:

subinacl /service \server* /grant=domainuser=QSI

Note that to map the ACE flags to the meaning with regards to service control, I went through the following process:

  1. Find the access rights from the flag, eg CC = SDDL_CREATE_CHILD = ADS_RIGHT_DS_CREATE_CHILD (ACE Strings link below)
  2. Find the constant matching this value, eg. 0x1 (ADS_RIGHTS_ENUM Enumeration link below)
  3. Match this to the SCM access right for the hexadecimal value, eg. 0x1 = SC_MANAGER_CONNECT (Service Security and Access Rights link below)

Map between sdshow output, right, hex value and SC/service meaning:


"CC"  ADS_RIGHT_DS_CREATE_CHILD          = 0x1,    SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG
"DC"  ADS_RIGHT_DS_DELETE_CHILD          = 0x2,    SC_MANAGER_CREATE_SERVICE, SERVICE_CHANGE_CONFIG
"LC"  ADS_RIGHT_ACTRL_DS_LIST            = 0x4,    SC_MANAGER_ENUMERATE_SERVICE, SERVICE_QUERY_STATUS
"SW"  ADS_RIGHT_DS_SELF                  = 0x8,    SC_MANAGER_LOCK, SERVICE_ENUMERATE_DEPENDENTS
"RP"  ADS_RIGHT_DS_READ_PROP             = 0x10,   SC_MANAGER_QUERY_LOCK_STATUS, SERVICE_START, 
"WP"  ADS_RIGHT_DS_WRITE_PROP            = 0x20,   SC_MANAGER_MODIFY_BOOT_CONFIG, SERVICE_STOP
"DT"  ADS_RIGHT_DS_DELETE_TREE           = 0x40,   SERVICE_PAUSE_CONTINUE
"LO"  ADS_RIGHT_DS_LIST_OBJECT           = 0x80,   SERVICE_INTERROGATE
"CR"  ADS_RIGHT_DS_CONTROL_ACCESS        = 0x100   SERVICE_USER_DEFINED_CONTROL
"RC"  READ_CONTROL                       = 0x20000 READ_CONTROL

Access right Description for services and SCM:


SERVICE_QUERY_CONFIG (0x0001) Required to call the QueryServiceConfig and QueryServiceConfig2 functions to query the service configuration. 
SERVICE_CHANGE_CONFIG (0x0002) Required to call the ChangeServiceConfig or ChangeServiceConfig2 function to change the service configuration. Because this grants the caller the right to change the executable file that the system runs, it should be granted only to administrators.  
SERVICE_QUERY_STATUS (0x0004) Required to call the QueryServiceStatusEx function to ask the service control manager about the status of the service. 
SERVICE_ENUMERATE_DEPENDENTS (0x0008) Required to call the EnumDependentServices function to enumerate all the services dependent on the service. 
SERVICE_START (0x0010) Required to call the StartService function to start the service. 
SERVICE_STOP (0x0020) Required to call the ControlService function to stop the service. 
SERVICE_PAUSE_CONTINUE (0x0040) Required to call the ControlService function to pause or continue the service. 
SERVICE_INTERROGATE (0x0080) Required to call the ControlService function to ask the service to report its status immediately. 
SERVICE_USER_DEFINED_CONTROL(0x0100) Required to call the ControlService function to specify a user-defined control code. 
SERVICE_ALL_ACCESS (0xF01FF) Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights in this table. 
READ_CONTROL Required to call the QueryServiceObjectSecurity function to query the security descriptor of the service object. 

SC_MANAGER_CONNECT (0x0001) Required to connect to the service control manager. 
SC_MANAGER_CREATE_SERVICE (0x0002) Required to call the CreateService function to create a service object and add it to the database. 
SC_MANAGER_ENUMERATE_SERVICE (0x0004) Required to call the EnumServicesStatusEx function to list the services that are in the database. 
SC_MANAGER_LOCK (0x0008) Required to call the LockServiceDatabase function to acquire a lock on the database. 
SC_MANAGER_QUERY_LOCK_STATUS (0x0010) 
SC_MANAGER_MODIFY_BOOT_CONFIG (0x0020) Required to call the NotifyBootConfigStatus function. 
SC_MANAGER_ALL_ACCESS (0xF003F) Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. 

Directory service object access rights


"RC"  SDDL_READ_CONTROL  READ_CONTROL 
"RP"  SDDL_READ_PROPERTY  ADS_RIGHT_DS_READ_PROP  
"WP"  SDDL_WRITE_PROPERTY  ADS_RIGHT_DS_WRITE_PROP  
"CC"  SDDL_CREATE_CHILD  ADS_RIGHT_DS_CREATE_CHILD  
"DC"  SDDL_DELETE_CHILD  ADS_RIGHT_DS_DELETE_CHILD  
"LC"  SDDL_LIST_CHILDREN  ADS_RIGHT_ACTRL_DS_LIST  
"SW"  SDDL_SELF_WRITE  ADS_RIGHT_DS_SELF  
"LO"  SDDL_LIST_OBJECT  ADS_RIGHT_DS_LIST_OBJECT  
"DT"  SDDL_DELETE_TREE  ADS_RIGHT_DS_DELETE_TREE  
"CR"  SDDL_CONTROL_ACCESS  ADS_RIGHT_DS_CONTROL_ACCESS  

ADS enum:


typedef enum  {
  ADS_RIGHT_DS_CREATE_CHILD          = 0x1,
  ADS_RIGHT_DS_DELETE_CHILD          = 0x2,
  ADS_RIGHT_ACTRL_DS_LIST            = 0x4,
  ADS_RIGHT_DS_SELF                  = 0x8,
  ADS_RIGHT_DS_READ_PROP             = 0x10,
  ADS_RIGHT_DS_WRITE_PROP            = 0x20,
  ADS_RIGHT_DS_DELETE_TREE           = 0x40,
  ADS_RIGHT_DS_LIST_OBJECT           = 0x80,
  ADS_RIGHT_DS_CONTROL_ACCESS        = 0x100 

} ADS_RIGHTS_ENUM;

READ_CONTROL = 0x20000;


References:

Applying Security Descriptors on the Device Object
http://msdn.microsoft.com/en-us/library/ms793368.aspx

Non-administrators cannot remotely access the Service Control Manager after you install Windows Server 2003 Service Pack 1
http://support.microsoft.com/default.aspx?scid=kb;EN-US;907460

Securing a Remote WMI Connection
http://msdn.microsoft.com/en-us/library/aa393266(VS.85).aspx

Configuring a Report Server for Remote Administration
http://msdn.microsoft.com/en-us/library/ms365170(SQL.90).aspx

Service Security and Access Rights
http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx

How to grant users rights to manage services in Windows 2000
http://support.microsoft.com/kb/288129

How to troubleshoot WMI-related issues in Windows XP SP2
http://support.microsoft.com/kb/875605

ACE Strings
http://msdn.microsoft.com/en-us/library/aa374928(VS.85).aspx

ADS_RIGHTS_ENUM Enumeration
http://msdn.microsoft.com/en-us/library/aa772285(VS.85).aspx

Wayne’s World of IT (WWoIT), Copyright 2009 Wayne Martin. 

  • Remove From My Forums
  • Question

  • Hi,

    I’m trying to setup a VPN server using RRAS on a windows server 2003 with one nic card. I did the following steps instructed here  http://support.microsoft.com/kb/323441/en-us.

    But when I’m in the part of » The Routing and remote access service has now been installed. Do you want to start the service?» Then I clicked yes but there will be a dialog box stating » An error occurred while trying to start the routing and remote
    access service on server. for more information about the error, see event viewer.

    This is the content of the error

    Event Type: Error

    Event Source: Service Control Manager
    Event Category: None
    Event ID: 7024
    Date: 11/5/2012
    Time: 11:45:35 AM
    User: N/A
    Computer: server
    Description:
    The Routing and Remote Access service terminated with service-specific error 2147500037 (0x80004005).

    For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

    I can’t figure out how to solved this one I tried using «sc query remoteaccess»

    C:>sc query remoteaccess

    SERVICE_NAME: remoteaccess
            TYPE               : 110  WIN32_OWN_PROCESS  (interactive)
            STATE              : 1  STOPPED
                                    (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN))

            WIN32_EXIT_CODE    : 1066  (0x42a)
            SERVICE_EXIT_CODE  : -2147467259  (0x80004005)
            CHECKPOINT         : 0x0
            WAIT_HINT          : 0x0

    This is the result I got.

Answers

  • Hi MYousuAli,

    Thank you. Unfortunately we decided to do a fresh installation of the server to hasten the process of building a VPN server. If ever I encounter this problem again I will make a thorough investigation. 

    Regards,

    Carlo

    • Marked as answer by

      Wednesday, November 7, 2012 5:47 AM

Приверженцам командной строки нравится возможность управлять службами Windows с помощью приглашения командной строки на ввод, но до недавнего времени в нашем распоряжении были лишь команды Net Start, Net Pause, Net Continue и Net Stop, то есть «запустить», «приостановить», «продолжить» и «остановить» работу сетевой службы.

Если есть желание узнать больше о службах, запускаемых с командной строки, необходимо исследовать возможности инструмента SC (sc.exe), который реализован в операционной системе Windows XP и более новых версиях.

Как он выглядит?

Команды SC задаются в соответствии со следующей структурой:

sc [] []

где необязательный параметр servername просто указывает на систему, в которой будет выполняться команда, параметр command — это особая подкоманда SC (например, pause, start, create, delete), параметр servicename — внутреннее имя службы, а параметр options относится к любым ключам, которых требует подкоманда. Простой пример:

sc server1 stop Lanmaserver

подключается к системе server1 и останавливает службу сервера, имеющую внутреннее служебное имя lanmanserver. Если нужно остановить службу сервера локально, параметр servername лучше опустить.

Внутреннее имя

Как видно из примера, необходимо знание внутреннего имени службы. Если предположить, что высвечиваемое имя для службы файлового сервера — Server, и попробовать команду

sc stop server

SC выдаст ошибку. Работает только параметр lanmanserver. Внутреннее имя также называется key name, потому что lanmanserver — это наименование раздела реестра внутри HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices, где операционная система Windows хранит информацию об этой особой службе. Если известно более приемлемое отображаемое имя, такое как Server для службы файлового сервера или DNS для службы сервера DNS Server, можно использовать команду getkeyname для преобразования отображаемого имени в ключевое имя. Например, чтобы найти ключевое имя для службы сервера DNS Server, можно задействовать команду

sc getkeyname

Выполнение этой команды покажет, что ключевое имя службы сервера DNS Server — DNS. Кстати, для SC это значения не имеет. Данный процесс можно пускать в обратном порядке и по ключевому имени получать более подходящее отображаемое имя при помощи команды getdisplayname.

Как он работает?

Диспетчер SC имеет четыре команды, которые соответствуют упомянутым выше сетевым командам: start, stop, pause и continue. Например, чтобы приостановить работу службы сервера, можно ввести

sc pause server

Команда SC stop ведет себя несколько иначе, чем в оснастке MMC (Microsoft Management), и не так, как команда Net Stop, которая понимает, что служба Computer Browser зависит от службы сервера. Оснастка и команда Net Stop спрашивают, нужно ли остановить работу службы Computer Browser, в то время как SC просто не выполнит операцию с сообщением

A stop control has been sent to a service that other running services are dependent on

Другими словами, в этом примере SC действует не так «разумно», как другие команды.

Однако с помощью команды enumdepend можно определить, какие еще службы зависят от данной службы:

sc enumdepend Lanmanserver

В ответ SC представит отчет о том, что служба DNS и служба браузера зависят от службы сервера. Но эта информация будет в кратком формальном виде. Например, можно использовать команду query, чтобы запросить службу о ее текущем состоянии. Запрос службы сервера

sc query Lanmanserver

возвращает информацию, которая показана на экране. Это основной способ вывода информации диспетчером SC о работе службы.

Создание служб

Рассмотрим одну из подкоманд диспетчера служб — ту, что позволяет создавать новые службы.

Предположим, нам необходимо установить новую службу, которая каждые несколько минут перехватывает изображения Web-камеры и отправляет их по определенному адресу. Эта служба распространяется бесплатно и не имеет хорошей документации. Все, что о ней известно, — это название wcmail.exe и то, что она была расположена по адресу C:wcwcmail.exe. Простейшая установочная команда диспетчера SC — sc create Webimagemailer binpath= C:wcwcmail.exe

на которую диспетчер служб ответит кратким сообщением

/SC/CreateService SUCCESS.

Эта команда выполняет несколько задач. В частности, она создает подраздел под названием Web imagemailer в разделе HKEY_ LOCAL_ MASHINESYSTEMCurrentControlSetServices. Внутри этого подраздела диспетчер служб SC создает другие подразделы под названиями Enum («Перечень») и Security («Безопасность») — такие разделы имеет в реестре большинство служб. Внутри этих подразделов имеется некоторое количество параметров для настройки, которые устанавливает диспетчер SC, но возможность для их точной настройки появится несколько позже. Один из этих параметров, ImagePath, содержит местоположение службы, которое было установлено в SC через ключ binpath= parameter. Диспетчер SC ведет себя несколько странно по отношению к своим параметрам, в данном случае требуется пробел между параметром и знаком равенства.

Экран. Запрос команды output

Исследование встроенных служб в MMC показывает, что теперь имеется служба под названием Webimagemailer, запускающаяся вручную и работающая в рамках локальной системы. Здесь можно было бы задействовать параметр start= parameter, который использует boot, system, auto, demand (ключи диспетчера SC для запуска вручную) или disabled — для настроек запуска. Таким же образом возможно использование параметра obj= username для задания учетной записи, от имени которой функционирует диспетчер SC. Также необходимо уделять внимание проблеме безопасности и не запрашивать малоизвестную службу, которая выполняется в рамках локальной системы. Можно было бы ввести учетную запись под названием, скажем, Webcamguy с паролем swordfish и только самые необходимые разрешения для того, чтобы wcmail.exe выполнила работу, и ничего более. Но раз уж мы занялись этим делом, имя Webimagemailer выглядит несколько неуклюже на фоне уже существующих служб. Воспользовавшись ключом displayname= «descriptive name», можно изменить его.

Еще одна попытка

Итак, теперь нам нужно создать модернизированную команду, которая будет работать лучше. Чтобы удалить первую попытку и освободить место для следующей, требуется набрать

sc delete Webimagemailer

Эта команда помечает службу для удаления; для достижения результата требуется перезагрузиться. Теперь можно добавить новый тип запуска, учетную запись службы и отображаемое имя:

sc create webimagemailer binpath= C:wcwcmail.exe
start= auto displayname=
obj= .webcamguy password= swordfish

Обратите внимание, важно оставить пробел после знака равенства.

Точная настройка

Предположим, что служба отлично работает, но если вы по каким-то причинам отсоедините от компьютера Web-камеру и потом забудете подключить ее обратно, то будете получать сообщение

At least one service or driver failed during startup

всякий раз при загрузке компьютера. Служба Webcam удобна, но не настолько важна, чтобы позволить ей надоедать беспрестанными напоминаниями о том, что Web-камера не подключена. Поэтому лучше убрать это сообщение.

В данной ситуации следует воспользоваться ключом error= parameter. Система Windows следит за тем, как запускаются службы, и можно настроить ответ операционной системы на несостоявшийся запуск четырьмя способами: обычный, режим по умолчанию; выводит сообщение на экран и начинает работу Windows в нормальном режиме; игнорирующий — просто отправляет сообщение в журнал событий; требовательный — распознает службу или драйвер по степени значимости и запускает перезагрузку операционной системы в последней известной хорошей конфигурации; и, наконец, критический, — вынуждает систему Windows осуществить перезагрузку до последней известной удачной конфигурации, но предписывает выдавать «синий экран», если драйвер или служба все еще не загружены.

Итак, следует удалить службу, перезагрузиться, добавить параметр error= ignore — и все должно быть в порядке. По крайней мере, до тех пор, пока не настанет необходимость решать определенные проблемы со взаимозависимостью служб.

Три подкоманды для SC

Продвинемся немного глубже. Предположим, что Webimagemailer не запускается до тех пор, пока не заработает служба распознавания изображений WIA (Windows Image Acquisition) с ключевым именем stisvc. В терминологии служб это означает, что Webimagemailer зависит от stisvc. Чтобы Webimagemailer получил инструкцию ожидания запуска stisvc, прежде чем начать работу, следует добавить параметр depend= stisvc. Необходимо помнить, что диспетчер SC требует оставлять пробел между знаком равенства и значением параметра. Чтобы определить, какая служба находится в зависимости от некоторых других служб, нужно составить список ключевых имен служб, разделенных левой наклонной чертой. Например, чтобы создать службу Webimagemailer и задать запуск служб stisvc и webclient до начала ее работы, следует набрать

sc create webimagemailer binpath= C:wcwcmail.exe
start= auto displayname=
obj= .webcamguy password= swordfish
error= ignore depend= stisvc/webclient

Раз уж мы затронули вопрос о зависимостях, можно воспользоваться тремя подкомандами SC — enumdepends, qc и config, чтобы запросить о них диспетчер SC. Если требуется определить, какие службы будут зависеть от данной службы, можно набрать

sc enumpend

Теперь, чтобы увидеть, какие службы находятся в зависимости от службы сервера под названием lanmanserver, надо напечатать

sc enumdepend Lanmanserver

Запуск такой команды на моем тестовом сервере Windows 2003, например, показывает, что службы Netlogon, Dfs, а также службы браузера компьютера находятся в зависимости от службы сервера.

Для завершения и определения зависимостей сервера можно воспользоваться подкомандой qc, как показано ниже

sc qc Lanmanserver

Эта команда выдает девять строчек информации о службе, одна из которых DEPENDENCIES. При запуске этой команды выясняется, что сервер не зависит ни от каких служб. Чтобы узнать, какие службы имеют более одной зависимости, можно протестировать диспетчер на службе Netlogon. Мы увидим, что служба Netlogon для начала работы требует запуска служб и сервера, и Workstation.

Иногда зависимости бывают более сложными. Например, некоторые службы могут начать работу, только если запущена одна из трех других служб. Запуск всех трех необязателен, вполне достаточно одной. Можно проинструктировать Windows по поводу такой динамики, информируя систему о том, что данная служба находится в зависимости от группы служб. В системе Windows имеется целый ряд таких служб, как, например, SCSI CDROM Class, SCSI miniport, Parallel arbitrator, NetBIOSGroup, NDIS, а также службы первичного диска и многие другие. Все эти службы и драйверы можно увидеть в списке групп, набрав

sc query type= service?driver?all group=

Например, чтобы посмотреть все службы и драйверы в группе служб первичного диска, нужно набрать

sc query type= all group=

Названия групп значения не имеют. Можно добавлять службы в имеющиеся группы или создавать новые группы служб, добавив команду group= groupname в команду SC Create или используя SC Config для сохранения службы в какую-либо группу. Например, чтобы добавить службу Webimagemailer в новую группу под названием unimportant, надо набрать

sc config webimagemailer group= unimportant

Однако нельзя поместить службу или драйвер в более чем одну группу служб.

Кроме того, можно сделать так, чтобы не происходила загрузка службы Webimagemailer без необходимой группы служб. Чтобы определить фиктивную группу Webstartup, воспользуемся параметром depends= webstartup. Чтобы указать Windows, что Webstartup — это группа, а не еще одна служба, следует перед ее именем поставить знак «плюс». Например, для перенастройки службы Webimagemailer на зависимость от группы запуска Webstartup, надо набрать

sc config webimagemailer depends= +webstartup

Таким образом, мы выяснили, как использовать зависимости и группы для более детального управления порядком загрузки службы. И теперь никто не удивится, почему я был так доволен, когда несколько лет назад обнаружил диспетчер SC.

Марк Минаси — Редактоp Windows IT Pro, MCSE и автор книги Mastering Windows Server 2003 (издательство Sybex). mark@minasi.com

Понравилась статья? Поделить с друзьями:
  • Service control manager 7045 windows 10
  • Service control manager 7040 ошибка windows 10
  • Service control manager 7034 windows 10 как исправить
  • Service control manager 7031 windows 10 как исправить
  • Service control manager 7030 windows 10