remotesigned powershell что это
about_Execution_Policies
Short description
Describes the PowerShell execution policies and explains how to manage them.
Long description
PowerShell’s execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps prevent the execution of malicious scripts.
On a Windows computer you can set an execution policy for the local computer, for the current user, or for a particular session. You can also use a Group Policy setting to set execution policies for computers and users.
Execution policies for the local computer and current user are stored in the registry. You don’t need to set execution policies in your PowerShell profile. The execution policy for a particular session is stored only in memory and is lost when the session is closed.
The execution policy isn’t a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.
On non-Windows computers, the default execution policy is Unrestricted and cannot be changed. The Set-ExecutionPolicy cmdlet is available, but PowerShell displays a console message that it’s not supported. While Get-ExecutionPolicy returns Unrestricted on non-Windows platforms, the behavior really matches Bypass because those platforms do not implement the Windows Security Zones.
PowerShell execution policies
Enforcement of these policies only occurs on Windows platforms. The PowerShell execution policies are as follows:
AllSigned
Bypass
Default
RemoteSigned
Restricted
Undefined
Unrestricted
On systems that do not distinguish Universal Naming Convention (UNC) paths from internet paths, scripts that are identified by a UNC path might not be permitted to run with the RemoteSigned execution policy.
Execution policy scope
You can set an execution policy that is effective only in a particular scope.
The valid values for Scope are MachinePolicy, UserPolicy, Process, CurrentUser, and LocalMachine. LocalMachine is the default when setting an execution policy.
The Scope values are listed in precedence order. The policy that takes precedence is effective in the current session, even if a more restrictive policy was set at a lower level of precedence.
MachinePolicy
Set by a Group Policy for all users of the computer.
UserPolicy
Set by a Group Policy for the current user of the computer.
Process
CurrentUser
The execution policy affects only the current user. It’s stored in the HKEY_CURRENT_USER registry subkey.
LocalMachine
The execution policy affects all users on the current computer. It’s stored in the HKEY_LOCAL_MACHINE registry subkey.
Managing the execution policy with PowerShell
To get the effective execution policy for the current PowerShell session, use the Get-ExecutionPolicy cmdlet.
The following command gets the effective execution policy:
To get all of the execution policies that affect the current session and display them in precedence order:
The result looks similar to the following sample output:
In this case, the effective execution policy is RemoteSigned because the execution policy for the current user takes precedence over the execution policy set for the local computer.
For example, the following command gets the execution policy for the CurrentUser scope:
Change the execution policy
To change the PowerShell execution policy on your Windows computer, use the Set-ExecutionPolicy cmdlet. The change is effective immediately. You don’t need to restart PowerShell.
If you set the execution policy for the scopes LocalMachine or the CurrentUser, the change is saved in the registry and remains effective until you change it again.
If you set the execution policy for the Process scope, it’s not saved in the registry. The execution policy is retained until the current process and any child processes are closed.
In Windows Vista and later versions of Windows, to run commands that change the execution policy for the local computer, LocalMachine scope, start PowerShell with the Run as administrator option.
To change your execution policy:
To set the execution policy in a particular scope:
A command to change an execution policy can succeed but still not change the effective execution policy.
For example, a command that sets the execution policy for the local computer can succeed but be overridden by the execution policy for the current user.
Remove the execution policy
To remove the execution policy for a particular scope, set the execution policy to Undefined.
For example, to remove the execution policy for all the users of the local computer:
To remove the execution policy for a Scope:
If no execution policy is set in any scope, the effective execution policy is Restricted, which is the default for Windows clients.
Set a different policy for one session
You can use the ExecutionPolicy parameter of pwsh.exe to set an execution policy for a new PowerShell session. The policy affects only the current session and child sessions.
To set the execution policy for a new session, start PowerShell at the command line, such as cmd.exe or from PowerShell, and then use the ExecutionPolicy parameter of pwsh.exe to set the execution policy.
During the session, the execution policy that is set for the session takes precedence over an execution policy that is set in the registry for the local computer or current user. However, it doesn’t take precedence over the execution policy set by using a Group Policy.
Use Group Policy to Manage Execution Policy
You can use the Turn on Script Execution Group Policy setting to manage the execution policy of computers in your enterprise. The Group Policy setting overrides the execution policies set in PowerShell in all scopes.
The Turn on Script Execution policy settings are as follows:
If you disable Turn on Script Execution, scripts do not run. This is equivalent to the Restricted execution policy.
If you enable Turn on Script Execution, you can select an execution policy. The Group Policy settings are equivalent to the following execution policy settings:
Group Policy | Execution Policy |
---|---|
Allow all scripts | Unrestricted |
Allow local scripts and remote signed scripts | RemoteSigned |
Allow only signed scripts | AllSigned |
If Turn on Script Execution is not configured, it has no effect. The execution policy set in PowerShell is effective.
The PowerShellExecutionPolicy.adm and PowerShellExecutionPolicy.admx files add the Turn on Script Execution policy to the Computer Configuration and User Configuration nodes in Group Policy Editor in the following paths.
For Windows XP and Windows Server 2003:
Administrative Templates\Windows Components\Windows PowerShell
For Windows Vista and later versions of Windows:
Administrative Templates\Classic Administrative Templates\Windows Components\Windows PowerShell
Policies set in the Computer Configuration node take precedence over policies set in the User Configuration node.
Execution policy precedence
When determining the effective execution policy for a session, PowerShell evaluates the execution policies in the following precedence order:
Manage signed and unsigned scripts
In Windows, programs like Internet Explorer and Microsoft Edge add an alternate data stream to files that are downloaded. This marks the file as «coming from the Internet». If your PowerShell execution policy is RemoteSigned, PowerShell won’t run unsigned scripts that are downloaded from the internet which includes email and instant messaging programs.
You can sign the script or elect to run an unsigned script without changing the execution policy.
Beginning in PowerShell 3.0, you can use the Stream parameter of the Get-Item cmdlet to detect files that are blocked because they were downloaded from the internet. Use the Unblock-File cmdlet to unblock the scripts so that you can run them in PowerShell.
Other methods of downloading files may not mark the files as coming from the Internet Zone. Some examples include:
Execution policy on Windows Server Core and Window Nano Server
When PowerShell 6 is run on Windows Server Core or Windows Nano Server under certain conditions, execution policies can fail with the following error:
PowerShell uses APIs in the Windows Desktop Shell ( explorer.exe ) to validate the Zone of a script file. The Windows Shell is not available on Windows Server Core and Windows Nano Server.
You could also get this error on any Windows system if the Windows Desktop Shell is unavailable or unresponsive. For example, during sign on, a PowerShell logon script could start execution before the Windows Desktop is ready, resulting in failure.
Using an execution policy of ByPass or AllSigned does not require a Zone check which avoids the problem.
Set-Execution Policy
Sets the PowerShell execution policies for Windows computers.
Syntax
Description
The Set-ExecutionPolicy cmdlet changes PowerShell execution policies for Windows computers. For more information, see about_Execution_Policies.
Beginning in PowerShell 6.0 for non-Windows computers, the default execution policy is Unrestricted and can’t be changed. The Set-ExecutionPolicy cmdlet is available, but PowerShell displays a console message that it’s not supported.
An execution policy is part of the PowerShell security strategy. Execution policies determine whether you can load configuration files, such as your PowerShell profile, or run scripts. And, whether scripts must be digitally signed before they are run.
The Set-ExecutionPolicy cmdlet’s default scope is LocalMachine, which affects everyone who uses the computer. To change the execution policy for LocalMachine, start PowerShell with Run as Administrator.
Examples
Example 1: Set an execution policy
This example shows how to set the execution policy for the local computer.
The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The Scope parameter specifies the default scope value, LocalMachine. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.
Example 2: Set an execution policy that conflicts with a Group Policy
This command attempts to set the LocalMachine scope’s execution policy to Restricted. LocalMachine is more restrictive, but isn’t the effective policy because it conflicts with a Group Policy. The Restricted policy is written to the registry hive HKEY_LOCAL_MACHINE.
The Set-ExecutionPolicy cmdlet uses the ExecutionPolicy parameter to specify the Restricted policy. The Scope parameter specifies the default scope value, LocalMachine. The Get-ChildItem cmdlet uses the Path parameter with the HKLM provider to specify registry location.
Example 3: Apply the execution policy from a remote computer to a local computer
This command gets the execution policy object from a remote computer and sets the policy on the local computer. Get-ExecutionPolicy sends a Microsoft.PowerShell.ExecutionPolicy object down the pipeline. Set-ExecutionPolicy accepts pipeline input and doesn’t require the ExecutionPolicy parameter.
Example 4: Set the scope for an execution policy
This example shows how to set an execution policy for a specified scope, CurrentUser. The CurrentUser scope only affects the user who sets this scope.
Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned policy. The Scope parameter specifies the CurrentUser. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.
The effective execution policy for the user becomes AllSigned.
Example 5: Remove the execution policy for the current user
This example shows how use the Undefined execution policy to remove an execution policy for a specified scope.
Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the Undefined policy. The Scope parameter specifies the CurrentUser. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.
Example 6: Set the execution policy for the current PowerShell session
The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the AllSigned policy. The Scope parameter specifies the value Process. To view the execution policy settings, use the Get-ExecutionPolicy cmdlet with the List parameter.
Example 7: Unblock a script to run it without changing the execution policy
This example shows how the RemoteSigned execution policy prevents you from running unsigned scripts.
A best practice is to read the script’s code and verify it’s safe before using the Unblock-File cmdlet. The Unblock-File cmdlet unblocks scripts so they can run, but doesn’t change the execution policy.
The Set-ExecutionPolicy uses the ExecutionPolicy parameter to specify the RemoteSigned policy. The policy is set for the default scope, LocalMachine.
The Get-ExecutionPolicy cmdlet shows that RemoteSigned is the effective execution policy for the current PowerShell session.
The Start-ActivityTracker.ps1 script is executed from the current directory. The script is blocked by RemoteSigned because the script isn’t digitally signed.
For this example, the script’s code was reviewed and verified as safe to run. The Unblock-File cmdlet uses the Path parameter to unblock the script.
To verify that Unblock-File didn’t change the execution policy, Get-ExecutionPolicy displays the effective execution policy, RemoteSigned.
The script, Start-ActivityTracker.ps1 is executed from the current directory. The script begins to run because it was unblocked by the Unblock-File cmdlet.
Parameters
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the execution policy. If there are no Group Policies and each scope’s execution policy is set to Undefined, then Restricted becomes the effective policy for all users.
The acceptable execution policy values are as follows:
Suppresses all the confirmation prompts. Use caution with this parameter to avoid unexpected results.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the scope that is affected by an execution policy. The default scope is LocalMachine.
The effective execution policy is determined by the order of precedence as follows:
Execution policies for the CurrentUser scope are written to the registry hive HKEY_LOCAL_USER.
Execution policies for the LocalMachine scope are written to the registry hive HKEY_LOCAL_MACHINE.
Type: | ExecutionPolicyScope |
Accepted values: | CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy |
Position: | 1 |
Default value: | LocalMachine |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
Microsoft.PowerShell.ExecutionPolicy, System.String
Outputs
None
Set-ExecutionPolicy doesn’t return any output.
Notes
Set-ExecutionPolicy doesn’t change the MachinePolicy and UserPolicy scopes because they are set by Group Policies.
Set-ExecutionPolicy doesn’t override a Group Policy, even if the user preference is more restrictive than the policy.
If the Group Policy Turn on Script Execution is enabled for the computer or user, the user preference is saved, but it is not effective. PowerShell displays a message that explains the conflict.
Политика выполнения скриптов PowerShell
При разработке PowerShell особое внимание было уделено безопасности. Одной из мер безопасности является наличие политики выполнения (Execution Policy), которая определяет, могут ли скрипты PowerShell выполняться в системе, и если могут, то какие именно.
Для примера возьмем чистую Windows 10, откроем консоль PowerShell и попробуем выполнить простой скрипт. Попытка завершится ошибкой, поскольку, как видно из сообщения, выполнение скриптов в системе запрещено.
Это сработала политика выполнения, и если мы все же хотим выполнить скрипт, то ее необходимо изменить. Выбрать можно одно из следующих значений:
• Restricted — в системе запрещено выполнение любых скриптов, допускается только выполнение отдельных команд. Это политика по умолчанию для клиентских ОС Windows;
• AllSigned — разрешено выполнение только скриптов, имеющих цифровую подпись от доверенного издателя;
• RemoteSigned — для удаленных скриптов требуется наличие цифровой подписи, локальные скрипты выполняются без ограничений. Удаленными считаются скрипты, полученные из удаленных источников (загруженные из интернета, полученные по электронной почте и т.п.), локальными — скрипты, созданные на локальном компьютере. Это политика по умолчанию для серверных ОС Windows;
• Unrestricted — разрешено выполнение любых скриптов, как локальных так и удаленных. При выполнении удаленного скрипта без цифровой подписи будет выдано предупреждение. Это дефолтная и единственно возможная политика для всех ОС, отличных от Windows;
• Bypass — разрешено выполнение любых скриптов, никакие предупреждения и запросы не выводятся;
• Default — сбрасывает политику на значение по умолчанию. Для серверов это RemoteSigned, для клиентов Restricted;
• Undefined — не определено. В случае, если значение политики не определено, то применяется политика Restricted.
Теоретически все понятно, проверим на практике. Для просмотра параметров политики используется командлет Get-ExecutionPolicy, а для изменения Set-ExecutionPolicy.
Для начала выведем действующую политику выполнения командой:
Как и ожидалось, текущая политика Restricted. Разрешим выполнение скриптов, установив для политики значение Unrestricted:
И еще попробуем запустить скрипт. На сей раз он выполнился без ошибок.
Политика Unrestricted разрешает выполнение любых скриптов, но у нее все же есть ограничения. Для проверки я подготовил два скрипта, локальный localscript.ps1 и удаленный remotescript.ps1. Сначала запустим локальный, он выполнится без проблем. А вот при запуске удаленного скрипта PowerShell выдаст предупреждение и потребует подтвердить его запуск. При ручном выполнении это не является большой проблемой, а вот в случае автоматического запуска (напр. из планировщика) скрипт может не отработать.
Теперь изменим политику на Bypass и еще раз запустим удаленный скрипт. На сей раз он просто выполнился, безо всяких сообщений и подтверждений. Bypass удобно использовать в ситуациях, когда скрипт должен гарантированно отработать, причем автоматически, без вмешательства пользователя.
Следующим пунктом нашего меню идет политика RemoteSigned. Она является наиболее сбалансированной как с точки зрения безопасности, так и удобства использования, поэтому на серверах включена по умолчанию. Установим для политики значение RemoteSigned и проверим ее действие. Локальный скрипт снова выполняется без проблем, а удаленный выдает ошибку, поскольку у него нет подписи.
У вас может возникнуть вопрос, как именно PowerShell различает локальные и удаленные скрипты. Тут все просто. При загрузке файла приложение (напр. браузер) добавляет файл идентификатор зоны (ZoneId), который и определяет, откуда был взят файл. Идентификатор хранится в альтернативном потоке и имеет значение от 0 до 4:
• Локальный компьютер (0)
• Местная сеть (1)
• Надежные сайты (2)
• Интернет (3)
• Опасные сайты (4)
Если файл имеет ZoneId 3 или 4, то PowerShell считает его удаленным. А если на компьютере включена конфигурация усиленной безопасности Internet Explorer, то файлы, взятые из локальной сети, тоже могут считаться удаленными.
Как выполнить удаленный скрипт? Во первых его можно разблокировать (превратить в локальный), для этого есть специальный командлет Unblock-File. Хотя если просто открыть скрипт на локальном компьютере и внести в него изменения, то он тоже станет локальным.
Ну и во вторых удаленный скрипт можно подписать. Подписывание скриптов — это тема отдельной статьи, поэтому вдаваться в подробности не будем. Просто подпишем его уже имеющимся сертификатом, проверим подпись и выполним. На сей раз успешно.
Переходим к политике AllSigned. Это наиболее жесткая политика, требующая подписывания всех без исключения скриптов, как удаленных так и локальных. И даже с подписанными скриптами она работает не так, как RemoteSigned. Для примера сменим политику на AllSigned и снова запустим подписанный скрипт. В этот раз для его выполнения потребуется подтверждение, т.к. PowerShell посчитал подпись недоверенной.
Области применения
Политика выполнения имеет свою область действия (scope). Всего есть 5 областей:
Вывести значение политики для всех областей можно командой:
Получается, что при установке политики без указания области изменяется значение LocalMachine. Если же требуется указать конкретную область действия, то сделать это можно с помощью параметра Scope командлета Set-ExecutionPolicy. Для примера установим для области СurrentUser политику Bypass:
Затем проверим значение политики в текущем сеансе и убедимся в том, что оно изменилось на Bypass.
Теперь установим политику Unrestricted для области Process:
Еще раз проверим текущую политику, теперь она имеет значение Unrestricted. Т.е. более ″конкретная″ политика всегда имеет больший приоритет.
Для областей UserPolicy и MachinePolicy значение политики задаются через GPO. За настройку отвечает параметр Turn on Script Execution (Включить выполнение сценариев), находящийся в разделе Administrative Templates\Windows Components\Windows PowerShell. Для UserPolicy он находится в конфигурации пользователя (User Configuration), для MachinePolicy — в конфигурации компьютера (Computer Configuration). Политика, применяемая к компьютеру, имеет приоритет перед политикой пользователя.
Для установки политики надо включить параметр и выбрать одно из трех значений:
• Allow only signed scripts (Разрешать только подписанные сценарии) — политика AllSigned;
• Allow local scripts and remote signed scripts (разрешать локальные и удаленные подписанные сценарии) — политика RemoteSigned;
• Allow all scripts (Разрешать все сценарии) — политика Unrestricted.
Политика Bypass считается небезопасной и ее нельзя установить через групповые политики.
Для примера установим для MachinePolicy политику RemoteSigned и проверим результат. Как видите, политика, назначенная через GPO, имеет больший приоритет и переопределяет все остальные политики.
Более того, при использовании GPO становится невозможным переназначить политики вручную. При попытке изменения выдается предупреждение, а текущая политика остается без изменений.
А что будет, если ни для одной области политика не определена, т.е. везде стоит значение Undefined? В этом случае все просто, выполнение всех скриптов запрещается, а текущая политика принимает значение Restricted.
Обход политики
Можно ли как то запустить скрип в обход политики выполнения, не изменяя ее значение? В принципе можно, есть несколько способов.
К примеру для того, чтобы выполнить скрипт, достаточно открыть его в проводнике, кликнуть правой клавишей мыши и выбрать пункт Выполнить с помощью PowewrShell (Run with PowerShell). Это запускает оболочку PowerShell c политикой Bypass. При этом политика применяется только для выполнения конкретного скрипта, значение политики в реестре не изменяется.
Этот способ называется ″Run with PowerShell″ и у него есть некоторые ограничения. Скрипты, запущенные таким образом, не могут взаимодействовать с пользователем (выводить сообщения на экран, требовать ввода данных и т.п.). Скрипт просто запускается, выполняется и немедленно закрывается.
Собственно говоря, предыдущий способ использует запуск PowerShell с указанием требуемой политики. Сделать это можно из командной строки, например для запуска скрипта можно попробовать такую команду:
Теоретически эта команда должна выполнить скрипт, не смотря на текущую политику. Так написано в официальной документации Microsoft. На практике же этот способ работает не всегда, например на одном из проверенных мной компьютеров я получил ошибку. При этом из проводника скрипт успешно выполнился.
Еще один вариант — это попробовать изменить политику выполнения для области Process. Эта операция не вносит изменений в реестр и не требует прав администратора. Но в том случае, если для назначения политики выполнения используются групповые политики, этот способ не сработает.
Ну и наконец можно просто считать содержимое скрипта и выполнить его в виде команды. Например так: