Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 34 ยท Real-World Use

Security and Secrets

Write safer PowerShell: what SecureString really protects, SecretManagement, least privilege, constrained language mode, script block logging and injection pitfalls.

PowerShell is powerful, and that is exactly why security matters. A script often runs with an administrator's rights, reads passwords, calls APIs and touches hundreds of machines. A small mistake, such as a token committed to git or a user value pasted into a command string, can turn a helpful script into an entry point for an attacker. The good news is that a handful of habits cover most of the risk.

In this lesson you will learn what SecureString does and does not protect, how to store secrets with the SecretManagement module, how to run with least privilege, what constrained language mode and script block logging are, and how injection happens. The security features belong to real PowerShell and Windows, so their commands are read-only. Two runnable stand-ins in JavaScript show the injection problem and the "wrap and redact" idea. They are models, not security tools.

Where scripts go wrong

Five habits that matter

Keep secrets out Not in scripts, not in git, not in logs.
Least privilege Run with only the rights the job needs.
No string commands Pass arguments as data, never as code.
Log and audit Know what ran, and when.
1 / 2

SecureString: useful, but not a vault

SecureString is a .NET type that holds text without showing it. Printing one shows only the type name, and Get-Credential returns a PSCredential whose Password is a SecureString. Many cmdlets, such as Invoke-RestMethod -Authentication Bearer -Token, require one. That makes it a useful marker: it tells you and the cmdlet that this value is sensitive.

POWERSHELL
$token = Read-Host -Prompt 'Token' -AsSecureString     # typed value is not echoed
$token                                                  # System.Security.SecureString

$cred = Get-Credential -UserName 'svc-report'
$cred.UserName
$cred.Password                                          # a SecureString

But a SecureString is a weak protection, and you should know its limits:

  • Anyone whose code runs in your session can turn it back into plain text. ConvertFrom-SecureString -AsPlainText (PowerShell 7) does it in one step.
  • Creating one from a normal string, ConvertTo-SecureString 'x' -AsPlainText -Force, means the plain text already existed in your script and in memory.
  • On Windows, ConvertFrom-SecureString and Export-Clixml encrypt with the Data Protection API (DPAPI), tied to that user on that machine. A file made this way cannot be read elsewhere, which is useful for local scheduled tasks and useless for sharing. On Linux and macOS, Export-Clixml does not encrypt the password, so the file holds it in readable form.
  • Microsoft's own .NET guidance advises against SecureString for new code, because it cannot give strong guarantees.

Treat it as a convenience for APIs that ask for it, not as a safe.

SecretManagement: one interface, many vaults

Better than files is a real secret store. The SecretManagement module gives you one set of commands, and you plug in a vault behind it. SecretStore is a local, encrypted vault for your user, and extensions exist for Azure Key Vault, KeePass and others.

POWERSHELL
Install-Module Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore

Register-SecretVault -Name LocalStore `
    -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault

Set-Secret -Name ReportApiToken -Secret (Read-Host -AsSecureString)
Get-SecretInfo                                  # names and types, never the values

$token = Get-Secret -Name ReportApiToken        # returns a SecureString
Invoke-RestMethod -Uri 'https://api.example.com/me' -Authentication Bearer -Token $token

The script mentions only the name of the secret, so the script can live in git and be shared. Each person or each server holds its own value in its own vault. When you move to production, you can swap the vault (for example to Azure Key Vault) without changing the script, because it still calls Get-Secret. Use Get-Secret -AsPlainText only for the rare tool that insists on plain text, and keep the result in a variable for as short a time as possible. More on calling APIs is in Web Requests and REST APIs.

A stand-in: wrapping and redacting

The idea behind these features is to make accidental disclosure harder. This model wraps a value so that printing, string interpolation and JSON conversion all show a placeholder, and adds a redaction function for log lines. It also proves the limit: code that can call reveal() can still read the value.

JS Stand-in: a secret that hides itself

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The lesson from the demo: wrapping stops accidents (a stray Write-Host), not attackers who already run code as you. Real protection comes from keeping the value in a vault with access control, and keeping untrusted code away from your session.

Least privilege

A script should run with the fewest rights that let it do the job. Do not start PowerShell as administrator out of habit, and do not give a scheduled task a domain admin account because it was easy. Practical steps:

  • Create a dedicated service account (on Windows domains, a group managed service account if you can) with only the permissions the task needs.
  • Use #Requires -RunAsAdministrator at the top of scripts that truly need elevation, so they stop with a clear message instead of failing halfway.
  • For delegated administration, Just Enough Administration (JEA) lets a user connect to a restricted remote session that exposes only chosen commands, as described in Remoting, Jobs and Parallelism.
  • Check Scripts and Execution Policy: execution policy is a safety belt against accidents, not a security boundary, since a user can bypass it for their own session.
  • Sign scripts you distribute and keep the signing certificate protected.

Constrained language mode

PowerShell has language modes that decide what code may do. In the normal FullLanguage mode a script can use any .NET type and method. In ConstrainedLanguage mode, PowerShell blocks the risky parts: arbitrary .NET types, Add-Type, COM objects and many method calls, while ordinary cmdlets still work.

POWERSHELL
$ExecutionContext.SessionState.LanguageMode     # FullLanguage or ConstrainedLanguage

The right way to enforce the mode on a machine is through an application control policy such as App Control for Business (WDAC) or AppLocker. When such a policy is active, PowerShell switches to constrained mode for scripts that are not trusted, and allows full language only to approved ones. Do not try to lock a machine by setting an environment variable, because users can change it, so it is not a defence. For your own scripts the lesson is: avoid exotic .NET tricks when a cmdlet will do, because simple scripts keep working in locked-down environments.

Script block logging and transcripts

Defenders need to see what PowerShell ran. Windows can record this, controlled by Group Policy or the registry:

  • Script block logging records the text of the code PowerShell compiles, in the Microsoft-Windows-PowerShell/Operational event log as event ID 4104. Obfuscated code is logged in its decoded form when it runs, which makes it very useful for investigations.
  • Module logging records pipeline execution details for chosen modules.
  • Transcription writes input and output of sessions to text files (Start-Transcript does it for a single session).

Anything you put in a script or on its command line may therefore end up in a log that many people can read. That is one more reason never to hard-code secrets: not only git, but event logs and transcripts would keep them. Fetch secrets at run time with Get-Secret, and keep them in variables that are never printed.

Injection: do not build code from data

Injection happens when untrusted text becomes part of a command that is then executed. In PowerShell the usual culprit is Invoke-Expression (alias iex), which runs a string as code, or building a command line by joining strings.

POWERSHELL
# DANGEROUS: if $name is  . ; Remove-Item -Recurse C:\data  it runs the second command
Invoke-Expression "Get-ChildItem $name"

# SAFE: $name is passed as one argument, whatever characters it contains
Get-ChildItem -LiteralPath $name

# SAFE for external programs: an array of arguments, not one big string
$arguments = @('--output', $outputFile, $name)
& 'C:\Tools\exporter.exe' @arguments

Rules that prevent most problems:

  1. Almost never use Invoke-Expression. Parse data with a parser (ConvertFrom-Json, Import-Csv) and call commands with parameters.
  2. Use -LiteralPath for file names that come from outside, so characters such as [ and * are not treated as wildcards.
  3. Validate input with [ValidateSet()], [ValidatePattern()] and [ValidateRange()] (see Advanced Functions), and reject what you do not expect rather than trying to clean it.
  4. Use parameterized queries when talking to databases, never string-built SQL.
  5. Remember that Start-Process -ArgumentList and -Command take strings that another shell will parse again.

The stand-in below shows why arguments as data are safe. A pretend shell splits a command line on ; the way an interpreter would, while an argument array stays one value no matter what it contains.

JS Stand-in: string commands vs argument arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first run two commands appear, so the attacker's text was executed. In the second, the whole value is one argument to Get-ChildItem, which will simply report that no such path exists.

A short security checklist

  • Keep secrets in a vault; reference them by name.
  • Run with a dedicated, minimal account; require elevation only when needed.
  • Do not rely on execution policy, and sign what you distribute.
  • Write simple code that works in constrained language mode.
  • Assume script blocks and command lines are logged.
  • Treat every outside value as data: no Invoke-Expression, use -LiteralPath, validate parameters.
  • Review modules before you install them from the PowerShell Gallery, and pin versions in production (see Modules and Profiles).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about SecureString is correct?

    SecureString is mostly a marker and a guard against accidents. Code running in your session can convert it back to plain text, so a real secret store is still needed.
  2. 2. What is the main advantage of Get-Secret over reading a password from a script file?

    With SecretManagement the script refers to a name, and the value lives in a vault that has its own protection. You can change vaults without changing the script.
  3. 3. Which line is vulnerable to injection if $name comes from a user?

    Invoke-Expression runs a string as code, so a value such as '. ; Remove-Item ...' adds a second command. Passing the value as a parameter keeps it as data.
  4. 4. Where does script block logging write its events on Windows?

    Script block logging records the text of executed code in the PowerShell Operational log as event 4104, which is why secrets typed into scripts can leak there.
  5. 5. Is execution policy a reliable security boundary?

    Execution policy is a safety feature against running scripts by mistake. Real enforcement needs application control such as WDAC or AppLocker.

Summary

  • SecureString marks and hides values from accidents, but it is not a vault, and on Linux and macOS Export-Clixml does not encrypt it.
  • Use SecretManagement (Set-Secret, Get-Secret) so scripts hold only secret names.
  • Apply least privilege: dedicated accounts, #Requires -RunAsAdministrator where needed, JEA for delegation.
  • Constrained language mode, enforced by application control, limits what code can do; simple scripts keep working in it.
  • Script block logging (event 4104) and transcripts record what ran, so never put secrets in code or command lines.
  • Avoid Invoke-Expression, pass arguments as data, use -LiteralPath and validate input.
  • The JavaScript demos model the ideas; they are not security tools.

Next: Testing and Style with Pester.