А АSunday 24 October 2021

PowerShell Security book #2.

Hi all.

Today I would like to present second part of my resume by e-book "PowerShell Security".

JEA.

I don't know if I need to describe JEA again. Ok, I will write about it very shortly today. So, by default, there are three Session Configurations on each Windows computer, namely: 

  • microsoft.powershell, 
  • microsoft.powershell.workflow,
  • microsoft.windows.server-managerworkflows.

1) Get-PSSessionConfiguration

Define "HelpDesk" configuration:

Register-PSSessionConfiguration -Name HelpDesk

This opens the dialog you already know from managing file permissions:

Register-PSSessionConfiguration -Name HelpDesk -ShowSecurityDescriptorUI

Defining RunsAs users:

Register-PSSessionConfiguration -Name HelpDesk -RunAsCredential forza.com\MikeLee

Set additional options via configuration file:

New-PSSessionConfigurationFile -Path .\MyConfig.pssc

The following are particularly useful to prevent users from potentially harmful actions:

-languageMode with the values FullLanguage, RestrictedLanguage, ConstrainedLanguage, NoLanguage: The latter allows only the exe-cution of cmdlets and functions, other language resources are not available. 

FullLanguage offers the full range of language capabilities, the other two lie between these two poles.

-VisibleAliases, VisibleCmdlets, VisibleFunctions, VisibleProviders: These allow you to specify which aliases, cmdlets, functions, and providers are available in the session. 

You can use wildcards and specify multiple values as array.

Example:

New-PSSessionConfigurationFile -Path .\MyConfig.pssc -VisibleCmdlets "Get*","Select*"

You adjust the Session Configuration based on this file:

Set-PSSessionConfiguration -Name HelpDesk -Path .\MyConfig.pssc

Enter-PSSession -ComputerName Remote-PC -ConfigurationName HelpDesk

-OR-

Invoke-Command -ComputerName Remote-PC -ConfigurationName Helpdesk {Get-ChildItem}

2) New-PSRoleCapabilityFile -Path MyRCF.psrc

-OR-

JEA Helper Tool create MyRCF.psrc

Once you have created the list of permitted cmdlets and parameters, you can add them to the .psrc file. You save this file in a directory called RoleCapabilities under

$env:ProgramFiles\WindowsPowerShell\Modules

The last step is to link the role capabilities to the desired session configu-ration. To do this, edit the configuration file with the extension .pssc and add the role functions there.

Since you create this file automatically at the beginning, this (commented out) section for RoleDefinitions should already be there:

RoleDefinitions = @{ 'CONTOSO\SqlAdmins' = ` @{ RoleCapabilities = 'SqlAdministration' }; 

'CONTOSO\SqlManaged' = @{ RoleCapabilityFiles = 'C:\RoleCapability\SqlManaged.psrc' }; 

'CONTOSO\ServerMonitors' = ` @{ VisibleCmdlets = 'Get-Process' } }

Ok, if I told you early you can find more information about it here. I'm not sure that JEA will have good features in the nearest future.

Audit.

You can perform audit of execution scripts by:

1) enable transcription:

we are using Start-Transcript and Stop-Transcript cmdlets.

2) configure GPO:

Policies > Administrative Templates > Windows Components > Windows PowerShell > PowerShell Transcription

-OR-

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\PowerShellCore\Transcription] 

"EnableTranscripting"=dword:00000001 

"OutputDirectory"="\\server\\pslogs"


3) setup scriptblock logging by GPO or Registry:

turn on PowerShell Script Block Logging and can be found under Policies > Administrative Templates > Windows Components > Windows PowerShell. 

-OR-

Script block logging for PowerShell Core:

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Pow-erShellCore\ScriptBlockLogging] 

"EnableScriptBlockLogging"=dword:00000001

        Example: application log under Microsoft=> Windows => PowerShell => Operational, and the commands are recorded under Scriptblock logging: record commands in the event log 109 event ID 4104. If you also record start and stop events, these appear under the IDs 4105 and 4106.

In event viewer activate as Source:

  • PowerShell (Microsoft-Windows-PowerShell)
  • PowerShell (PowerShell)
  • PowerShellCore.

Merging command sequences by ID 6524:

$created = Get-WinEvent -FilterHashtable ` @{ProviderName="Microsoft-Windows-PowerShell"; Id=4104} | where ProcessId -eq 6524

$sortedScripts = $created | sort {$_.Properties[0].Value} $mergedScript = -join ($sortedScripts | foreach {$_.Properties[2].Value})

4) enable encryption events. Wow, is't possible? Sure!

Template of certification:

[Version]

Signature = "$Windows NT$"

[Strings]

szOID_ENHANCED_KEY_USAGE = "2.5.29.37"

szOID_DOCUMENT_ENCRYPTION = "1.3.6.1.4.1.311.80.1"

[NewRequest]

Subject = "cryptme@forza.com"

MachineKeySet = false

KeyLength = 2048

KeySpec = AT_KEYEXCHANGE

HashAlgorithm = Sha1

Exportable = true

RequestType = Cert

KeyUsage = "CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERT_DATA_ENCIPHERMENT_KEY_USAGE"

ValidityPeriod = "Years"

ValidityPeriodUnits = "1000"

[Extensions]

%szOID_ENHANCED_KEY_USAGE% = "{text}%szOID_DOCUMENT_EN-CRYPTION%"


        4.1) Request:

To request the certificate, use the command:

certreq -new <INF-file-name>.inf <Certificate-name>.cer


The certificate is automatically copied to the local certificate store of the logged-on user.


4.2) Encode event: 

To enable secure event logging, Microsoft provides a setting in Group Policy. 

It is called Enable Protected Event Logging and can be found under Computer Configuration => 

Policies => Administrative Templates => Windows Components => Event Logging.


4.3) Decode event:

$msg = Get-WinEvent Microsoft-Windows-PowerShell/Operational -ComputerName myPC -MaxEvents 2 -Credential domain\user

"Last log entry as clear text:"

$msg[1] | select -ExpandProperty Message | Unprotect-CmsMessage

# $msg[0] is always "prompt"


4.4) Protect something:

The process is relatively simple. Protect-CmsMessage expects the input file via the Path  parameter.  Alternatively, you can provide the contents to be encrypted via the Content parameter or via a pipeline. The target file is specified via OutFile; otherwise, the output is stdout.

$protected = "Hello World"| Protect-CmsMessage -To BDDSAFASFRTNB380HGG657687GFDR

$protected | Unprotect-CmsMessage


5) in Registry as with auditing the file system, three measures are required:

  • Enable registry monitoring via GPO
  • Configure the system access control list (SACL) for the resource in question
  • Analyze the event log.

5.1) Activate registry auditing:

Computer Configuration => Policies => Windows Settings => Security Settings => 

        Advanced Audit Policy Configuration => Audit Policies => Object Access > Audit Registry.

(Microsoft has deprecated the settings under Security Settings => Local Policies => Audit Policy Win7)

5.2) Setting permissions for registry keys

When changing the SACL of this key in the registry of many computers, it makes sense to use a GPO.  You can configure the necessary setting under Computer Configuration => Policies => Windows Settings => Security Set-tings => Registry.

5.3) You can retrieve these logs with PowerShell as follows:

Get-EventLog -LogName Security -Source "*auditing*" -InstanceId 4657,4660


Refactoring.

Of course, you have to maintain you code corresponding to clearance and best standards. For it you can use Strict mode: Set-StrictMode -Version Latest

Also analyzing your code by ScriptAnalyzer is good practice.

ScriptAnalyzer features:

Get-Command -Module PSScriptAnalyzer

  • Get-ScriptAnalyzerRule
  • Invoke-ScriptAnalyzer
  • Invoke-Formatter.

ScriptAnalyzer step by step:

1) Get-ScriptAnalyzerRule -Severity Error

2) $file = Get-Content -Raw -Path .\MyCheck.ps1

   Invoke-ScriptAnalyzer -Path .\MyCheck.ps1 -Fix

3) Invoke-Formatter -ScriptDefinition '{ $_.Status.IsCompleted -eq $true }'

# where scriptDefinition is

$scriptDefinition = @'

function foo {

"Hello of all"

}

'@


# where settings is

$settings = @{

    IncludeRules = @("PSPlaceOpenBrace", "PSUseConsistentIndentation")

    Rules = @{

        PSPlaceOpenBrace = @{

            Enable = $true

            OnSameLine = $false

        }

        PSUseConsistentIndentation = @{

            Enable = $true

        }

    }

}

# and do it

Invoke-Formatter -ScriptDefinition $scriptDefinition -Settings $settings

End. Good luck.

No comments:

Post a Comment

А что вы думаете по этому поводу?

Версия на печать

Популярное