- Отладка программ Debug programs
- Справочные материалы Reference
- Возможные значения Possible values
- Рекомендации Best practices
- Location Location
- Значения по умолчанию Default values
- Управление политикой Policy management
- Групповая политика Group Policy
- Вопросы безопасности Security considerations
- Уязвимость Vulnerability
- Противодействие Countermeasure
- Возможное влияние Potential impact
- Debug programs
- Reference
- Possible values
- Best practices
- Location
- Default values
- Policy management
- Group Policy
- Security considerations
- Vulnerability
- Countermeasure
- Potential impact
- Практическое руководство. Отладка приложений служб Windows How to: Debug Windows Service Applications
- Отладка службы To debug a service
- Советы по отладке для служб Windows Debugging Tips for Windows Services
- Практическое руководство. Запуск службы Windows как консольного приложения How to: Run a Windows Service as a console application
Отладка программ Debug programs
Область применения Applies to
В этой статье описываются лучшие методики, расположение, значения, **** управление политиками и вопросы безопасности для параметра политики безопасности программ отлаки. Describes the best practices, location, values, policy management, and security considerations for the Debug programs security policy setting.
Справочные материалы Reference
Этот параметр политики определяет, какие пользователи могут присоединять или открывать любые процессы, даже те, которыми они не владеют. This policy setting determines which users can attach to or open any process, even a process they do not own. Разработчики, которые отладиют собственные приложения, не нуждаются в этом праве пользователя. Developers who are debugging their own applications do not need this user right. Это право пользователя необходимо разработчикам, которые отладит новые компоненты системы. Developers who are debugging new system components need this user right. Это право пользователя предоставляет доступ к конфиденциальным и критически важным компонентам операционной системы. This user right provides access to sensitive and critical operating-system components.
Константа: SeDebugPrivilege Constant: SeDebugPrivilege
Возможные значения Possible values
- Определяемый пользователей список учетных записей User-defined list of accounts
- Не определено Not defined
Рекомендации Best practices
- Назначьте это право только доверенным пользователям, чтобы уменьшить уязвимости системы безопасности. Assign this user right only to trusted users to reduce security vulnerabilities.
Location Location
Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment
Значения по умолчанию Default values
По умолчанию это право имеют члены группы «Администраторы». By default, members of the Administrators group have this right.
В следующей таблице перечислены фактические и эффективные значения политики по умолчанию для последних поддерживаемых версий Windows. The following table lists the actual and effective default policy values for the most recent supported versions of Windows. Значения по умолчанию также можно найти на странице свойств политики. Default values are also listed on the policy’s property page.
Тип сервера или объект групповой политики Server type or GPO | Значение по умолчанию Default value |
---|---|
Default Domain Policy Default Domain Policy | Не определено Not defined |
Политика контроллера домена по умолчанию Default Domain Controller Policy | Администраторы Administrators |
Параметры по умолчанию для автономного сервера Stand-Alone Server Default Settings | Администраторы Administrators |
Действующие параметры по умолчанию для контроллера домена Domain Controller Effective Default Settings | Администраторы Administrators |
Действующие параметры по умолчанию для рядового сервера Member Server Effective Default Settings | Администраторы Administrators |
Действующие параметры по умолчанию для клиентского компьютера Client Computer Effective Default Settings | Администраторы Administrators |
Управление политикой Policy management
В этом разделе описываются функции и средства, которые помогут вам управлять этой политикой. This section describes features and tools that are available to help you manage this policy.
Перезапуск устройства не требуется для того, чтобы этот параметр политики был эффективным. A restart of the device is not required for this policy setting to be effective.
Изменения прав пользователя вступают в силу при его следующем входе в учетную запись. Any change to the user rights assignment for an account becomes effective the next time the owner of the account logs on.
Групповая политика Group Policy
Параметры применяются в следующем порядке с помощью объекта групповой политики (GPO), который будет перезаписывать параметры на локальном компьютере при следующем обновлении групповой политики: Settings are applied in the following order through a Group Policy Object (GPO), which will overwrite settings on the local computer at the next Group Policy update:
- Параметры локальной политики Local policy settings
- Параметры политики сайта Site policy settings
- Параметры политики домена Domain policy settings
- Параметры политики подразделения OU policy settings
Если локальный параметр затеняется, это означает, что в настоящее время этот параметр контролируется GPO. When a local setting is greyed out, it indicates that a GPO currently controls that setting.
Вопросы безопасности Security considerations
В этом разделе описывается, каким образом злоумышленник может использовать компонент или его конфигурацию, как реализовать меры противодействия, а также рассматриваются возможные отрицательные последствия их реализации. This section describes how an attacker might exploit a feature or its configuration, how to implement the countermeasure, and the possible negative consequences of countermeasure implementation.
Уязвимость Vulnerability
Право пользователя программы отлаки можно использовать для захвата конфиденциальной информации об устройстве из системной памяти, а также для доступа и изменения структуры ядра или приложений. The Debug programs user right can be exploited to capture sensitive device information from system memory or to access and modify kernel or application structures. Некоторые средства атаки используют это право пользователя для извлечения паролей с использованием hashed и других закрытых сведений о безопасности или для вставки вредоносных программ. Some attack tools exploit this user right to extract hashed passwords and other private security information or to insert malware. По умолчанию право пользователя программ отлаки назначено только администраторам, что помогает снизить риск этой уязвимости. By default, the Debug programs user right is assigned only to administrators, which helps mitigate risk from this vulnerability.
Противодействие Countermeasure
Удалите учетные записи всех пользователей и **** групп, для работы с которые не требуется право пользователя программ отлаки. Remove the accounts of all users and groups that do not require the Debug programs user right.
Возможное влияние Potential impact
Если вы отзовете это право пользователя, никто не сможет отлалать программы. If you revoke this user right, no one can debug programs. Однако в типичных обстоятельствах редко требуется эта возможность на производственных устройствах. However, typical circumstances rarely require this capability on production devices. Если возникает проблема, требуемая отладки приложения на производственном сервере, можно временно переместить сервер в другое подразделение **** и назначить пользователю программ отладки право на отдельную групповую политику для этого подразделения. If an issue arises that requires an application to be debugged on a production server, you can move the server to a different organizational unit (OU) temporarily and assign the Debug programs user right to a separate Group Policy for that OU.
Debug programs
Applies to
Describes the best practices, location, values, policy management, and security considerations for the Debug programs security policy setting.
Reference
This policy setting determines which users can attach to or open any process, even a process they do not own. Developers who are debugging their own applications do not need this user right. Developers who are debugging new system components need this user right. This user right provides access to sensitive and critical operating-system components.
Possible values
- User-defined list of accounts
- Not defined
Best practices
- Assign this user right only to trusted users to reduce security vulnerabilities.
Location
Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment
Default values
By default, members of the Administrators group have this right.
The following table lists the actual and effective default policy values for the most recent supported versions of Windows. Default values are also listed on the policy’s property page.
Server type or GPO | Default value |
---|---|
Default Domain Policy | Not defined |
Default Domain Controller Policy | Administrators |
Stand-Alone Server Default Settings | Administrators |
Domain Controller Effective Default Settings | Administrators |
Member Server Effective Default Settings | Administrators |
Client Computer Effective Default Settings | Administrators |
Policy management
This section describes features and tools that are available to help you manage this policy.
A restart of the device is not required for this policy setting to be effective.
Any change to the user rights assignment for an account becomes effective the next time the owner of the account logs on.
Group Policy
Settings are applied in the following order through a Group Policy Object (GPO), which will overwrite settings on the local computer at the next Group Policy update:
- Local policy settings
- Site policy settings
- Domain policy settings
- OU policy settings
When a local setting is greyed out, it indicates that a GPO currently controls that setting.
Security considerations
This section describes how an attacker might exploit a feature or its configuration, how to implement the countermeasure, and the possible negative consequences of countermeasure implementation.
Vulnerability
The Debug programs user right can be exploited to capture sensitive device information from system memory or to access and modify kernel or application structures. Some attack tools exploit this user right to extract hashed passwords and other private security information or to insert malware. By default, the Debug programs user right is assigned only to administrators, which helps mitigate risk from this vulnerability.
Countermeasure
Remove the accounts of all users and groups that do not require the Debug programs user right.
Potential impact
If you revoke this user right, no one can debug programs. However, typical circumstances rarely require this capability on production devices. If an issue arises that requires an application to be debugged on a production server, you can move the server to a different organizational unit (OU) temporarily and assign the Debug programs user right to a separate Group Policy for that OU.
Практическое руководство. Отладка приложений служб Windows How to: Debug Windows Service Applications
Служба должна запускаться из диспетчера управления службами, а не из Visual Studio. A service must be run from within the context of the Services Control Manager rather than from within Visual Studio. Поэтому, процесс отладки службы сложнее, чем отладка приложений Visual Studio других типов. For this reason, debugging a service is not as straightforward as debugging other Visual Studio application types. Для отладки службы необходимо запустить службу, а затем подключить отладчик к процессу, в котором она выполняется. To debug a service, you must start the service and then attach a debugger to the process in which it is running. Приложение можно отлаживать с помощью всех стандартных средств отладки Visual Studio. You can then debug your application by using all of the standard debugging functionality of Visual Studio.
Не следует присоединять к процессу, если неизвестно, что собой представляет данный процесс, и неясны последствия подключения к процессу (включая даже уничтожение этого процесса). You should not attach to a process unless you know what the process is and understand the consequences of attaching to and possibly killing that process. Например, при подключении к процессу WinLogon и последующей остановке процесса отладки система будет остановлена, так как она не может работать без данного процесса. For example, if you attach to the WinLogon process and then stop debugging, the system will halt because it can’t operate without WinLogon.
Отладчик можно прикреплять только к выполняющейся службе. You can attach the debugger only to a running service. Процесс подключения прерывает текущую работу службы (фактически он не останавливает и не приостанавливает ее). The attachment process interrupts the current functioning of your service; it doesn’t actually stop or pause the service’s processing. То есть, если служба уже выполнялась на момент запуска процесса отладки, она по-прежнему технически находится в состоянии «Started» в ходе отладки, однако ее работа приостанавливается. That is, if your service is running when you begin debugging, it is still technically in the Started state as you debug it, but its processing has been suspended.
После присоединения к процессу можно установить точки останова и использовать их для отладки кода. After attaching to the process, you can set breakpoints and use these to debug your code. После выхода из диалогового окна, используемого для подключения к процессу, вы продолжаете оставаться в режиме отладки. Once you exit the dialog box you use to attach to the process, you are effectively in debug mode. Для запуска, остановки, приостановки и продолжения работы служб (то есть, попадания в заданные точки) можно использовать диспетчер управления службами. You can use the Services Control Manager to start, stop, pause and continue your service, thus hitting the breakpoints you’ve set. Позднее эту фиктивную службу можно удалить после успешного завершения отладки. You can later remove this dummy service after debugging is successful.
В этой статье рассматривается процесс отладки службы, выполняемой на локальном компьютере (также можно выполнять отладку служб Windows, которые выполняются на удаленном компьютере). This article covers debugging a service that’s running on the local computer, but you can also debug Windows Services that are running on a remote computer. См. статью об удаленной отладке. See Remote Debugging.
Процесс отладки метода OnStart может быть сложным, так как диспетчер управления службами накладывает ограничение в 30 секунд на все попытки запуска службы. Debugging the OnStart method can be difficult because the Services Control Manager imposes a 30-second limit on all attempts to start a service. Дополнительные сведения см. в статье Устранение неполадок. Отладка служб Windows. For more information, see Troubleshooting: Debugging Windows Services.
Для получения значимой информации для отладки отладчик Visual Studio должен найти файлы символов для двоичных файлов, для которых выполняется отладка. To get meaningful information for debugging, the Visual Studio debugger needs to find symbol files for the binaries that are being debugged. При отладке службы, созданной в Visual Studio, файлы символов (PDB-файлы) находятся в той же папке, что и исполняемый файл или библиотека, и отладчик загружает их автоматически. If you are debugging a service that you built in Visual Studio, the symbol files (.pdb files) are in the same folder as the executable or library, and the debugger loads them automatically. При отладке службы, которая не была построена, сначала следует найти символы для службы и убедиться, что они могут быть найдены отладчиком. If you are debugging a service that you didn’t build, you should first find symbols for the service and make sure they can be found by the debugger. См. руководство по определению файлов символов (.pdb) и файлов с исходным кодом в отладчике Visual Studio. See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger. Если вы выполняете отладку системного процесса или хотите иметь символы для системных вызовов в своих службах, то необходимо добавить серверы символов Майкрософт. If you’re debugging a system process or want to have symbols for system calls in your services, you should add the Microsoft Symbol Servers. См. статью об отладке с помощью символов. See Debugging Symbols.
Отладка службы To debug a service
Постройте службу в конфигурации отладки. Build your service in the Debug configuration.
Установите службу. Install your service. Дополнительные сведения см. в разделе Практическое руководство. Установка и удаление служб. For more information, see How to: Install and Uninstall Services.
Запустите службу из диспетчера служб, обозревателя сервера или из кода. Start your service, either from Services Control Manager, Server Explorer, or from code. Дополнительные сведения см. в разделе Практическое руководство. Запуск служб. For more information, see How to: Start Services.
Запустите Visual Studio с учетными данными администратора, чтобы вы могли подключиться к системным процессам. Start Visual Studio with administrative credentials so you can attach to system processes.
(Необязательное действие.) В строке меню Visual Studio последовательно выберите Инструменты и Параметры. (Optional) On the Visual Studio menu bar, choose Tools, Options. В диалоговом окне Параметры последовательно выберите Отладка и Символы, установите флажок Серверы символов Microsoft и нажмите кнопку ОК. In the Options dialog box, choose Debugging, Symbols, select the Microsoft Symbol Servers check box, and then choose the OK button.
В строке меню в меню Отладка или Инструменты выберите пункт Присоединение к процессу. On the menu bar, choose Attach to Process from the Debug or Tools menu. (Клавиатура: CTRL+ALT+P) (Keyboard: Ctrl+Alt+P)
Откроется диалоговое окно Процессы. The Processes dialog box appears.
Установите флажок Показать процессы, запущенные всеми пользователями. Select the Show processes from all users check box.
В разделе Доступные процессы выберите процесс для службы и нажмите кнопку Присоединиться. In the Available Processes section, choose the process for your service, and then choose Attach.
Процесс будет иметь то же имя, что и исполняемый файл для службы. The process will have the same name as the executable file for your service.
Откроется диалоговое окно Присоединение к процессу . The Attach to Process dialog box appears.
Выберите соответствующие параметры, а затем нажмите кнопку ОК, чтобы закрыть диалоговое окно. Choose the appropriate options, and then choose OK to close the dialog box.
Теперь вы находитесь в режиме отладки. You are now in debug mode.
Установите точки останова, которые буден нужно использовать в коде. Set any breakpoints you want to use in your code.
Откройте диспетчер управления службами и выполните несколько операций со своей службой (выполните команды остановки, приостановки и продолжения), чтобы обнаружить свои точки останова. Access the Services Control Manager and manipulate your service, sending stop, pause, and continue commands to hit your breakpoints. Дополнительные сведения о запуске диспетчера управления службами см. в разделе Практическое руководство. Запуск служб. For more information about running the Services Control Manager, see How to: Start Services. Также см. раздел Устранение неполадок. Отладка служб Windows. Also, see Troubleshooting: Debugging Windows Services.
Советы по отладке для служб Windows Debugging Tips for Windows Services
Присоединение к процессу службы позволяет отлаживать основную часть кода (но не весь код) для этой службы. Attaching to the service’s process allows you to debug most, but not all, the code for that service. Например, так как служба уже была запущена, нельзя выполнять отладку кода в методе OnStart службы или кода в методе Main , который используется для загрузки службы подобным образом. For example, because the service has already been started, you cannot debug the code in the service’s OnStart method or the code in the Main method that is used to load the service this way. Одним из способов обхода этого ограничения является создание временной второй службы в приложении службы, которая предназначена только для отладки. One way to work around this limitation is to create a temporary second service in your service application that exists only to aid in debugging. Можно установить обе службы,а затем запустить эту фиктивную службу для загрузки процесса службы. You can install both services, and then start this dummy service to load the service process. Когда временная служба запустит процесс, в Visual Studio в меню Отладка можно будет присоединиться к процессу службы. Once the temporary service has started the process, you can use the Debug menu in Visual Studio to attach to the service process.
Попробуйте добавлять вызовы в метод Sleep с целью задержки выполнения действия, пока вы не присоединитесь к процессу. Try adding calls to the Sleep method to delay action until you’re able to attach to the process.
Попробуйте заменить программу на обычное консольное приложение. Try changing the program to a regular console application. Для этого измените метод Main следующим образом, чтобы он мог быть запущен и как служба Windows, и как консольное приложение (в зависимости от способа запуска). To do this, rewrite the Main method as follows so it can run both as a Windows Service and as a console application, depending on how it’s started.
Практическое руководство. Запуск службы Windows как консольного приложения How to: Run a Windows Service as a console application
Добавьте метод в свою службу, которая запускает методы OnStart и OnStop: Add a method to your service that runs the OnStart and OnStop methods:
Перепишите метод Main следующим образом: Rewrite the Main method as follows:
В окне свойств проекта на вкладке Приложение задайте для параметра Тип выходных данных значение Консольное приложение. In the Application tab of the project’s properties, set the Output type to Console Application.
Щелкните Начать отладку (F5). Choose Start Debugging (F5).
Чтобы снова запустить программу как службу Windows, установите ее и запустите обычным образом (для службы Windows). To run the program as a Windows Service again, install it and start it as usual for a Windows Service. Отменять эти изменения необязательно. It’s not necessary to reverse these changes.
В некоторых случаях, например, если требуется устранить некоторую проблему, которая возникает только при запуске системы, необходимо использовать отладчик Windows. In some cases, such as when you want to debug an issue that occurs only on system startup, you have to use the Windows debugger. Скачайте набор драйверов Windows (WDK) и узнайте о способах отладки служб Windows. Download the Windows Driver Kit (WDK) and see How to debug Windows Services.