Unusually Long PowerShell CommandLine
A Sigma rule for process creation on Windows, from SigmaHQ’s threat hunting rules, by oscd.community, Natalia Shornikova.
low 1 ATT&CK technique 2 programs it names 10 everyday examples trip it
What it looks for
detection:
selection_length:
CommandLine|re: '.{1000,}'
selection_powershell:
- Image|endswith:
- '\powershell.exe'
- '\pwsh.exe'
- OriginalFileName:
- 'PowerShell.EXE'
- 'pwsh.dll'
- Description: 'Windows Powershell'
- Product: 'PowerShell Core 6'
condition: all of selection_*
The rule’s detection, its selections and fields in order of name. The whole rule, with its references and false positives, is on SigmaHQ, by oscd.community, Natalia Shornikova, under the Detection Rule License 1.1. CmdID evaluates it on a command line alone: a test on what a command line cannot show, such as the parent process or the user, is not met.
Command lines that trip it
Effects of disabling a session configuration on the page for Disable-PSSessionConfiguration
PS> Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto
Name Permission
---- ----------
MaintenanceShell BUILTIN\Administrators AccessAllowed
microsoft.powershell BUILTIN\Administrators AccessAllowed
microsoft.powershell32 BUILTIN\Administrators AccessAllowed
PS> Disable-PSSessionConfiguration -Name MaintenanceShell -Force
PS> Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto
Name Permission
---- ----------
MaintenanceShell Everyone AccessDenied, BUILTIN\Administrators AccessAllowed
microsoft.powershell BUILTIN\Administrators AccessAllowed
microsoft.powershell32 BUILTIN\Administrators AccessAllowed
PS> New-PSSession -ComputerName localhost -ConfigurationName MaintenanceShell
[localhost] Connecting to remote server failed with the following error message : Access is denied.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailedIdentifyExample 3 - Using multiple PSSessions on multiple computers on the page for Disconnect-PSSession
PS> $s = New-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask
PS> Invoke-Command $s -FilePath \\Server01\Scripts\Get-PatchStatus.ps1
PS> Get-PSSession -Name ITTask -ComputerName Srv1 | Disconnect-PSSession
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 ITTask Srv1 Disconnected Microsoft.PowerShell None
PS> Get-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 ITTask Srv1 Disconnected Microsoft.PowerShell None
2 ITTask Srv2 Opened Microsoft.PowerShell Available
3 ITTask Srv30 Opened Microsoft.PowerShell Available
PS> Get-PSSession -ComputerName Srv1 -Name ITTask -Credential Domain01\User01
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 ITTask Srv1 Disconnected Microsoft.PowerShell None
PS> $s = Connect-PSSession -ComputerName Srv1 -Name ITTask -Credential Domain01\User01
PS> Invoke-Command -Session $s {dir $HOME\Scripts\PatchStatusOutput.ps1}
PS> Invoke-Command -Session $s {mkdir $HOME\Scripts\PatchStatusOutput}
PS> Invoke-Command -Session $s -FilePath \\Server01\Scripts\Get-PatchStatus.ps1
PS> Disconnect-PSSession -Session $sIdentifyExample 4 - Change the timeout value for a PSSession on the page for Disconnect-PSSession
PS> $Timeout = New-PSSessionOption -IdleTimeout 172800000
PS> $s = New-PSSession -Computer Server01 -Name ITTask -SessionOption $Timeout
PS> Disconnect-PSSession -Session $s
Disconnect-PSSession : The session ITTask cannot be disconnected because the specified
idle timeout value 172800(seconds) is either greater than the server maximum allowed
43200 (seconds) or less that the minimum allowed60(seconds). Choose an idle time out
value that is within the allowed range and try again.
PS> Invoke-Command -ComputerName Server01 {Get-PSSessionConfiguration Microsoft.PowerShell} |
Format-List -Property *
Architecture : 64
Filename : %windir%\system32\pwrshplugin.dll
ResourceUri : http://schemas.microsoft.com/powershell/microsoft.powershell
MaxConcurrentCommandsPerShell : 1000
UseSharedProcess : false
ProcessIdleTimeoutSec : 0
xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration
MaxConcurrentUsers : 5
lang : en-US
SupportsOptions : true
ExactMatch : true
RunAsUser :
IdleTimeoutms : 7200000
PSVersion : 3.0
OutputBufferingMode : Block
AutoRestart : false
SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)
MaxMemoryPerShellMB : 1024
MaxIdleTimeoutMs : 2147483647
Uri : http://schemas.microsoft.com/powershell/microsoft.powershell
SDKVersion : 2
Name : microsoft.powershell
XmlRenderingType : text
Capability : {Shell}
RunAsPassword :
MaxProcessesPerShell : 15
ParentResourceUri : http://schemas.microsoft.com/powershell/microsoft.powershell
Enabled : true
MaxShells : 25
MaxShellsPerUser : 25
Permission : BUILTIN\Administrators AccessAllowed
PSComputerName : localhost
RunspaceId : aea84310-6dbf-4c21-90ac-13980039925a
PSShowComputerName : True
PS> $s.Runspace.ConnectionInfo
ConnectionUri : http://Server01/wsman
ComputerName : Server01
Scheme : http
Port : 80
AppName : /wsman
Credential :
ShellUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell
AuthenticationMechanism : Default
CertificateThumbprint :
MaximumConnectionRedirectionCount : 5
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize : 209715200
UseCompression : True
NoMachineProfile : False
ProxyAccessType : None
ProxyAuthentication : Negotiate
ProxyCredential :
SkipCACheck : False
SkipCNCheck : False
SkipRevocationCheck : False
NoEncryption : False
UseUTF16 : False
OutputBufferingMode : Drop
IncludePortInSPN : False
Culture : en-US
UICulture : en-US
OpenTimeout : 180000
CancelTimeout : 60000
OperationTimeout : 180000
IdleTimeout : 172800000
PS> Disconnect-PSSession $s -IdleTimeoutSec 43200
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
4 ITTask Server01 Disconnected Microsoft.PowerShell None
PS> $s.Runspace.ConnectionInfo.IdleTimeout
43200000IdentifyFormat the properties of a culture object on the page for Get-Culture
PS C:> $C = Get-Culture
PS C:> $C | Format-List -Property *
Parent : en
LCID : 1033
KeyboardLayoutId : 1033
Name : en-US
IetfLanguageTag : en-US
DisplayName : English (United States)
NativeName : English (United States)
EnglishName : English (United States)
TwoLetterISOLanguageName : en
ThreeLetterISOLanguageName : eng
ThreeLetterWindowsLanguageName : ENU
CompareInfo : CompareInfo - 1033
TextInfo : TextInfo - 1033
IsNeutralCulture : False
CultureTypes : SpecificCultures, InstalledWin32Cultures, FrameworkCultures
NumberFormat : System.Globalization.NumberFormatInfo
DateTimeFormat : System.Globalization.DateTimeFormatInfo
Calendar : System.Globalization.GregorianCalendar
OptionalCalendars : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar}
UseUserOverride : True
IsReadOnly : False
PS C:> $C.Calendar
MinSupportedDateTime : 1/1/0001 12:00:00 AM
MaxSupportedDateTime : 12/31/9999 11:59:59 PM
AlgorithmType : SolarCalendar
CalendarType : Localized
Eras : {1}
TwoDigitYearMax : 2029
IsReadOnly : False
PS C:> $C.DateTimeFormat
AMDesignator : AM
Calendar : System.Globalization.GregorianCalendar
DateSeparator : /
FirstDayOfWeek : Sunday
CalendarWeekRule : FirstDay
FullDateTimePattern : dddd, MMMM dd, yyyy h:mm:ss tt
LongDatePattern : dddd, MMMM dd, yyyy
LongTimePattern : h:mm:ss tt
MonthDayPattern : MMMM dd
PMDesignator : PM
RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern : M/d/yyyy
ShortTimePattern : h:mm tt
SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern : MMMM, yyyy
AbbreviatedDayNames : {Sun, Mon, Tue, Wed...}
ShortestDayNames : {Su, Mo, Tu, We...}
DayNames : {Sunday, Monday, Tuesday, Wednesday...}
AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...}
MonthNames : {January, February, March, April...}
IsReadOnly : False
NativeCalendarName : Gregorian Calendar
AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...}
MonthGenitiveNames : {January, February, March, April...}
PS C:> $C.DateTimeFormat.FirstDayOfWeek
SundayIdentifyCompare the types of files system drives on the page for Get-PSDrive
PS C:> Get-PSDrive -PSProvider FileSystem
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
A A:\
C 202.06 23718.91 FileSystem C:\
D 1211.06 123642.32 FileSystem D:\
G 202.06 710.91 FileSystem \\Music\GratefulDead
X Registry HKLM:\Network
PS C:> net use
New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK G: \\Server01\Public Microsoft Windows Network
PS C:> [System.IO.DriveInfo]::GetDrives() | Format-Table
Name DriveType DriveFormat IsReady AvailableFreeSpace TotalFreeSpace TotalSize RootDirectory VolumeLabel
---- --------- ----------- ------- ------------------ -------------- --------- ------------- -----------
A:\ Network False A:\
C:\ Fixed NTFS True 771920580608 771920580608 988877418496 C:\ Windows
D:\ Fixed NTFS True 689684144128 689684144128 1990045179904 D:\ Big Drive
E:\ CDRom False E:\
G:\ Network NTFS True 69120000 69120000 104853504 G:\ GratefulDead
PS N:> Get-CimInstance -Class Win32_LogicalDisk
DeviceID DriveType ProviderName VolumeName Size FreeSpace
-------- --------- ------------ ---------- ---- ---------
A: 4
C: 3 Windows 988877418496 771926069248
D: 3 Big! 1990045179904 689684144128
E: 5
G: 4 \\Music\GratefulDead 988877418496 771926069248
PS C:> Get-CimInstance -Class Win32_NetworkConnection
LocalName RemoteName ConnectionState Status
--------- ---------- --------------- ------
G: \\Music\GratefulDead Connected OKIdentifyCreate a sample configuration file on the page for New-PSSessionConfigurationFile
$configSettings = @{
Path = '.\SampleFile.pssc'
SchemaVersion = '1.0.0.0'
Author = 'User01'
Copyright = '(c) Fabrikam Corporation. All rights reserved.'
CompanyName = 'Fabrikam Corporation'
Description = 'This is a sample file.'
ExecutionPolicy = 'AllSigned'
PowerShellVersion = '3.0'
LanguageMode = 'FullLanguage'
SessionType = 'Default'
EnvironmentVariables = @{TESTSHARE='\\Test2\Test'}
ModulesToImport = @{ModuleName='PSScheduledJob'; ModuleVersion='1.0.0.0'; GUID='50cdb55f-5ab7-489f-9e94-4ec21ff51e59'},'PSDiagnostics'
AssembliesToLoad = 'System.Web.Services','FSharp.Compiler.CodeDom.dll'
TypesToProcess = 'Types1.ps1xml','Types2.ps1xml'
FormatsToProcess = 'CustomFormats.ps1xml'
ScriptsToProcess = 'Get-Inputs.ps1'
AliasDefinitions = @{Name='hlp';Value='Get-Help';Description='Gets help.';Options='AllScope'},
@{Name='Update';Value='Update-Help';Description='Updates help';Options='ReadOnly'}
FunctionDefinitions = @{Name='Get-Function';ScriptBlock={Get-Command -CommandType Function};Options='ReadOnly'}
VariableDefinitions = @{Name='WarningPreference';Value='SilentlyContinue'}
VisibleAliases = 'c*','g*','i*','s*'
VisibleCmdlets = 'Get*'
VisibleFunctions = 'Get*'
VisibleProviders = 'FileSystem','Function','Variable'
RunAsVirtualAccount = $true
RunAsVirtualAccountGroups = 'Backup Operators'
}
New-PSSessionConfigurationFile @configSettings
Get-Content SampleFile.psscIdentifyGet results after a network outage on the page for Receive-PSSession
PS> $s = New-PSSession -ComputerName Server01 -Name AD -ConfigurationName ADEndpoint
PS> $s
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
8 AD Server01 Opened ADEndpoint Available
PS> Invoke-Command -Session $s -FilePath \\Server12\Scripts\SharedScripts\New-ADResolve.ps1
Running "New-ADResolve.ps1"
# Network outage
# Restart local computer
# Network access is not re-established within 4 minutes
PS> Get-PSSession -ComputerName Server01
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 Backup Server01 Disconnected Microsoft.PowerShell None
8 AD Server01 Disconnected ADEndpoint None
PS> Receive-PSSession -ComputerName Server01 -Name AD -OutTarget Job -JobName AD
Job Id Name State HasMoreData Location
-- ---- ----- ----------- --------
16 ADJob Running True Server01
PS> Get-PSSession -ComputerName Server01
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 Backup Server01 Disconnected Microsoft.PowerShell Busy
8 AD Server01 Opened ADEndpoint AvailableIdentifyReconnect to disconnected sessions on the page for Receive-PSSession
PS> $parms = @{
InDisconnectedSession = $true
ComputerName = "Server01", "Server02", "Server30"
FilePath = "\\Server12\Scripts\SharedScripts\Get-BugStatus.ps1"
Name = "BugStatus"
SessionOption = @{IdleTimeout = 86400000}
ConfigurationName = "ITTasks"
}
PS> Invoke-Command @parms
PS> exit
PS> $s = Get-PSSession -ComputerName Server01, Server02, Server30 -Name BugStatus
PS> $s
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 ITTask Server01 Disconnected ITTasks None
8 ITTask Server02 Disconnected ITTasks None
2 ITTask Server30 Disconnected ITTasks None
PS> $Results = Receive-PSSession -Session $s
PS> $s
Id Name ComputerName State ConfigurationName Availability
-- ---- ------------ ----- ----------------- ------------
1 ITTask Server01 Opened ITTasks Available
8 ITTask Server02 Opened ITTasks Available
2 ITTask Server30 Opened ITTasks Available
PS> $Results
Bug Report - Domain 01
----------------------
ComputerName BugCount LastUpdated
-------------- --------- ------------
Server01 121 Friday, December 30, 2011 5:03:34 PMIdentifyUnregister without a restart on the page for Unregister-PSSessionConfiguration
PS> Unregister-PSSessionConfiguration -Name "MaintenanceShell" -NoServiceRestart
PS> Get-PSSessionConfiguration -Name "MaintenanceShell"
Get-PSSessionConfiguration -Name MaintenanceShell : No Session Configuration matches criteria "MaintenanceShell".
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
PS> New-PSSession -ConfigurationName "MaintenanceShell"
Id Name ComputerName State Configuration Availability
-- ---- ------------ ----- ------------- ------------
1 Session1 localhost Opened MaintenanceShell Available
PS> Restart-Service winrm
PS> New-PSSession -ConfigurationName MaintenanceShell
[localhost] Connecting to remote server failed with the following error message :
The WS-Management service cannot process the request.
The resource URI (http://schemas.microsoft.com/powershell/MaintenanceShell) was not found in the WS-Management catalog.
The catalog contains the metadata that describes resources, or logical endpoints.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionOpenFailedIdentifyInsert breakpoint for debugging a DSC resource on the page for Wait-Debugger
[DscResource()]
class FileResource
{
[DscProperty(Key)]
[string] $Path
[DscProperty(Mandatory)]
[Ensure] $Ensure
[DscProperty(Mandatory)]
[string] $SourcePath
[DscProperty(NotConfigurable)]
[Nullable[datetime]] $CreationTime
[void] Set() {
$fileExists = $this.TestFilePath($this.Path)
if ($this.Ensure -eq [Ensure]::Present) {
if (! $fileExists) {
$this.CopyFile()
}
} else {
if ($fileExists) {
Write-Verbose -Message "Deleting the file $($this.Path)"
Remove-Item -LiteralPath $this.Path -Force
}
}
}
[bool] Test() {
$present = Test-Path -LiteralPath $this.Path
if ($this.Ensure -eq [Ensure]::Present) {
return $present
} else {
return (! $present)
}
}
[FileResource] Get() {
$present = Test-Path -Path $this.Path
if ($present) {
$file = Get-ChildItem -LiteralPath $this.Path
$this.CreationTime = $file.CreationTime
$this.Ensure = [Ensure]::Present
} else {
$this.CreationTime = $null
$this.Ensure = [Ensure]::Absent
}
return $this
}
[void] CopyFile() {
# Testing only - Remove before deployment!
Wait-Debugger
if (! (Test-Path -LiteralPath $this.SourcePath)) {
throw "SourcePath $($this.SourcePath) is not found."
}
if (Test-Path -LiteralPath $this.Path -PathType Container) {
throw "Path $($this.Path) is a directory path"
}
Write-Verbose "Copying $($this.SourcePath) to $($this.Path)"
Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force
}
}Identify