How to audit NTLM?

I’ve seen the following blog post last week about Stop using LAN Manager and NTLMv1!

The first step proposed that sounds reasonable and wise is to audit event ID 4624.
Here’s one way to do it:

$c =  Get-Credential 
$xml = @'
<QueryList>
 <Query Id="0" Path="security">
  <Select Path="security">
   *[System[(EventID=4624)]]
    and
    (
     *[EventData[Data[@Name='AuthenticationPackageName']!='Kerberos']]
     and
     *[EventData[Data[@Name='LmPackageName']!='NTLM V2']]
   )
  </Select>
 </Query>
</QueryList>
'@
(Get-ADDomainController  -Filter *).HostName | 
Where { $_ -notin @('dc1.fqdn','dc3.fqdn') } | 
ForEach-Object {
 Get-WinEvent -ComputerName $_ -FilterXml $xml  -ErrorAction SilentlyContinue -Credential $c | # -MaxEvents 1
 ForEach-Object {
  $h = @{}
  ([xml]$_.Toxml()).Event.EventData.Data | 
  ForEach-Object {
   $h.Add($_.'Name',$_.'#text')            
  }
  [PSCustomObject]$h
 }
} | Out-GridView

The above example shows how to audit 4624 events on domain controllers but you can also audit 4624 events on any computer.

What else could be done to audit NTLM?
You can also enable specific NTLM auditing on every computer using group policies.
By default, it’s empty and off.

But once you’ve activated these 3 settings:

You can also activate these settings using the following registry modifications:


# Audit NTLM Authentication in this domain: Enable all
$HT = @{ Path = 'HKLM:\SYSTEM\CurrentControlSet\services\Netlogon\Parameters' }
Set-ItemProperty @HT -Name AuditNTLMInDomain -Value 7

# Audit incoming NTLM traffic: Enable auditing for all accounts
$HT = @{ Path = 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0' }
Set-ItemProperty @HT -Name AuditReceivingNTLMTraffic -Value 2

# Restrict NTLM: Outgoing NTLM traffic to remote servers: Audit All
$HT = @{ Path = 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0' }
Set-ItemProperty @HT -Name RestrictSendingNTLMTraffic -Value 1

To list what events will be logged you can do:

(Get-WinEvent -ListProvider Microsoft-Windows-NTLM).Events | 
Select Id,Description | 
Out-GridView

When auditing is enabled, we should look at 8001,8002 and 8003 events.
Here’s how to have a quick overview of both 8001 and 8002 events combined:

# NTLM client blocked audit: 
# Audit outgoing NTLM authentication traffic that would be blocked.
Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-NTLM/Operational' ; Id = 8001,8002 } |
ForEach-Object {
 $e = $_
 switch ($e.Id) {
  8001 {
   $Direction = 'Out'
   $TargetName = $e.Properties[0].Value ;
   $ProcessID = $e.Properties[3].Value 
   $ProcessName = $e.Properties[4].Value ;
   $Identity =  "$($e.Properties[2].Value)\$($e.Properties[1].Value)"
   break
  }
  8002 {
   $Direction = 'In'
   $TargetName = $env:COMPUTERNAME
   $ProcessID = $e.Properties[0].Value 
   $ProcessName = $e.Properties[1].Value ;
   $Identity =  "$($e.Properties[4].Value)\$($e.Properties[3].Value)"
  }
  default {}
 }
 [PSCustomObject]@{ 
  TargetName = $TargetName
  Direction = $Direction
  ProcessId = $ProcessID
  ProcessName  = $ProcessName
  Identity = $Identity
 }
} | Out-GridView
Advertisements

Remoting error 0x80090311

Last week, I had to enable someone in a domain to restart computers in a another domain.
I’ve first created a restricted endpoint on the Domain Controller itself.
I could enter the endpoint and use the only cmdlet exposed (Restart-Computer) with its limited parameters and values.
But, when I tried to use the endpoint from the computer in the other domain using valid credentials I had the following error:

WARNING: Failed to create and import session because Connecting to remote server server.fqdn failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no logon servers available to service the logon request.
Possible causes are:

How can I have a no logon servers available for authentication with the DC itself?
To make it work, I only changed the way I entered credentials.
I initially typed

-Credential (Get-Credential NetBiosDomainName\UserName)

and replaced it with

-Credential (Get-Credential FullyQualifiedDomainName\UserName)

Fine but afterward I encountered the issue I reported a few weeks ago on this blog post D’oh!
Running the Get-Command command in a remote session reported the following error: A parameter cannot be found that matches parameter name ‘PowerShellVersion’

No problem, it’s easier to move the endpoint to a server that runs PowerShell 4.0 than to remove PowerShell 5.1 from client computers.

Again with this other server, I had the same error 0x80090311: no logon servers available for Kerberos authentication 😦
This time, I had to modify the target computer name where the endpoint is located and write it using the correct case that matches the way SPN (Service Principal Name) are identified in Active Directory.
The Test-WSMan cmdlet behaved the same way:

Test-WSMan -ComputerName TargetserverFqDNincorretcase -Authentication Kerberos -Credential (Get-Credential FullyQualifiedDomainName\UserName)

and replaced it with

Test-WSMan -ComputerName TargetServerFQDNCorretCase -Authentication Kerberos -Credential (Get-Credential FullyQualifiedDomainName\UserName)

Now that the authentication worked, I hit another unexpected road block.
Using domain admin credentials I could do on the DC:

 Enter-PSSession -ComputerName localhost -ConfigurationName 'MySecureEndPoint'

But not on the member server. I got the following error: Enter-PSSession : AuthorizationManager check failed.

Well, I only found one configuration item that was inconsistent with the way my endpoint is configured that could explain the fact I get the equivalent of an “access denied”.
I’m using a RunAs account who is able to restart remote computers and both the DC and the member server have this policy set:

After removing the whole GPO that configured WinRM, I was finally able to deliver the reboot button:


Achievement unlocked πŸ˜‰

Follow-up on Microsoft Advisory ADV170012

If you are lucky and have System Center Configuration Manager, aka ConfigMgr, in you environment, you can get the inventory of the TPM embedded in you workstations or laptops.

You need to enable the Win32_TPM WMI class in the Hardware Inventory settings of your clients.

If you’ve only laptops, you can filter the query with the chassis types.
Then the problem is that the Manufacturer Id is returned as int32 and it doesn’t tell you what’s the manufacturer name and when the TPM manufacturer actually is Infineon whether its vulnerable or not.

Luckily, there’s a way to get the Manufacturer name from the int32 that is described on the the Win32_TPM WMI class on msdn.

Using the example provided, we can do

('{0:X0}' -f 1414548736) -split "(?<=\G.{2})",4 | 
ForEach-Object { 
 [char][int]"0x$($_)"
}

If I combine the ConfigMgr query, test if the TPM is vulnerable and get its manufacturer name from its id, I’ve the following code:

And if you use the 2nd example provided in the help, you can quickly have relevant results (IFX is Infineon)

If you cannot get results and have a WMI quota violation instead, see this post

Happy TPM madness scoping using #ConfigMgr and #PowerShell 😎

About Microsoft Advisory ADV170012

After this year Intel AMT fiasco, we’ve got not a new TPM madness. I ❀ IT

If you don’t know what it’s about, please take the time to read first the Microsoft Advisory ADV170012

Now, let’s quickly jump into the only question we care about: How do I find out whether I’m affected or not?

The PowerShell script provided on this page is supposed to help IT achieve this task.


Unfortunately, it doesn’t scale very well and Microsoft doesn’t give you too much details and just tells us to use PSRemoting to scale and query multiple computers.

The script has other major issues like:

  • it doesn’t send an object through the pipeline and just uses Write-Host to paint/color my console
  • it doesn’t handle gracefully the fact that you must be running the script with elevated user rights (Run as Administrator).
    (please note that there’s a warning about administrative privileges in bold in the forewords)
  • it uses aliases which is not a best practice
  • it doesn’t respect the Verb-Noun format for function names
  • worse, it uses Get-TPM that is cmdlet that was introduced as of Windows 8 and that isn’t available on Windows 7

Don’t get me wrong, the script is good enough for my home computer and the code exposes very well the core logic to determine if my device is affected.
I especially love the way the return statement is used in the switch block.
Anyway, I rewrote the script to ease the scoping of this TPM madness πŸ˜€

Let’s see how to use it:

# Example 1:
$c = Get-Credential
$targets = @(
'PCHPModel1',
'PCHPModel2',
'PCFujitsuModel1',
'PCFujitsuModel2',
'PCLenovoModel1',
'PCLenovoModel2'
)
Invoke-Command -ComputerName $targets -ScriptBlock ${Function:\Test-InfineonTPMVulnerability} -ErrorAction SilentlyContinue -Credential $c |
Select -Property ComputerName,TPMVersion,Vulnerable,Unknown,ClearRequired,Reason |
Format-Table -AutoSize

# Example 2:
Invoke-Command -ComputerName $targets -ScriptBlock ${Function:\Test-InfineonTPMVulnerability} -ErrorAction SilentlyContinue -AsJob -Credential $c |
Wait-Job -Any | Receive-Job | Out-GridView

Bonus 1:
In Windows 7, you cannot use the new Suspend-Bitlocker cmdlet introduced as of Windows 8.
You can use manage-bde.exe

Manage-bde.exe –protectors –disable c:

or you can use WMI

$HT = @{
 Namespace = 'root/cimv2/Security/MicrosoftVolumeEncryption'
 Class = 'Win32_EncryptableVolume'
}
(Get-WmiObject @HT -Filter 'DriveLetter="C:"').DisableKeyProtectors()

Bonus 2: On Windows 10, if you want to use the detection option 1 and query events from the Event Source TPM-WMI, the fastest way to achieve this is by using an XML query that only targets the microsoft-windows-tpm-wmi provider like this:


$xml = @'
<QueryList><Query Id="0" Path="system"><Select Path="system">*[System/Provider[@Name='microsoft-windows-tpm-wmi']]</Select></Query></QueryList>
'@
Get-Winevent -FilterXml $xml -ErrorAction SilentlyContinue

Happy TPM madness scoping 😎

Service Control Manager ACL module


When I saw this trick from John Lambert being retweeted after the Petya malware campaign (remember, the one after the Wannacry campaign that exploited SMBv1 protocol and vulnerability called EternalBlue), it was clear it can be used to stop other ways used by Petya to propagate over the wire. Of course, you could block wmic.exe and psexec.exe if you’ve Applocker and an Enterprise version of Windows. But the above trick blocks the remote use of psexec and is a hardening measure with a broader scope. I thought, it would be nice to have a PowerShell module that would help playing with this defensive configuration of the Service Controller Manager.

I wanted to use the same approach I used for the NetCease module, where I’d just set the hardened configuration in the registry.
It appeared to be a bad idea because the registry value doesn’t exist by default

It’s also a very bad idea because you can have a different configuration based on the roles and features installed on your computer.

This is what you’d typically find on a Windows 7 computer

And this is what you’d find on Windows 2012 R2 with Hyper-V

These limits explain how and why the Set-SCManagerPermission function in the Service Control Manager ACL module (SCManager) adds a Deny to the network service (NT AUTHORITY\NETWORK, S-1-5-2).

I’ve also chosen to rely on sc.exe and the functions are most of the time of wrapper around sc.exe mainly because sc.exe is required when the registry key and value don’t exist and using sc.exe apply changes immediately without a reboot.

You can find the SCManager module in this Github repository

I’ve also published a digitally signed version on the PowerShell Gallery.

Set-SCManagerPermission -Verbose -Confirm:$false
Get-SCManagerPermission |
Select Transl*,Secu*,AccessMask,AceType | 
ft -AutoSize

If sc.exe is used to access any service remotely, it will end with an Access Denied error.

This module and the hardened configuration it sets will for sure block the remote use of psexec.exe or sc.exe.

But, it could also break some Microsoft or third party products or services.

It has the capability to undo the change made using the Restore-SCManagerPermission function without a reboot.

Restore-SCManagerPermission -Verbose -Confirm:$false

Please use it first in a testing environment and report any broken service/product you may encounter.

Get the status of WSUS clients installing the September Cumulative Update

A few days ago, a PM.org list member asked the following question:

I’m trying to find out what the status is on clients installing the September Cumulative Update.

He also reported that he was using WID (Windows Internal Database) and not SQL. He was also struggling with the Microsoft Report Viewer and Microsoft System CLR Types for SQL Server.

I replied that he can achieve this using only #PowerShell and the WSUS API πŸ˜€ but my first try was:

$updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
$updateScope.TextIncludes= '4038777'
(Get-WsusServer).GetUpdateApprovals($updateScope) | 
ForEach-Object {
 $tg = (Get-WsusServer).GetComputerTargetGroup($($_.ComputerTargetGroupId))
 Write-Verbose -Message "Dealing with approval type $($_.Action) on to target group '$($tg.Name)'" -Verbose
 $tg.GetComputerTargets($true) | 
 ForEach-Object {
  $computer = $_
   $State = $computer.GetUpdateInstallationSummary($updateScope)
   [PSCustomObject]@{
    ComputerName = $_.FullDomainName ;
    Unknown = $( if($State.UnknownCount) { $true } else { $false} );
    NotApplicable = $( if($State.NotApplicableCount) { $true } else { $false } );
    NotInstalled = $( if($State.NotInstalledCount) { $true } else { $false } );
    Downloaded = $( if($State.DownloadedCount) { $true } else { $false } );
    Installed = $( if($State.InstalledCount) { $true } else { $false } );
    InstalledPendingReboot = $( if($State.InstalledPendingRebootCount) { $true } else { $false } );
    Failed = $( if($State.FailedCount) { $true } else { $false } );
   }
 }
} | ogv

Well, the above code did the job but performed very poorly. It took more than a minute to display the results for a hundred client computers.

I took the update scope approach with a custom text filter and I’ve been inspired by my previous blog post about WSUS reporting.

I wasn’t satisfied and I believed I took the wrong approach and that there should be one or more efficient ways to get the results.
So, the next morning, I gave it another try and found another way to skin the cat:

$kb = '4038777' | % { (Get-WsusServer).SearchUpdates($_) } | ? Title -match 'Windows 7 for x64-based ' |  ? { $_.IsLatestRevision }
(Get-WsusServer).GetComputerTargetGroups() | 
ForEach-Object {
 $kb.GetUpdateInstallationInfoPerComputerTarget($_)  | 
 ForEach-Object {
  [PSCustomObject]@{
   Computer = (Get-WsusServer).GetComputerTarget($_.ComputerTargetId).FullDomainName
   State = $_.UpdateInstallationState
  }
 }
} | ogv

The above way performs much faster (max 8 seconds for the same 100 computers) and has less code 😎

PSGallery and catalog files

I’ve been using catalog files associated with modules published on the PowerShellGallery the wrong way and got a warning from the PowerShell gallery administrator because my catalog files were breaking the Install-Module cmdlet experience.

As of PowerShell 5.1, you can create catalog files with the new New-FileCatalog cmdlet. Let’s quickly see what is a catalog file?

A digitally-signed catalog file (.cat) can be used as a digital signature for an arbitrary collection of files. A catalog file contains a collection of cryptographic hashes, or thumbprints. Each thumbprint corresponds to a file that is included in the collection.

(Source) May I insist on “can be used” in the above definition πŸ™„

That’s what I initially did. I was using catalog files as containers for a collection of file hashes. I didn’t use the catalog file as a digital signature and didn’t sign digitally catalog files. Catalog files allowed me to replace CSV files that I stored in my ADK repository and have a much better solution to check the integrity of each ADK files downloaded using the Test-FileCatalog cmdlet. See the following commit. The core functionality of catalog files just served very well my scenario where I just wanted to check that files downloaded match their hash.
Just a quick digression about performance. In the above scenario, using Get-AuthenticodeSignature (yes, all ADK files are digitally signed πŸ˜€ ) is the slowest (took 1 minute 28 seconds) 😦 , using Test-FileCatalog took 46 seconds πŸ™‚ and my CSV file with the Get-FileHash approach took only 28 seconds 😎 .

The code signing requirements for modules on the PowerShell gallery however are much higher than what I did with the ADK files. These requirements can be found in the PowerShellGallery Publishing Guidelines and Best Practices
modulo the fact that Save-Module doesn’t validate the catalog file (issue introduced on GH)

I’ve acquired a code signing certificate and here are the steps I use to sign a module before publishing it to the gallery.

  • Commit last changes to the module in the master branch
  • git.exe push -u origin master
    

    Copy the local github repo for the module to ~/Documents\WindowsPowerShell\Modules\$MyModule without folders like .git

    robocopy $GHRepoSource ~/Documents\WindowsPowerShell\Modules\$MyModule /R:0 /Z /S /XD .git /XD .vscode /XF README.md *.cat /NP
    
  • Use the latest version of the PSScriptAnalyzer to check if my module is compliant with coding best practices
  • # Run PSScriptAnalyzer
    Invoke-ScriptAnalyzer -Path ~/Documents\WindowsPowerShell\Modules\$MyModule -Recurse -Verbose
    
  • Sign the module and its manifest
  • # Sign the module
    $cert = Get-ChildItem Cert:\CurrentUser\My\ -CodeSigningCert | 
    Where { $_.HasPrivateKey -and ( $_.NotAfter -gt (Get-Date)) }
    
    Get-ChildItem ~/Documents\WindowsPowerShell\Modules\$MyModule -Include *.psd1,*.psm1 -Recurse |
    Set-AuthenticodeSignature -Certificate $cert -TimestampServer http://timestamp.digicert.com -Verbose -HashAlgorithm SHA256
    # at this stage only .psd1 and psm1 are signed
    Get-AuthenticodeSignature ~/Documents\WindowsPowerShell\Modules\$MyModule\*
    
  • Create the catalog file
  • # Create the catalog file
    New-FileCatalog -Path  ~/Documents\WindowsPowerShell\Modules\$MyModule -CatalogFilePath ~/Documents\WindowsPowerShell\Modules\$MyModule\MyModule.cat -CatalogVersion 2.0 -Verbose
    
  • Sign the catalog file
  • # Sign the catalog file
    Get-ChildItem ~/Documents\WindowsPowerShell\Modules\$MyModule\MyModule.cat -EA 0 |
    Set-AuthenticodeSignature -Certificate $cert -TimestampServer http://timestamp.digicert.com -Verbose -HashAlgorithm SHA256
    
  • Test the catalog file
  • # Test the catalog file
    Test-FileCatalog -Path ~/Documents\WindowsPowerShell\Modules\$MyModule -CatalogFilePath ~/Documents\WindowsPowerShell\Modules\$MyModule\MyModule.cat -Detailed 
    Get-AuthenticodeSignature ~/Documents\WindowsPowerShell\Modules\$MyModule\*
    

At this point everything is set and I can use the Publish-Module cmdlet.

Conclusion: If you want to use catalog files on PowerShellGallery, remember that you’ve to sign them digitally along with your regular module files.