Preventing changes and execution

Preventing changes to scripts and preventing the execution of scripts are both possible by digitally signing them. Strong public-key cryptography is used to ensure the integrity of your script. Signatures can automatically be validated and used to prove changes in a script.

In order to prevent accidental or intended (that is, malicious) changes, you can leverage the PowerShell execution policy. The execution policy was originally intended to prevent users from accidentally executing scripts on their system, and to prevent malicious code from being run without the user's consent. In his blog post from 2008 (https://blogs.msdn.microsoft.com/powershell/2008/09/30/powershells-security-guiding-principles/), Lee Holmes likens it to a safety harness that can be adjusted to your liking, as seen in the following code sample:

# Show execution policy and source of it
Get-ExecutionPolicy -List

# Set execution policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process

# Start Shell with specific execution policy
pwsh.exe -ExecutionPolicy Bypass

# Executing scripts with broken signature (tampered scripts) in AllSigned mode
Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope Process

$codeSigningCert = Get-ChildItem Cert:CurrentUsermy -CodeSigningCert
New-Item -ItemType File -Path .ValidScript.ps1 -Value 'Get-Process -Id $Pid'
Set-AuthenticodeSignature -FilePath .ValidScript.ps1 -Certificate $codeSigningCert -IncludeChain all

(Get-Content -Path .ValidScript.ps1) -replace 'Get-Process', 'Stop-Process' | Set-Content .ValidScript.ps1

# Script execution will now generate an error
.ValidScript.ps1

The default execution policy for a client system (or stock-keeping unit (SKU)) is Restricted, while on a server SKU newer than 2012, it is set to RemoteSigned:

AllSigned

All scripts need to be digitally signed with a valid, trusted signature to be executed.

RemoteSigned

All downloaded scripts need to be signed with a valid, trusted signature to be executed (standard for servers).

Restricted

No scripts can be executed; PowerShell is in interactive mode only (standard for clients).

Unrestricted

All scripts can be executed. Scripts from the internet will generate a confirmation message.

Bypass

All bets are off. The least prohibitive mode, commonly used by software deployment tools, and so on.

Undefined

If all levels are undefined, results in Restricted.

 

The execution policy is, by no means, any kind of security boundary. It is simply a way to prevent accidental changes to the system. Do not get yourself lulled into a false sense of security.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.172.252