Tracking WMI Activity with PSGumshoe

WMI (Windows Management Instrumentation) is the Microsoft implementation of the Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) standards from the Distributed Management Task Force (DMTF). This allows for a unified way to manage a group of systems by administrators allowing them to get information about the system, its current state and to execute actions. Because of this many attackers leverage this for enumeration, lateral movement, and persistence. Defenders and security vendors leverage it heavily also, in fact, most vulnerability scanners would not be able to do a lot of what they do on windows hosts without it.

I wrote the PSGumshoe PowerShell module initially with a group of good friends of mine to help with the job of performing threat hunting and incident response. I maintain the module as my personal tool for working in my research of finding IOCs for the tools I write in my day job for the Red Team and the Pentest Team, also when I help out in some of the incident response engagements.

I would like to share some of the new functions I added to the module for the purpose of tracking some of the WMI activities that attackers may perform once they gained a foothold on the system.

Read More

Sysmon for Linux PowerShell Module

Sysmon has been a great tool to enhance logging in Windows for many year allowing well organized teams to cover many gaps in their log and even improve their capabilities at detecting all kinds of attacks. Microsoft released a version of Sysmon for Linux to provide the same type of value to those defending Linux systems. Logs are saved in to Syslog as single line XML blobs that can be ingested and parsed by SIEM products. To aid with extracting the Sysmon specific events from syslog I wrote the SysmonLinux.Util module. The module can parse one or more Syslog files even GZip files archived by LogRotate from a Linux system and allow for the search of specific events that meet a given criteria. The module can be use also for aiding in the generation of filter rules based on the resulting objects of queries performed against the logs, greatly speeding the creation and tunning of Sysmon configuration files.

Install

The recommended method for installing the module is to install the module from the PowerShell Gallery, https://www.powershellgallery.com/packages/SysmonLinux.Util The command to install the module is

Install-Module -Name SysmonLinux.Util -Force

The module source code can also be downloaded from GitHub https://github.com/darkoperator/SysmonLinux.Util/

Exploring the Module

Once the module is installed we can take a look at the functions made available for working with tge Get-Command cmdlet in PowerShell.

PS /home/carlos> Get-Command -Module sysmonlinux.util                                                                                              
CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        ConvertTo-SysmonRule                               0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxConfigChange                        0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxEvent                               0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxFileCreate                          0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxFileDelete                          0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxNetworkConnect                      0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxProcessCreate                       0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxProcessTerminate                    0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxRawAccess                           0.0.3      SysmonLinux.Util
Function        Get-SysmonLinuxState                               0.0.3      SysmonLinux.Util

The functions available at the moment of this is written are described bellow in the table.

Function Description
ConvertTo-SysmonRule Takes resulting objects from the other module function and turns them in to Sysmon Rules
Get-SysmonLinuxConfigChange Gets Sysmon configuration change events from one or more syslog files.
Get-SysmonLinuxEvent Gets any Syslon event allowing filtering either by Image and ProcessGUID from one or more syslog files.
Get-SysmonLinuxFileCreate Gets Sysmon File Create events from one or more syslog files.
Get-SysmonLinuxFileDelete Gets Sysmon File Delete events from one or more syslog files.
Get-SysmonLinuxNetworkConnect Gets Sysmon Network Connect events from one or more syslog files.
Get-SysmonLinuxProcessCreate Gets Sysmon Process Create events from one or more syslog files.
Get-SysmonLinuxProcessTerminate Gets Sysmon Process Terminate events from one or more syslog files.
Get-SysmonLinuxRawAccess Gets Sysmon Raw Access events from one or more syslog files.
Get-SysmonLinuxState Gets Sysmon Linux State events from one or more syslog files.

The Get-Help cmdlet or its alias help can be used to look at the parameters and their details for each of the functions. It will also show which parameters allow for wildcards so as to make searching for specific events much easier.

PS /home/carlos> help Get-SysmonLinuxEvent

NAME
    Get-SysmonLinuxEvent

SYNOPSIS
    Gets one or more Sysmon for Linux event types from Syslog logs.


SYNTAX
    Get-SysmonLinuxEvent -EventType <String[]> [[-SyslogFile] <String[]>] [-Image <String[]>] [-User 
    <String[]>] [<CommonParameters>]

    Get-SysmonLinuxEvent -EventType <String[]> [[-SyslogFile] <String[]>] [-ProcessGuid <String[]>] 
    [-Image <String[]>] [-User <String[]>] [<CommonParameters>]


DESCRIPTION
    Gets one or more Sysmon for Linux event types from Syslog logs. Allows for filtering by ProcessGUID 
    and User.


PARAMETERS
    -EventType <String[]>
        Event type to pull from Syslog log file.

        Required?                    true
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false

    -SyslogFile <String[]>
        Specifies a path to one or more locations.

        Required?                    false
        Position?                    1
        Default value                @("/var/log/syslog")
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  false

    -ProcessGuid <String[]>
        ProcessGuid to search for a given event type, ParentProcessGuid will also be matched to this 
        value.

        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false

    -Image <String[]>
        Image to search for a given event type.The '*' wildcard is supported for matching.

        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  true

    -User <String[]>
        User to seach for a given event type.

        Required?                    false
        Position?                    named
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false

    <CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer, PipelineVariable, and OutVariable. For more information, see
        about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). 

INPUTS
    System.IO.FileInfo


OUTPUTS
    System.Management.Automation.PSCustomObject


NOTES


        General notes

    -------------------------- EXAMPLE 1 --------------------------

    PS />Get-SysmonLinuxEvent -EventType Any -ProcessGuid "{de9527a5-6a3f-616f-a52f-d98154560000}"

    EventId           : 1
    Version           : 5
    EventType         : ProcessCreate
    Computer          : ubuntu
    EventRecordID     : 35705
    RuleName          : -
    UtcTime           : 2021-10-20 01:00:47.600
    ProcessGuid       : {de9527a5-6a3f-616f-a52f-d98154560000}
    ProcessId         : 2356
    Image             : /usr/sbin/dumpe2fs
    FileVersion       : -
    Description       : -
    Product           : -
    Company           : -
    OriginalFileName  : -
    CommandLine       : dumpe2fs -h /dev/sda5
    CurrentDirectory  : /
    User              : root
    LogonGuid         : {de9527a5-0000-0000-0000-000000000000}
    LogonId           : 0
    TerminalSessionId : 4294967295
    IntegrityLevel    : no level
    Hashes            : -
    ParentProcessGuid : {00000000-0000-0000-0000-000000000000}
    ParentProcessId   : 874
    ParentImage       : -
    ParentCommandLine : -
    ParentUser        : -

    EventId       : 9
    Version       : 2
    EventType     : RawAccessRead
    Computer      : ubuntu
    EventRecordID : 35706
    RuleName      : -
    UtcTime       : 2021-10-20 01:00:47.619
    ProcessGuid   : {de9527a5-6a3f-616f-a52f-d98154560000}
    ProcessId     : 2356
    Image         : /usr/sbin/dumpe2fs
    Device        : /dev/sda5
    User          : root

    EventId       : 5
    Version       : 3
    EventType     : ProcessTerminate
    Computer      : ubuntu
    EventRecordID : 35707
    RuleName      : -
    UtcTime       : 2021-10-20 01:00:47.620
    ProcessGuid   : {de9527a5-6a3f-616f-a52f-d98154560000}
    ProcessId     : 2356
    Image         : /usr/sbin/dumpe2fs
    User          : root

    Find all events that match the specified ProcessGuid.





RELATED LINKS

Leveraging the Functions

The functions are divided in 2 groups, all of the functions minus ConvertTo-SysmonRule are meant for getting from Syslog log files the events for their type and allow to target certain events by filtering based on their properties. Each function returns the log entry as an object, this allows for the use of regular built in PowerShell cmdlets to further filter and process the resulting log entry objects. Bellow we use the Select-Object cmdlet to select only some of the properties of the resulting objects and from the results only have unique entries.

PS /home/carlos> Get-SysmonLinuxNetworkConnect -Image /usr/lib/systemd/systemd-resolved | select destinationip,image -unique                       

DestinationIp Image
------------- -----
10.101.101.2  /usr/lib/systemd/systemd-resolved
127.0.0.1     /usr/lib/systemd/systemd-resolved
127.0.0.53    /usr/lib/systemd/systemd-resolved

By default the functions will open the /var/log/syslog file, a list of files can be passed to the -SyslogFile parameter or passed to the filtering functions via the pipeline. On most distributions of linux the lograted daemon runs on a schedule and archives the syslog log file in to a Gzip compressed file. The SysmonLinux.Util module can handle this files by decompressing in to the temp folder the files and processing each file if they have the .gz extension.

PS /home/carlos> ls /var/log/syslog* | Get-SysmonLinuxRawAccess | select image,user -Unique | Format-List       
Image : /usr/sbin/grub-probe
User  : root

Image : /usr/sbin/blkid
User  : root

Image : /usr/lib/systemd/systemd-logind
User  : root

Image : /usr/sbin/dumpe2fs
User  : root

Image : /usr/lib/systemd/system-generators/systemd-gpt-auto-generator
User  : root

Image : /usr/bin/mount
User  : root

Image : /usr/lib/systemd/systemd-udevd
User  : root

Image : /usr/lib/udev/scsi_id
User  : root

Image : /usr/lib/udev/cdrom_id
User  : root

Image : /usr/lib/udev/ata_id
User  : root

Image : /usr/lib/udisks2/udisksd
User  : root

The ConvertTo-SysmonRule function is the only function whose purpose is not the extraction of log entries from syslog files but for turning the resulting objects in to rules that can then be used for exclude or include rule groups to further tune configuration files.

PS /home/carlos> ls /var/log/syslog* | Get-SysmonLinuxRawAccess | select image,user -Unique | ConvertTo-SysmonRule
<Rule groupRelation="and">
  <Image condition='is'>/usr/sbin/grub-probe</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/sbin/blkid</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/systemd/systemd-logind</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/sbin/dumpe2fs</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/systemd/system-generators/systemd-gpt-auto-generator</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/bin/mount</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/systemd/systemd-udevd</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/udev/scsi_id</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/udev/cdrom_id</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/udev/ata_id</Image>
  <User condition='is'>root</User>
</Rule>
<Rule groupRelation="and">
  <Image condition='is'>/usr/lib/udisks2/udisksd</Image>
  <User condition='is'>root</User>
</Rule>

I do hope that others find the module useful and will leverage it when working with Sysmon for Linux.

Beyond the Technical - Advise for those starting in Infosec

One question I get on a regular basis is “I want to start a career in infosec where do I start?” and when I ask in what area of infosec one of the most common answer if not the only one is “I want to hack”. When I hear this, I see the focus is mostly on doing cool stuff, that is their strategic goal. I believe having this goal is not a bad one since they are looking for something that will fulfill them and they find fun but, in my opinion, I find it to be also a goal that will lead to more stress and frustration since it will not match reality. You see when one works in information security consulting or as an internal team the business goal of your customer is the security of the system, your goal is to provide as much as possible a service that ensures that all security risk that can be managed are covered. What does this then entail for the person that wants to become a practitioner? It means that since they work under the context of value to the business that a lot of their work will be around how they can best serve the goals of the business without impacting them in a negative manner. What does this mean for the person that wants to be great at their job in infosec, you have to remember not everyone wants to be great many just want to do tasks they like and that ambition of being great professionally is not part of their goals, for those that do it means that they have to focus on areas other than the technical side of TTPs and IOCs. The areas of study and focus should be:

 

How does a business operate, one has to remember that depending on customer one has to ask how are they structured, what do they do and what are the business goals? Without this basic information one does not have the proper context to make decisions on the actions they need to do.

  • Understand Team dynamics, in addition to the regular business processes, one also needs to cultivate political collateral, by this I mean to understand the different inter department and internal department politics, build rapport with the leaders of the teams and their key members. Many times, when it comes to getting thing done this built collateral will help in getting things approved and also come in to play in better understanding what level of effort will be involved to get things done since all play a part and they buy in will dictate the tempo of operation.

  • Soft skills, any consultant with experience will tell you that the quality of the reports and presentations that are the results of an engagements will make or break the reputation of the consultancy, if recommendations are implemented and if one becomes a trusted advisor or not that gets brought in in the future. This is where having that business knowledge and political collateral come in to play because one can tailor how information is presented so it has the biggest impact.

  • Understanding the market, many practitioners will subscribe to podcasts, YouTube channels and blogs on only the area they are interested in, be it attack emulation or incident response, security operations or DevSec but very few subscribe to other technology podcasts that discuss enterprise technology. Gaining this information is key in to understanding where to allocate time to study and practice since those with the knowledge in those areas when a enterprise decides to look in to it will have a higher advantage, also when operating in enterprises many do not focus on those systems with the depth of knowledge that may be needed to know how to target and communicate in relation to it. (Examples are Software as a Service, Platform as a Service and Infrastructure as a Service in cloud environments).

  • Investment on self, one area that I hear complains constantly of those that are in a field and been able to get their foot in the door is lack of personal development planning in consultancies and business. My normal advice may sound harsh but a softer version of it is to don’t care and invest in one self, it is an investment that with time and effort will provide compound interests. Don’t wait for others but move first, many resources are free like the Microsoft Virtual Academy, others are low cost like Udemy, others provide a wider range of subjects missed by the technical side like LinkedIn Learning. The important part is to plan and invest in yourself, outwork the naysayers.

 

As you can see there is a lot of foundational areas of understanding and mastery outside of the technical, in fact many of these areas dictate where you invest your time and resources when it comes on what you focus on the technical realm since at the end of the day you are providing a business with a service.

An example from when I was a Senior Solution Architect working on how to secure a new datacenter for a customer in Central America. The datacenter was going to be hosting very important data. As part of my prepwork I made sure to find out the mission statement for the government agency I was working with, how did the project and goals related to the mission statement, who where the backers of the project, their motivation and many more in lunches, conference calls and any other opportunity. When I flew back to work on the plan I knew how to target my wording and phases of the project design to ensure each of the stakeholders inside and outside the agency would resonate with parts of it and ensure the rest in some way supported their individual goal and agendas in one manner or the other. This ensure quick buy in and ensured as a pushed for stuff to be monitored, controls be placed on different areas that the benefits expressed for each would mean that they would be putting in risk their own goals and ambitions in risk, I hacked the organizational thinking structure you may say. This is something that it is not a bit that is on or off, it was me getting out of my confort zone and being happy that my boss at the time took the time to mentor me and forced me to go to project management training, sales training, effective communication seminar and many other stuff outside of my technical area of expertise so he could have a more balanced resource.

Your mentality has to be to never be outworked by the competition. or unprepared for the situation, always striving to be balanced and not leave stuff to chance. Set your standard, work on achieving it and then set a new one.

Operational Thoughts in Trying Times

This post is as much as a reminder to myself of where I should focus on the multiple jobs I have and also share with the community are large what I consider important and key in this trying times.

Last year a dinner I had a very nice conversation with my friend Ed Skoudis on security consultancies and how many operated. This conversation covered many aspects from markets, politics, engagement best practices, retention of employees, and knowledge collection. Later at the end of the year, I had a good brainstorming session with Andrew Thompson via DMs on how recessions and the cyclical up and down of markets may change security consultancies where those that can adapt the faster, have worked to provide the greatest diverse value and have planned ahead for the changes will be the ones to dominate when the market is down. The initial seed for these conversations came from multiple videos from Gary Vee. I think with what is currently happening with COVID19 pandemic I would like to share my options on this.

Half of my career in infosec has been as a lead or a manager leading groups from 2 all the way to 24 in multiple projects. I had the luck to be in organizations that during some time periods I had some of the best upper managers, in my opinion, I could ever wish for. Under them, I saw companies grow exponentially and produce some of the best resources I have ever worked with. I now from time to time advise startups as part of my work for an incubator and I would like to share some of the advice I give based on the experience I have so far.

Read More

Getting DNS Client Cached Entries with CIM/WMI

What is DNS Cache

The DNS cache maintains a database of recent DNS resolution in memory. This allows for faster resolution of hosts that have been queried in the recent past. To keep this cache fresh and reduce the chance of stale records the time of items in the cache is of 1 day on Windows clients. 

The DNS Client service in Windows is the one that manages the cache on a system, This time Window can be modified via the registry in the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache\Parameters where the MaxCacheTtl property controls the time in the cache in seconds and the MaxNegativeCacheTtl property controls the time a failed response is cached.  

Why is it Important

For an attacker, it means primarily situational awareness. It allows him to know what other systems this host has accessed and the IP address of the host. This may allow identifying security platforms by the FQDNs used as well as business process systems, both internal or in the cloud. On an important note for the attacker is that if his implant/agent on the system does not include its own resolution capability it has an IOC present on the system that can be used to track its command and control infrastructure. 

For a defender, the ability to know what hosts a system may have connected to in the last 24 hours. This will permit a defender to query across his environment for hosts that are communicating or have communicated with a specific host if DNS resolution was part of the process and if the attacker is not using its own resolution method. If the attacker is “Living off the Land” and using OS tools it will still leave the femoral trace on the system until the cached entry TTL (Time to Live) expires.

MSFT_DNSClientCache class

In Windows 8/2012 Microsoft added the MSFT_DNSClientCache class into the CIM object database in Windows. The class is under the new namespace that was also added to Root\StandardCimv2 and the resources are provided as part of the DnsClientCim.dll. This allows us to query for instances of the class and get all entries for the DNS Cache database. 

Read More