Clear eventlog

I’ve been testing the new Sysmon tool from Sysinternals written by Mark Russinovich and Thomas Garnier I’ve already mentioned in this post.

It has been recently updated to version 1.01.
Since I updated from version 1.0 to 1.01, events written by the previous driver aren’t readable anymore using the “general view” of eventvwr.exe:

Fortunately, the xml data can still be parsed :-)

Anyway, I wanted to clear the log after I upgraded.
The built-in Clear-EventLog doesn’t help in this case :-(

The built-in Get-WinEvent cmdlet returns a System.Diagnostics.Eventing.Reader.EventLogConfiguration .Net object that hasn’t any method to clear the content of the log.

Get-WinEvent -ListLog * | 
Where LogName -match "sysmon" | Get-Member -Force

The System.Diagnostics.Eventing.Reader.EventLogSession .Net class has however a method that can clear logs:

The first method to clear the log is by just giving a logName as parameter

(New-Object System.Diagnostics.Eventing.Reader.EventLogSession).
ClearLog("Microsoft-Windows-Sysmon/Operational")

The second method to clear the log is by passing a logName and a backupath

(New-Object System.Diagnostics.Eventing.Reader.EventLogSession).
ClearLog(
 "Microsoft-Windows-Sysmon/Operational",
 "C:\windows\temp\sysmon.evtx"
)

Both methods generate a 104 event ID in the System log.

Get-WinEvent -FilterHashtable @{ LogName = 'System' ; Id = 104} -MaxEvents 2 | 
Sort TimeCreated | Foreach {
 ([xml]($_.ToXml())).Event.UserData.LogFileCleared
}


With event 104 we can see what account cleared what log and whether it’s been saved to any BackupPath.

Scan for updates from different sources and compare results

Context: I’m working with PowerShell version 2.0 on a Windows 2008 R2 server connected to Internet, managed by an internal WSUS.

Goal: I want to perform two scans to get results from WSUS and Microsoft Update to compare them.
I just want to see Important updates and not optional updates

Reminder :

  • I’ve already shown how to quickly perform a scan and hide some updates on PowerShell Magazine, here
  • I’ve also already shown on Windows 8.x how to get updates from the Windows Store, here

Foreword: To be able to get updates from Microsoft Update, your Windows Update Agent (WUA) must ‘opt-in’.
This can be achieved with the following code:

# Opt-in to MU            
$UpdateSvc = New-Object -ComObject Microsoft.Update.ServiceManager            
$UpdateSvc.AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"")            
$UpdateSvc.QueryServiceRegistration("7971f918-a847-4430-9279-4a52d1efe18d") | fl *            
$UpdateSvc.Services | Where { $_.Name -eq "Microsoft Update"}

Step 1: Modify the Get-WindowsUpdate function I presented on PowerShell Magazine by adding a FromMU parameter

Function Get-WindowsUpdate {
 
    [Cmdletbinding()]
    Param(
        [Parameter()]
        [system.Boolean]$FromMU=$false
    )
 
    Process {
        try {
            Write-Verbose "Getting Windows Update"
            $Session = New-Object -ComObject Microsoft.Update.Session           
            $Searcher = $Session.CreateUpdateSearcher() 
            
            if($fromMU) {
                $Searcher.ServiceID = '7971f918-a847-4430-9279-4a52d1efe18d'
                $Searcher.SearchScope =  1 # MachineOnly
                $Searcher.ServerSelection = 3 # Third Party                  
            }
            $Criteria = "IsInstalled=0 and DeploymentAction='Installation' or IsPresent=1 and DeploymentAction='Uninstallation' or IsInstalled=1 and DeploymentAction='Installation' and RebootRequired=1 or IsInstalled=0 and DeploymentAction='Uninstallation' and RebootRequired=1"           
            $SearchResult = $Searcher.Search($Criteria)          
            $SearchResult.Updates
        } catch {
            Write-Warning -Message "Failed to query Windows Update because $($_.Exception.Message)"
        }
    }
}

Only 3 properties of the Searcher object have been defined inside the if/else block.
These properties can also be discovered by reading the WindowsUpdate.log.

The modified function can be tested like this:

Get-WindowsUpdate | Out-GridView
Get-WindowsUpdate -FromMU:$true | Out-GridView

Problem: The MU scan mixes both Important and optional updates although the WUA is configured like this:
(do not give me recommended updates the same way I receive important updates)

Notice also that there’s no property from the previous Out-GridView window that would help distinguish between these “kinds” of updates.
I find also ambiguous the difference between “Optional” updates and “Recommended” updates.
To avoid confusion, let’s treat “optional” updates as updates that you can see in the “Optional” view of the Windows Update GUI.

Step 2: Find out what updates are optional vs. important

$UpdatesFromMU = Get-WindowsUpdate -FromMU:$true 
$Results = $UpdatesFromMU | ForEach-Object {
    $_ | Add-Member -MemberType ScriptProperty -Name isImportant -Value ({
        if (-not($this.BrowseOnly) -and $this.AutoSelectOnWebSites) {
            $true
        } else { 
            $false
        }
    }) -Force -PassThru |
    Add-member -MemberType ScriptProperty -Name isOptional -Value ({
        -not($this.isImportant)
    }) -Force -PassThru
}

As you can see, I’ve chosen to add script properties on the fly.

Let’s check if this corresponds to an interactive scan with the GUI

$Results | Where { $_.isImportant } | Measure
$Results | Where { $_.isOptional }  |  Measure



There’s one additional optional update that is included in the scan made with PowerShell.
In my case, it’s Microsoft .NET Framework 4 for Windows Server 2008 R2 x64-based Systems (KB982671)

Step 3: Get more info about updates

This step is more experimental. As the built-in description property of the update isn’t enough descriptive (it doesn’t tell you what it fixes), I’ll use the MoreInfoUrls property and extract the title from the raw html returned by an http request.
I don’t have the handy new Invoke-WebRequest cmdlet provided by PowerShell version 3.0, so I’ll use the old method.

$Results | Where { $_.isImportant } | 
ForEach-Object { 
    $update = $_
    $TitleLine = $pageTitle = $null
    try {
        $TitleLine = (new-object Net.Webclient).DownloadString([system.Uri]$($_.MoreInfoUrls )) -split '\<' | 
        Select-string -Pattern "\:pagetitle\=" -ErrorAction Stop | Select -Expand Line
        if ($TitleLine) {
            $pageTitle = @(([regex]'.*\="(?<Title>.*)"\s/\>').Matches(($TitleLine).ToString())) | 
            Select -Last 1 -Expand Groups | 
            Select -Last 1 -Expand Value
            $_ | Add-Member -MemberType NoteProperty -Name "Page Title" -Value $pageTitle -Force -PassThru -ErrorAction Stop
        }
    } catch {
        Write-Warning -Message "Failed for $($update.Title) because $($_.Exception.Message)"
        $update | Add-Member -MemberType NoteProperty -Name "Page Title" -Value $($update.Description) -Force -PassThru
    }        
} | 
Select Title,@{
    l='Category';e={$_.Categories | Where { -not($_.Parent) } | Select -Expand Name}
},'Page Title' | 
Out-GridView

Step 4: scan for Updates from WSUS and Microsoft Update and compare results

I can now export results from the scan performed against Microsoft Update by just replacing the above Out-GridView cmdlet by the following code:

Export-Csv -Path "$($home)\Documents\scan.results.$((Get-date).toString('yyyy-MM-dd-HHmm')).MU.csv"

To get results from WSUS, I do:

#
# scan from WSUS
#
$UpdatesFromWSUS = Get-WindowsUpdate
$Results = $UpdatesFromWSUS | ForEach-Object {
    $_ | Add-Member -MemberType ScriptProperty -Name isImportant -Value ({
        if (-not($this.BrowseOnly) -and $this.AutoSelectOnWebSites) {
            $true
        } else { 
            $false
        }
    }) -Force -PassThru |
    Add-member -MemberType ScriptProperty -Name isOptional -Value ({
        -not($this.isImportant)
    }) -Force -PassThru
}
$Results | Where { $_.isImportant } | Measure
$Results | Where { $_.isOptional }  |  Measure
# > no need to distinguish between the 2 kinds :-)

$Results | 
ForEach-Object { 
    $update = $_
    $TitleLine = $pageTitle = $null
    try {
        $TitleLine = (new-object Net.Webclient).DownloadString([system.Uri]$($_.MoreInfoUrls )) -split '\<' | 
        Select-string -Pattern "\:pagetitle\=" -ErrorAction Stop | Select -Expand Line
        if ($TitleLine) {
            $pageTitle = @(([regex]'.*\="(?<Title>.*)"\s/\>').Matches(($TitleLine).ToString())) | 
            Select -Last 1 -Expand Groups | 
            Select -Last 1 -Expand Value
            $_ | Add-Member -MemberType NoteProperty -Name "Page Title" -Value $pageTitle -Force -PassThru -ErrorAction Stop
        }
    } catch {
        Write-Warning -Message "Failed for $($update.Title) because $($_.Exception.Message)"
        $update | Add-Member -MemberType NoteProperty -Name "Page Title" -Value $($update.Description) -Force -PassThru
    }        
} | 
Select Title,@{
    l='Category';e={$_.Categories | Where { -not($_.Parent) } | Select -Expand Name}
},'Page Title' | 
Export-Csv -Path "$($home)\Documents\scan.results.$((Get-date).toString('yyyy-MM-dd-HHmm')).WSUS.csv"

To compare results, I do:

Compare-Object -Property Title -IncludeEqual -ReferenceObject (
    Import-CSV (
        Get-ChildItem "$($home)\Documents\scan.results.*.MU.csv" | 
        Sort LastWriteTime | Select -Last 1
    )
) -DifferenceObject (
    Import-CSV (
        Get-ChildItem "$($home)\Documents\scan.results.*.WSUS.csv" | 
        Sort LastWriteTime | Select -Last 1
    )
) 

Enjoy :-D

about WSUS reporting

Before we start, may I introduce the official Terminology for Update Status
As you can see, the status “Needed” and “Installed/Not Applicable”, don’t mean the same thing when it applies either to a single computer or a computer target group. Don’t let the GUI fool you!

This article from the WSUS team in 2008 said that:

Usually there are two kinds of reports people run: The default WSUS reports accessed from the WSUS MMC console and the reporting tools located in the API Samples and Tools:
WSUS3: http://download.microsoft.com/download/5/d/c/5dc98401-bb01-44e7-8533-3e79ae0e0f97/Update%20Services%203.0%20API%20Samples%20and%20Tools.EXE

I’ve a Windows Server 2012 R2 core edition where I don’t want to install the Report Viewer.

I’m stuck with the second option and almost forced into using the API samples and tools ;-)

What are these tools ?

Before I go through the above list, you should know that things have changed since 2008.
A common best practice and approach in PowerShell is to return objects and let you choose the format you want to export: CSV, XML,…

I’ll now focus on showing how to achieve what the API samples and tools do with PowerShell.

  • ApprovedUpdatesToXML
    # ApprovedUpdatestoXML
    # \Update Services 3.0 API Samples and Tools\ApprovedUpdatesToXML
    
    $updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
    $updateScope.ApprovedStates = (
    ([Microsoft.UpdateServices.Administration.ApprovedStates]::HasStaleUpdateApprovals.value__+
    [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved.value__)
    )
    
    # get the list of updates that are approved, or have an older revision that is approved
    $Updates = (Get-WsusServer).GetUpdates($updateScope) 
    # calling IUpdate.GetUpdateApprovals once for each update can be expensive, so instead
    # we use call IUpdateServer.GetUpdateApprovals() to get all approvals for all updates at once
    $allUpdateApprovals = (Get-WsusServer).GetUpdateApprovals($updateScope)
    # similarly, construct a table of target group
    $allTargetGroups = (Get-WsusServer).GetComputerTargetGroups()
    $Updates | ForEach-Object {
        $update = $_
        [PSCustomObject]@{
            Id = $update.Id.UpdateId.ToString() ;
            Title = $update.Title ;
            Classification = $update.UpdateClassificationTitle ;
            Approvals = $( 
            if ($update.IsApproved) {
                # This revision (the latest revision) is approved; get the approvals and write them
                $allUpdateApprovals | Where { 
                    $_.UpdateID.UpdateID -eq $update.Id.UpdateId
                } | 
                ForEach-Object {
                    $approval = $_
                    [PSCustomObject]@{
                        RevisionNumber = $update.Id.RevisionNumber ;
                        TargetGroup = ($allTargetGroups | Where { $_.ID -eq $approval.ComputerTargetGroupId }).Name ;
                        Approval = $approval.Action ;
                        Deadline = $( 
                            if ($_.Deadline -lt ([datetime]::maxvalue)) {
                                $_.Deadline    
                            } else {
                                "None"
                            }
                        ) ;
                        ApprovalDate = $approval.CreationDate ;
                    }
                }
            } elseif ($update.HasStaleUpdateApprovals) {
                # This revision has older revisions that are approved; get their approvals and write them
                $update.GetRelatedUpdates(
                    [Microsoft.UpdateServices.Administration.UpdateRelationship]::AllRevisionsOfThisUpdate
                    ) | Where isApproved | 
                    ForEach-Object {
                    $revision = $_
                    $revision.GetUpdateApprovals() |
                    ForEach-Object {
                        $approval = $_
                        [PSCustomObject]@{
                            RevisionNumber = $update.Id.RevisionNumber ;
                            TargetGroup = ($allTargetGroups | Where { $_.ID -eq $approval.ComputerTargetGroupId }).Name ;
                            Approval = $approval.Action ;
                            Deadline = $( 
                                if ($_.Deadline -lt ([datetime]::maxvalue)) {
                                    $_.Deadline    
                                } else {
                                    "None"
                                }
                            ) ;
                            ApprovalDate = $approval.CreationDate ;
                        }
                    }
                    }
            } else {
            }
        ) ;
        }
    }  | Export-Clixml -Depth 2 -Path $home\Documents\ApprovedUpdatesToXML.xml
    
  • ComputerStatusToXML
  • # ComputerStatusToXML
    # \Update Services 3.0 API Samples and Tools\ComputerStatusToXML
    
    $computerScope = New-object Microsoft.UpdateServices.Administration.ComputerTargetScope
    $computerScope.IncludeDownstreamComputerTargets = $true
    (Get-WsusServer).GetComputerTargets($computerScope) | ForEach-Object {
        $computer = $_
        [PSCustomObject]@{
            Name = $computer.FullDomainName ;
            LastReportedStatus = $computer.LastReportedStatusTime ;
            ParentServer = $(
                if ($computer.ParentServerId -ne [System.Guid]::Empty) {
                    $computer.GetParentServer().FullDomainName
                } else {
                    'localhost'
                }
            );
            UpdateStatus = $(
                $computer.GetUpdateInstallationInfoPerUpdate() | 
                Where {
                    $_.UpdateInstallationState -ne 'NotApplicable'
                } |
                ForEach-Object {
                    [PSCustomObject]@{
                        Title = $_.GetUpdate().Title ;
                        Status = $_.UpdateInstallationState ;
                    }
                }
            );
            }
    } | 
    Export-Clixml -Depth 2 -Path $home\Documents\ComputerStatusToXML.xml
    
  • ListApprovedUpdates
  • # \Update Services 3.0 API Samples and Tools\ListApprovedUpdates
    
    $updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
    $updateScope.ApprovedStates = (
    ([Microsoft.UpdateServices.Administration.ApprovedStates]::HasStaleUpdateApprovals.value__+
    [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved.value__)
    )
    
    (Get-WsusServer).GetUpdates($updateScope) | ForEach-Object {
        $update = $_ 
        if ($_.isApproved) {
            $_.GetUpdateApprovals() | ForEach-Object {
                $approval =  $_
                [PSCustomObject]@{
                    Title = $update.Title ;
                    Classification = $update.UpdateClassificationTitle ;
                    'Applies to' = $update.ProductTitles
                    'Approved on' = $approval.CreationDate
                }
                
            }
        }
    }
    
  • UpdateStatusToCSV
  • # UpdateStatusToCSV    
    # Update Services 3.0 API Samples and Tools\UpdateStatusToCSV
    $updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
    $updateScope.ApprovedStates = (
    ([Microsoft.UpdateServices.Administration.ApprovedStates]::HasStaleUpdateApprovals.value__+
    [Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved.value__)
    )
    
    (Get-WsusServer).GetUpdates($updateScope) | ForEach-Object {
        $update = $_
        $update.GetSummaryPerComputerTargetGroup() | ForEach-Object {
            if ($_.ComputerTargetGroupId.Equals([Microsoft.UpdateServices.Administration.ComputerTargetGroupId]::AllComputers)) {
                [PSCustomObject]@{
                    'Update Name' = $update.Title
                    Classification = $update.UpdateClassificationTitle
                    Installed = $_.InstalledCount
                    'Installed Pending Reboot' = $_.InstalledPendingRebootCount
                    Needed = ($_.DownloadedCount + $_.NotInstalledCount)
                    'Not Needed' = $_.NotApplicableCount
                    Failed = $_.FailedCount
                    Unknown = $_.UnknownCount
                    'Last Updated' = $(
                        switch ($_.LastUpdated) {
                            ([datetime]::MinValue) {
                                "Never" ; break
                            }
                            default {$_.ToShortDateString()}
                        })
                }
            }
        }
    } | Export-Csv -Path $home\Documents\ApprovedUpdateStatus.csv
    
  • UpdateStatustoXML
  • # UpdateStatustoXML
    # Update Services 3.0 API Samples and Tools\UpdateStatusToXML
    
    $Updates = (Get-WsusServer).GetUpdates()
    $AllComputersGroup = (Get-WsusServer).GetComputerTargetGroup(
    [Microsoft.UpdateServices.Administration.ComputerTargetGroupId]::AllComputers
    )
    
    $Updates | Where {-not($_.IsDeclined)} | ForEach-Object -Process {
        [PSCustomObject]@{
            Title = $_.Title
            ComputerStatus = ($AllComputersGroup.GetUpdateInstallationInfoPerComputerTarget($_) | ForEach-Object {
                [pscustomobject]@{
                    ComputerName = $_.GetComputerTarget().FullDomainName ;
                    InstallationStatus = $_.UpdateInstallationState.ToString() ;
                    ApprovalStatus = $_.UpdateApprovalAction.ToString()
    
                }
            })
        }
    } | Export-Clixml -Depth 2 -Path $home\Documents\ApprovedUpdateStatus.xml
    
    
  • UpdatesToXML
  • # UpdatesToXML
    # Update Services 3.0 API Samples and Tools\UpdatesToXML
    
    (Get-WsusServer).GetUpdates(
        [Microsoft.UpdateServices.Administration.ApprovedStates]::Any,
        [datetime]::MinValue,
        [datetime]::MaxValue,
        $null,
        $null
    ) | ForEach-Object -Process {
        $_ | 
        Add-Member -MemberType ScriptProperty -Name UpdateID -Value {
            $this.Id.UpdateID.toString().ToUpper()
        } -Force -PassThru |
        Add-Member -MemberType ScriptProperty -Name BundledUpdates -Value { 
                $_.GetRelatedUpdates(
                    [Microsoft.UpdateServices.Administration.UpdateRelationship]::UpdatesBundledByThisUpdate
                ) | 
                Select -Property @{l='UpdateID';e={$_.Id.UpdateID.ToString().ToUpper()}},
                Title,@{l='Classification';e={$_.UpdateClassificationTitle}}
        } -Force -PassThru | 
        Add-Member -MemberType ScriptProperty -Name BundlingUpdates -Value {
                $_.GetRelatedUpdates(
                    [Microsoft.UpdateServices.Administration.UpdateRelationship]::UpdatesThatBundleThisUpdate
                ) | 
                Select -Property @{l='UpdateID';e={$_.Id.UpdateID.ToString().ToUpper()}},
                Title,@{l='Classification';e={$_.UpdateClassificationTitle}}
        } -Force -PassThru | 
        Add-Member -MemberType ScriptProperty -Name SupersededUpdates -Value {
                $_.GetRelatedUpdates(
                    [Microsoft.UpdateServices.Administration.UpdateRelationship]::UpdatesSupersededByThisUpdate
                ) |
                Select -Property @{l='UpdateID';e={$_.Id.UpdateID.ToString().ToUpper()}},
                Title,@{l='Classification';e={$_.UpdateClassificationTitle}}
        } -Force -PassThru | 
        Add-Member -MemberType ScriptProperty -Name SupersedingUpdates -Value {
                $_.GetRelatedUpdates(
                    [Microsoft.UpdateServices.Administration.UpdateRelationship]::UpdatesThatSupersedeThisUpdate
                ) |
                Select -Property @{l='UpdateID';e={$_.Id.UpdateID.ToString().ToUpper()}},
                Title,@{l='Classification';e={$_.UpdateClassificationTitle}}
        } -Force -PassThru
        
    } | Select -Property UpdateID,Title,@{l='Classification';e={$_.UpdateClassificationTitle}},
    LegacyName,Description,@{l='SyncDate';e={$_.ArrivalDate.ToLocalTime()}},
    @{l='ReleaseDate';e={$_.CreationDate.ToLocalTime()}},MsrcSeverity,SecurityBulletins,
    @{l='KBArticles';e={$_.KnowledgeBaseArticles}},AdditionalInformationUrls,
    BundledUpdates,BundlingUpdates,SupersededUpdates,SupersedingUpdates |
    Export-Clixml -Depth 2 -Path $home\Documents\UpdatesToXML.xml
    

The above samples show that it’s possible to do some reporting under PowerShell but there are some limitations and drawbacks.

For example, UpdateStatustoXML sample is extremely slow as it will go through all updates except those that are declined.
To reduce its scope and increase performance, you should consider filtering on the left.

I was looking at WSUS reporting mainly because I wanted to determine the compliance level of the Windows 7 computers I grouped under a target group named ‘Windows 7 x64′.
How can I determine a compliance ratio?
More precisely, I wanted to know what was installed on my computer against what I approved and what may be missing again against what I previously approved.

I wanted to use the ApprovedComputerTargetGroups of the UpdateScope object to get a better filter but it’s a read-only property.

The trick that let me find my way was the updatescope used to filter both the GetUpdateApprovals and GetUpdateInstallationSummary methods.


$targetgroup = (Get-WsusServer).GetComputerTargetGroups() | Where Name -eq "Windows 7 x64"

$updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
$updateScope.UpdateApprovalActions = "Install"
$updateScope.ApprovedStates = (
([Microsoft.UpdateServices.Administration.ApprovedStates]::HasStaleUpdateApprovals.value__+
[Microsoft.UpdateServices.Administration.ApprovedStates]::LatestRevisionApproved.value__)
)
$total = (Get-WsusServer).GetUpdateApprovals($updateScope).Count
$targetgroup.GetComputerTargets($true) | Where FullDomainName -match "^MyComputerNamePattern" | 
ForEach-Object {
    $computer = $_
    $State = $computer.GetUpdateInstallationSummary($updateScope)
    [PSCustomObject]@{
        Name = $_.FullDomainName ;
        IPAddress = $_.IPAddress ;
        # 'Operating System'  = $_.OSDescription ;
        Version = $_.ClientVersion ;
        RebootPending = $(
            if($State.InstalledPendingRebootCount) {
                $true
            } else {
                $false
            }
        );
        Compliant = '{0:P}' -f (($State.InstalledCount)/($total - $State.NotApplicableCount));
        Needed = $State.FailedCount + $State.DownloadedCount + $State.UnknownCount + $_.NotInstalled
    }
}


As you can see above, I’ve got I computer that misses 15 updates. It’s expected as it’s mainboard is out-of-order…

Please note that there’s also a way to do this directly from the database.
The SQL path is available on http://blogs.technet.com/b/wsus/archive/2008/06/20/baseline-compliance-report-using-public-wsus-views.aspx

If you’re looking for the Microsoft.UpdateServices.Administration Namespace documentation it’s available on MSDN.

There are other samples available online. There’s for example: How to Determine All Approved Updates.

I’d like also to reference the great work Boe Prox already did about WSUS reporting:

As we are today the second Tuesday of August, may I wish you happy Patch Tuesday and reboot Wednesday :-D

Post-mortem #DFIR investigation of #PowerShell attacks

A nice white paper has been published by FireEye recently, entitled “Investigating PowerShell Attacks” written by Ryan Kazanciyan and Matt Hastings.
It’s actually the white paper they announced in the article they published in the two-week Security series on PowerShell Magazine last month, also entitled “Investigating PowerShell Attacks

First, I’d like to applaud the initiative and the awesome work they did :-D
It’s a good reading that summarizes what artifacts a DFIR analyst may find during a post-mortem investigation:

  • Registry
  • Prefetch
  • Network Traffic
  • Memory
  • Eventlogs
  • Persistence

If you’re not familiar with the Prefetch feature, you can read the following pages:

A side note: please bear in mind that the Prefetcher is turned off by default if the OS is running Windows 7 on a Solid State Drive (SSD).

If you’re not familiar with the “Remoting” feature of Windows PowerShell, I’d recommend reading the “Secrets of PowerShell Remoting” free ebook published by PowerShell.org and written by Don Jones, Tobias Weltner and Dave Wyatt.
While not referenced by the “Investigating PowerShell Attacks” white paper, if you want to explore how to read the data chunks in the WinRM analytic eventlog, you should read the “Diagnostics and Troubleshooting” chapter in the “Secrets of PowerShell Remoting” ebook where the authors provided and showed how to use the Construct-PSDataRemoteObject cmdlet. This cmdlet is available from the PSdiagnostics.zip file hosted on http://www.concentratedtech.com/downloads

The “Investigating PowerShell Attacks” white paper is available from

There’s one technique Ryan Kazanciyan and Matt Hastings talked about that could give additional forensics evidence:

The authors have worked with several organizations that have implemented homegrown logging solutions. One such technique entails overwriting PowerShell’s built-in Prompt function22 (again, through the addition of code in all user profiles). A custom prompt could capture any input submitted at the local PowerShell command line and save it to a file or to an event log (using the Write-EventLog cmdlet). Once again, this approach would not capture remoting activity.

That’s a great idea :-) Unfortunately, they didn’t show what the code may look like.
James O’Neill already shared some code on his blog about this technique http://jamesone111.wordpress.com/2012/01/28/adding-persistent-history-to-powershell/

More recently a PowerTip that explores other techniques was also published on this page http://powershell.com/cs/blogs/tips/archive/2014/08/08/logging-what-a-script-does.aspx It uses the Start-Transcript and the Set-PSDebug cmdlets

As we are in August, I’d like to mention that Mark Russinovich and Thomas Garnier released the Sysmon tool

System Monitor (Sysmon) is a Windows system service and device driver that, once installed on a system, remains resident across system reboots to monitor and log system activity to the Windows event log. It provides detailed information about process creations, network connections, and changes to file creation time

Source and more on http://technet.microsoft.com/en-us/sysinternals/dn798348

My fellow Windows PowerShell MVP Carlos Perez already wrote an awesome post about this new Sysmon tool that shows how useful it can be for DFIR post-mortem analysis http://www.darkoperator.com/blog/2014/8/8/sysinternals-sysmon

European PowerShell Summit

Si tu utilises Windows PowerShell – ton outil préféré – (quasi) quotidiennement et que tu comprends l’anglais, tu as une occasion unique de rencontrer d’autres personnes enthousiastes qui partagent la même passion, d’apprendre de nouvelles techniques, de développer tes connaissances, ton réseau, de rencontrer d’autres experts, des MVPs PowerShell et des membres de la team PowerShell chez Microsoft.

Comment? Simple, il te suffit de te rendre au “European PowerShell Summit” organisé par PowerShell.org qui se tient pendant 3 jours, du 29 Septembre au 1er Octobre 2014 à Amsterdam au Pays-Bas. Il y a aussi d’autres avantages, plus de détails sont disponibles sur http://powershell.org/wp/community-events/summit/

L’agenda du sommet a été publié sur cette page http://eventmgr.azurewebsites.net/event/agenda/PSEU14

Les inscriptions sont ouvertes et se font via http://eventmgr.azurewebsites.net/event/home/PSEU14

Retrospective. What an awesome month!

I’m a PowerShell MVP since the 1st of July. I’m deeply honored to receive this award and join this awesome community. I’d like to say thank you to those who nominated me, enjoy my work, read my blog and support me.

I attended the SANS FOR508 training on Advanced Computer Forensic Analysis and Incident Response in Paris in March 2014 and successfully passed the GCFA on the 16th of July.
I’m also now a Certified Forensics Analyst
I’d like to thank to my employer who paid the training and voucher.

I also wrote two articles for PowerShell Magazine this month:

Again, I’d like to thank you. My blog wouldn’t have crossed 160K visits since its creation and 10K views this month without you

May the Power of the Shell be with you ;-)

I’m currently into the following pipeline

Stop-Work | Start-Vacation | Enjoy-Holidays | Enjoy-FamilyTime

About Get-Service

The Get-Service cmdlet will retrieve

“objects that represent the services on a local computer or on a remote computer”.

Ambiguous way of formulating things, isn’t it? Let’s try to uncover the meaning behind.

Get-Service | Measure
Get-Service -Name * | Measure
Get-Service -Name * -include * | Measure

I always get a count of 169 services as you can see:

The Get-Service cmdlet output is a System.ServiceProcess.ServiceController .Net object.

Get-Service | Get-Member -Static

It has 2 static methods, GetServices and GetDevices.

What’s their definition?

[System.ServiceProcess.ServiceController]::GetServices
[System.ServiceProcess.ServiceController]::GetDevices


No way to authenticate to query a remote computer. That’s why Get-Service doesn’t support the Credential parameter.

[System.ServiceProcess.ServiceController]::GetServices() |
Measure

I got the same number of services as the Get-Service cmdlet.

[System.ServiceProcess.ServiceController]::GetDevices() | 
Measure


What the heck? What are these 237 additional services?

The GetDevices method

retrieves the device driver services on the local computer.

, i.e, KernelDriver and FileSystemDriver service types.

([System.ServiceProcess.ServiceController]::GetDevices()).ServiceType | 
Sort -Unique

The GetServices method

retrieves all the services on the local computer, except for the device driver services.

([System.ServiceProcess.ServiceController]::GetServices()).ServiceType | 
Sort -Unique

Let’s do some maths:

[System.ServiceProcess.ServiceController]::GetDevices() +
[System.ServiceProcess.ServiceController]::GetServices() | 
Measure

# Are they unique?
[System.ServiceProcess.ServiceController]::GetDevices() + 
[System.ServiceProcess.ServiceController]::GetServices() | 
Sort -Unique | Measure


In other words, the Get-Service cmdlet outputs by default only the objects that you can obtain using the GetServices method.
Really?

Let’s find the name of one kernel driver service.

[System.ServiceProcess.ServiceController]::GetDevices() |
Select -Last 1 -Property Status,Name,ServiceType,DisplayName |
Format-Table -AutoSize

If I start type the first two letters of the service name I’m looking for and rely on the tab completion, only services that you can get with the GetServices method are enumerated.

If I type:

Get-Service -Name Wud*
Get-Service -Name WudfP*
Get-Service -Name WudfPf

I get:

Based on the above results, the Get-Service cmdlet is able to retrieve kernel driver or file system driver services only if you know their exact name. Wildcard are not allowed in this case.

Why Kernel drivers and file system drivers aren’t returned by the Get-Service cmdlet by default? I can probably guess the answer.
The Get-Service is designed to pass objects through the pipeline to other cmdlets that take actions like “Start”,”Stop”,”Pause”,”Resume”.
Let’s say I do:

Get-Service -Name wu* | 
Stop-Service -PassThru -Verbose | 
Set-Service -StartupType Disabled -Verbose

Better safe than sorry. Imagine there’s a critical kernel driver returned by the above wildcard query. It would probably immediately end with a blue screen.
If you really know what you do, you have to know the exact name of kernel driver and file system driver services to be able to manipulate them with the built-in *-Service cmdlets.