Windows powershell код события 403

Windows Powershell Critical Windows Event IDs Monitor Techhyme

PowerShell is a command-line shell and scripting language designed for Windows operating systems. It is based on the .NET framework and provides an object-oriented approach to managing and automating tasks in Windows environments.

PowerShell works by executing commands or scripts that interact with the operating system, applications, and other systems. These commands are called cmdlets, and they follow a consistent verb-noun syntax that makes it easy to remember and use them. For example, the command “Get-Process” retrieves information about the processes running on the system, while “Stop-Process” stops a process.

PowerShell supports piping, which means that the output of one command can be passed as input to another command. This makes it possible to create powerful one-liner commands that can perform complex tasks.

PowerShell also supports scripting, which allows users to create scripts that automate repetitive tasks or perform complex operations. PowerShell scripts can be saved as .ps1 files and executed like any other command-line program.

PowerShell provides a powerful set of features for managing and automating Windows environments. It is highly extensible, and users can create their own custom cmdlets, functions, and modules to enhance its capabilities. Its object-oriented approach, consistent syntax, and support for piping and scripting make it a popular tool among system administrators, developers, and power users.

Windows PowerShell is a powerful command-line tool used for managing and automating tasks in Windows environments. However, PowerShell can also be used maliciously by attackers to gain unauthorized access to systems and steal sensitive information. Therefore, monitoring PowerShell events is crucial to detect and respond to potential security threats.

Here are some of the top critical Windows PowerShell event IDs that you should monitor:

Event ID Description
400 Logged when a PowerShell command encounters a runtime error
403 Logged when a PowerShell command execution is blocked due to a script execution policy
600 Logged when a PowerShell command is executed with elevated privileges
800 Logged when a PowerShell command is executed remotely using PowerShell remoting
4103 Logged when PowerShell module logging is enabled and a module is loaded or unloaded
4104 Logged when PowerShell script block logging is enabled and a script block is executed
8003 Logged when PowerShell transcription is enabled and a PowerShell command is executed
  • Event ID 400: This event is logged when a PowerShell command encounters a runtime error, such as a syntax error or an exception.
  • Event ID 403: This event is logged when a PowerShell command execution is blocked due to a script execution policy.
  • Event ID 600: This event is logged when a PowerShell command is executed with elevated privileges, such as administrator-level access.
  • Event ID 800: This event is logged when a PowerShell command is executed remotely using PowerShell remoting.
  • Event ID 4103: This event is logged when PowerShell module logging is enabled and a module is loaded or unloaded.
  • Event ID 4104: This event is logged when PowerShell script block logging is enabled and a script block is executed.
  • Event ID 8003: This event is logged when PowerShell transcription is enabled and a PowerShell command is executed. Transcription logs record all the input and output of a PowerShell command, making it a valuable source of forensic data.

By monitoring these critical PowerShell event IDs, you can detect and respond to potential security threats and ensure the security and integrity of your Windows environment.

You may also read:

“Huh, that’s weird. Look at this system. I think the attacker used PowerShell.” It was late summer 2012, and we were working on an incident response investigation for a Fortune 100 technology company compromised by an intruder attempting to steal intellectual property. The evidence wasn’t terribly exciting: just a simple reconnaissance script to enumerate domain users and systems. But it was an anomaly – or at least, a rare occurrence within the scope of our previous case work. We conduct hundreds of incident response investigations every year, most of which involve targeted attacks for the purposes of espionage, stealing intellectual property, or theft of financial data. Attacker tools, tactics, and procedures regularly change and evolve – and PowerShell was a new wrinkle.

Fast forward almost two years later. Stories of PowerShell usage in both targeted compromises and opportunistic malware are hitting infosec media with alarming frequency. We also see these trends in our daily casework: an increasing number of investigations involve attacker reconnaissance, command execution, or data theft facilitated by PowerShell. Just a few months ago, we responded to a case where the attacker evolved from relying on custom tools and PsExec, to exclusive use of PowerShell remoting, for lateral movement and command-and-control (and thereby evaded detection for many months). The gap between attackers’ PowerShell skills, and organizations’ ability to detect and respond to its misuse, is growing.

Prior articles by Matthew Graeber, Joseph Bialek, and Will Schroeder did a great job of explaining why PowerShell is so dangerous in the hands of an attacker – particularly given elevated privileges during the post-exploitation phase of an incident. It provides:

  • A built-in mechanism for remote command execution
  • The ability to execute malicious code without ever touching disk
  • The ability to evade many Anti-Virus and Intrusion Prevention Systems
  • Full access to WMI and .NET Framework

The unauthorized use of PowerShell presents several challenges to forensic analysts and system administrators alike:

  • As a legitimate component of Windows, PowerShell execution does not necessarily indicate malicious behavior.
  • PowerShell 2.0 does not provide a practical mechanism for detailed (e.g. per-command) auditing. PowerShell 3.0 and later provides comprehensive module logging – but is only installed by default on Windows 8 or Server 2012, which remain uncommon in many corporate environments.
  • PowerShell remoting sessions occur in ephemeral process memory with few-to-no persistent artifacts.
  • Many system administrators and security professionals remain unfamiliar with PowerShell and its management or security controls.

Faced with these mounting challenges, we decided to research the forensic “footprints” left behind by the ways that an attacker might use PowerShell – a topic for which publicized information is scarce. Our work focused on three fundamental scenarios: local PowerShell execution, PowerShell remoting, and the configuration of a persistent PowerShell backdoor through the use of WMI. We examined multiple sources of evidence, including the registry, file system, event logs, process memory, and network traffic.

Unfortunately, we never found the “white whale” – a single source of evidence, consistently available across all versions of Windows and PowerShell, that provides a complete history of all activity on an endpoint regardless of how it occurs. However, we did identify multiple artifacts containing tidbits of information that, when combined, can solve common investigative questions.

In the upcoming weeks, we’ll be releasing a whitepaper and presentation at Black Hat USA and DEF CON that focuses on the forensic analysis portion of our research. However, in this article we wanted to share a corollary of our findings – the sources of evidence that are best suited for establishing a baseline and monitoring a Windows enterprise environment.

As alluded to by Microsoft in their recent update to the Mitigating Pass-the-Hash whitepaper, organizations should orient their detection and prevention efforts around the assumption that a breach has occurred. More specifically, that means assuming that an attacker has successfully compromised credentials that provide local administrator-equivalent access to targeted system(s) (if not domain administrator outright). The worst-case scenario is unfortunately the reality for the majority of Windows environments that we encounter during investigations. Any security control put in place to limit the use of PowerShell – be it the execution policy, disabled remoting, or constrained endpoints, may be bypassed altogether.

Instead of depending on these settings to prevent malicious usage of PowerShell, we recommend using them to establish a baseline of normal activity in an environment. Deviations from this baseline may serve as an indication of attacker activity. We recommend that organizations formulate a PowerShell monitoring strategy by first assessing and enumerating the following:

  • Which servers/server groups are administered via PowerShell remoting? By local PowerShell script execution? What about workstations/end-user systems?
  • Which domain accounts use PowerShell remoting? What are the source hostnames from which these users would administer systems?
  • What are the names and common directories used for legitimate PowerShell scripts within the environment? Are legitimate scripts used by the organization digitally signed?
  • Are any systems configured to automatically load and execute PowerShell scripts for maintenance or administration purposes?

Once complete, administrators can rely on centralized Windows event log forwarding and collection (for at-scale monitoring) or local event log analysis (for targeted forensics and investigations) to identify signs of anomalous PowerShell usage. This effort will require filtering and tuning – that’s where having a baseline, or even monitoring a subset of known-good systems with common configuration for a period of time, can help.

In the interest of providing recommendations applicable to all versions of PowerShell, inclusive of 2.0, we recommend evaluating the following log sources and events:

  • Windows PowerShell event log entries indicating the start and stop of PowerShell activity:

    • Event ID 400 (“Engine state is changed from None to Available”), upon the start of any local or remote PowerShell activity.
    • Event ID 600 referencing “WSMan” (e.g. “Provider WSMan Is Started”), indicating the onset of PowerShell remoting activity on both source and destination systems.
    • Event ID 403 (“Engine state is changed from Available to Stopped”), upon the end of the PowerShell activity.
  • System event log entries indicating a configuration change to the Windows Remote Management service:

    • Event ID 7040 “The start type of the Windows Remote Management (WS-Management) service was changed from [disabled / demand start] to auto start.” – recorded when PowerShell remoting is enabled.
    • Event ID 10148 (“The WinRM service is listening for WS-Management requests”) – recorded upon reboot on systems where remoting has been enabled.
  • WinRM Operational event log entries indicating authentication prior to PowerShell remoting on an accessed system:

    • Event ID 169 (“User [DOMAIN\Account] authenticated successfully using [authentication_protocol]”)
  • Security event log entries indicating the execution of the PowerShell console or interpreter:

    • Event ID 4688 (“A new process has been created”) – includes account name, domain, and executable name in the event message.
  • AppLocker event log entries recording the local execution of PowerShell scripts. We recommend enabling AppLocker in audit mode across an environment for this specific purpose. Upon script execution in audit mode, the AppLocker MSI and Script Event Log may record:

    • Event ID 8006 (“[script_path] was allowed to run but would have been prevented from running if the AppLocker policy were enforced”)
    • Event ID 8005 (“[script_path] was allowed to run”).

Both of these events will include the user account that attempted to execute a script.

We fully expect that threat actors will continue to employ more sophisticated PowerShell techniques and improve their counter-forensic strategies over time. It is our hope that our work will increase awareness of these attacks, motivate organizations to enhance their detection and monitoring capabilities, and drive additional research. We look forward to sharing further details in our forthcoming whitepaper and presentations at Black Hat USA and DEF CON.

Authors are Ryan Kazanciyan and Matt Hastings.

Ryan Kazanciyan is a Technical Director with Mandiant and has eleven years of experience in incident response, forensic analysis, and penetration testing. Since joining Mandiant in 2009, he has led investigation and remediation efforts for dozens of Fortune 500 organizations, focusing on targeted attacks, industrial espionage, and financial crime.

Matt Hastings is a Consultant with Mandiant, a division of FireEye, Inc. Based in the Washington D.C area, Matt focuses on enterprise-wide incident response, high-tech crime investigations, penetration testing, strategic corporate security development, and security control assessments; working with the Federal government, defense industrial base, financial industry, Fortune 500 companies, and global organizations.

Share on:

Powershell Logo

Для просмотра логов Windows можно использовать команды Get-WinEvent и Get-EventLog

Get-EventLog получает список журналов или событий в заданном журнале на локальном или удалённом компьютере. Указывая нужные параметры для Get-EventLog, можно с лёгкостью искать искомые события по значениям их свойств. Get-EventLog возвращает события, соответствующие всем указанным значениям свойств. Командлет Get-EventLog работает только со стандартными классическими журналами событий Windows. Если нужно искать по остальным событиям из журналов Windows, используйте командлет Get-WinEvent.

Представим, что вам нужна основная информация о журналах событий на вашем компьютере. В этом случае убедитесь, что вы включили параметр list при вызове Get-EventLog:

Get-EventLog -list

Если вам нужна только информация о конкретном журнале событий, используйте командлет Where-Object, чтобы ограничить извлечение данных конкретным журналом событий:

Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Application"}

Эта команда извлекает все события в журнале событий системы:

Get-EventLog system

После выполнения команды выше на экран будет выведено слишком много данных. Используйте параметр -Newest и верните только нужное количество последних событий, записанных в журнале. Например, эта команда извлекает последние 10 событий, записанные в журнал событий системы:

Get-EventLog System -newest 10

Вот данные, которые вы получите:

Чтобы получить более подробную информацию, просто добавьте командлет Format-List:

Get-EventLog System -newest 10 | Format-List

Полученная информация будет уже такой:

Вы также можете передавать данные через командлет Where-Object для возврата подмножества событий. Например, эта команда извлекает только те события в журнале событий Windows PowerShell, у которых значение EventID равно 403:

Get-EventLog "Windows PowerShell" | Where-Object {$_.EventID -eq 403}

Вот небольшая команда, которая извлекает все события в журнале событий Windows PowerShell, а затем использует командлет Group-Object для группировки этих событий с помощью EventID. Другими словами, команда подсчитывает общее количество событий для каждого идентификатора (например, произошло два события с EventID 300, произошло шесть событий с событием EventID 400 и т. Д.). Затем эти данные передаются через командлет Sort-Object для предоставления результатов, отсортированных по EventID. Вот команда:

Get-EventLog "Windows PowerShell" | Group-Object eventid | Sort-Object Name

Примеры использования Get-Eventlog:

Поиск событий по ID после 3 июля:

Get-EventLog -ComputerName compname -After 03/07/2017 -LogName System | Where-Object {$_.EventID -eq "6005"}

Поиск в логах нескольких серверов:

$servers = "compname1", "compname2", "compname3"
ForEach ($Server in $servers) {$Server; Get-EventLog -LogName System -Computername $Server |  Where-Object {$_.EventID -eq "6005"}}

Возвращает все события журнала Windows PowerShell, в сообщениях которых содержится слово «failed»:

Get-Eventlog -logname "Windows PowerShell" -message "*failed*"

Поиск событий, статус которых «Ошибка»:

Get-Eventlog -logname System -EntryType Error

Командлет Get-WinEvent берёт данные из журналов событий, а именно — стандартные журналы событий, события приложений и системы. Если вызвать команду Get-WinEvent без параметров, то будут показаны все события из журналов событий компьютера. Для прерывания выполнения команды нажмите сочетание клавиш CTRL+C. Стоит отметить то, что Get-WinEvent работает только в Windows Vista, Windows Server 2008 R2 и старше. Также потребуется установленная платформа Microsoft .NET Framework 3.5 или новее.

Примеры использования Get-Winevent:

Поиск в логе System по ID 6005:

Get-WinEvent -ComputerName compname -LogName system | where {$_.id -eq "6005"}

Поиск событий за последние 40 дней:

$yesterday = (get-date) - (new-timespan -day 40)
Get-WinEvent -FilterHashTable @{LogName='system';StartTime=$yesterday; id='6005'}

Поиск событий за последние 5 дней для Outlook:

$starttime = (get-date).adddays(-5)	
Get-WinEvent -ComputerName compname -FilterHashtable @{logname="application"; ProviderName="outlook"; StartTime= $starttime}

Поиск в логах нескольких серверов:

$servers = "compname1", "compname2", "compname3"
ForEach ($Server in $Servers) {$Server; Get-WinEvent -LogName System -MaxEvents "2" -Computername $Server}


Go to Windows10


r/Windows10

Welcome to the largest community for Microsoft Windows 10, the world’s most popular computer operating system!

This is not a tech support subreddit, use r/WindowsHelp or r/TechSupport to get help with your PC




Members





Online



Powershell event ID 403 in the Event Viewer?

So I’ve looked at the Event Viewer for Powershell and it seems that whenever I start my PC the Event Viewer shows an event with the ID 403. Is this normal? It says » Engine state is changed from Available to Stopped.»

Archived post. New comments cannot be posted and votes cannot be cast.

Powershell Logo

Для просмотра логов Windows можно использовать команды Get-WinEvent и Get-EventLog

Get-EventLog получает список журналов или событий в заданном журнале на локальном или удалённом компьютере. Указывая нужные параметры для Get-EventLog, можно с лёгкостью искать искомые события по значениям их свойств. Get-EventLog возвращает события, соответствующие всем указанным значениям свойств. Командлет Get-EventLog работает только со стандартными классическими журналами событий Windows. Если нужно искать по остальным событиям из журналов Windows, используйте командлет Get-WinEvent.

Представим, что вам нужна основная информация о журналах событий на вашем компьютере. В этом случае убедитесь, что вы включили параметр list при вызове Get-EventLog:

Get-EventLog -list

Если вам нужна только информация о конкретном журнале событий, используйте командлет Where-Object, чтобы ограничить извлечение данных конкретным журналом событий:

Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Application"}

Эта команда извлекает все события в журнале событий системы:

Get-EventLog system

После выполнения команды выше на экран будет выведено слишком много данных. Используйте параметр -Newest и верните только нужное количество последних событий, записанных в журнале. Например, эта команда извлекает последние 10 событий, записанные в журнал событий системы:

Get-EventLog System -newest 10

Вот данные, которые вы получите:

Чтобы получить более подробную информацию, просто добавьте командлет Format-List:

Get-EventLog System -newest 10 | Format-List

Полученная информация будет уже такой:

Вы также можете передавать данные через командлет Where-Object для возврата подмножества событий. Например, эта команда извлекает только те события в журнале событий Windows PowerShell, у которых значение EventID равно 403:

Get-EventLog "Windows PowerShell" | Where-Object {$_.EventID -eq 403}

Вот небольшая команда, которая извлекает все события в журнале событий Windows PowerShell, а затем использует командлет Group-Object для группировки этих событий с помощью EventID. Другими словами, команда подсчитывает общее количество событий для каждого идентификатора (например, произошло два события с EventID 300, произошло шесть событий с событием EventID 400 и т. Д.). Затем эти данные передаются через командлет Sort-Object для предоставления результатов, отсортированных по EventID. Вот команда:

Get-EventLog "Windows PowerShell" | Group-Object eventid | Sort-Object Name

Примеры использования Get-Eventlog:

Поиск событий по ID после 3 июля:

Get-EventLog -ComputerName compname -After 03/07/2017 -LogName System | Where-Object {$_.EventID -eq "6005"}

Поиск в логах нескольких серверов:

$servers = "compname1", "compname2", "compname3"
ForEach ($Server in $servers) {$Server; Get-EventLog -LogName System -Computername $Server |  Where-Object {$_.EventID -eq "6005"}}

Возвращает все события журнала Windows PowerShell, в сообщениях которых содержится слово «failed»:

Get-Eventlog -logname "Windows PowerShell" -message "*failed*"

Поиск событий, статус которых «Ошибка»:

Get-Eventlog -logname System -EntryType Error

Командлет Get-WinEvent берёт данные из журналов событий, а именно — стандартные журналы событий, события приложений и системы. Если вызвать команду Get-WinEvent без параметров, то будут показаны все события из журналов событий компьютера. Для прерывания выполнения команды нажмите сочетание клавиш CTRL+C. Стоит отметить то, что Get-WinEvent работает только в Windows Vista, Windows Server 2008 R2 и старше. Также потребуется установленная платформа Microsoft .NET Framework 3.5 или новее.

Примеры использования Get-Winevent:

Поиск в логе System по ID 6005:

Get-WinEvent -ComputerName compname -LogName system | where {$_.id -eq "6005"}

Поиск событий за последние 40 дней:

$yesterday = (get-date) - (new-timespan -day 40)
Get-WinEvent -FilterHashTable @{LogName='system';StartTime=$yesterday; id='6005'}

Поиск событий за последние 5 дней для Outlook:

$starttime = (get-date).adddays(-5)	
Get-WinEvent -ComputerName compname -FilterHashtable @{logname="application"; ProviderName="outlook"; StartTime= $starttime}

Поиск в логах нескольких серверов:

$servers = "compname1", "compname2", "compname3"
ForEach ($Server in $Servers) {$Server; Get-WinEvent -LogName System -MaxEvents "2" -Computername $Server}

  • Windows powershell как отключить автозапуск
  • Windows pin window on top
  • Windows postgresql восстановить базу из бэкапа
  • Windows player portable скачать бесплатно для windows 10
  • Windows powershell как перейти в папку