CTF思路
点击放大


<h2 align="center">Remember to take a look at the <code>/More</code> folder! ;)</h2>
<br>
<di="center">
!Hits
!GitHub Stars
!Last Commit
!Repo Size
<!-- !GitHub Forks
!GitHub Watchers -->
</div>
<p align="center">
Thank you for exploring this project! I hope you will find the content and perhaps e sharing with others. This project represents years of dedication, learning, and refinement, fueled by countless hours and cups of coffee ☕. If you’d like to support its continued growth, your contribution would be highly appreciated.
</p>
<!-- <br> -->
<!--
<p align="center">
<a href=" target="_blank">
<img src=" alt="Buy Me A Coffee" height="50px">
</a>
</p>
-->
Host-based IDS (HIDS): Installed on an OS to monitor inbound/outbound host traffic and running processes.
Network-based IDS (NIDS): A dedicated device or ser network traffic via a switch’s monitor port to detect malicious activity across the network or VLANs.
Some of these pro are:
* IVPN
* Mullvad
* ProtonVPN
Some of these pro are:
* Vultr
* Linode
* DigitalOcean
* OneHostCloud
| Term | Description |
|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------|
| Virus | Malware that infects a computer by inserting itself into programs, potentially causing data and program damage. Needs user interaction to spread. |
| Worm | Malware that replicates itself and spreads without user interaction, often through networks, email, or other means. |
| Trojan horse | Malware disguised as a legitimate program that performs harmful actions once inside a system. |
| Spyware | Malware that secretly collects information about a user's acti and reports it back to the attacker. |
| Phishing | A technique to steal sensiti by posing as a legitimate organization or indi. |
| DoS attack | O a system with traffic to disrupt its services. |
| DDoS attack & botnets| A distributed denial-of-service attack using a network of compromised devices to o a target with traffic. |
| Spam | Unwanted email that can o recipients and may spread malware or phishing attempts. |
| Ransomware | Malware that encrypts data and demands payment for decryption. |
| Rootkit | Malware that grants an attacker root access and conceals its presence from the user. |
| Adware | Malware that displays unwanted ad on a computer. |
Protecting against disclosure, alteration, and destruction/denial is very important, as this protection is equi to working to maintain confidentiality, integrity and a.
1. Simple Security Property: This property is referred to as “no read up”; it states that a subject at a lower security le read an object at a higher security level. This rule prevents access to sensiti above the authorized level.
2. Star Security Property: This property is referred to as “no write down”; it states that a subject at a higher security le write to an object at a lower security level. This rule prevents the disclosure of sensiti to a subject of lower security level.
3. Discretionary-Security Property: This property uses an access matrix to allow read and write operations. An example access matrix is shown in the table below and used in conjunction with the first two properties.
The first two properties can be summarized as “write up, read down.” You can share confidential information with people of higher security clearance (write up), and you can recei information from people with lower security clearance (read down).
| Subjects | Object A | Object B |
| --- | --- | --- |
| Subject 1 | Write | No access |
| Subject 2 | Read/Write | Read |
Limitation: It was not designed to handle file-sharing.
1. Simple Integrity Property: This property is referred to as “no read down”; a higher integrity subject should not read from a lower integrity object.
2. Start Integrity Property: This property is referred to as “no write up”; a lower integrity subject should not write to a higher integrity object.
Limitation: Does not handle internal threats (insider threat).
When managing access rights, two crucial concepts are used: Pri Identity Management (PIM) and Pri Access Management (PAM).
What is essential when discussing pri and access controls is the principle of least pri. Simply, users should be given the minimum amount of pri, and only those that are absolutely necessary for them to perform their duties.
1. Trust but : the actions of trusted entities through automated security mechanisms like logs and intrusion detection.
2. Zero Trust: Assume no trust and require authentication and authorization for all access, reducing the potential impact of breaches. Implementations like microsegmentation enhance security.
This process is very similar to a risk assessment made in workplaces for employees and customers. The principles all return to:
It is, however, a complex process that needs constant review and discussion with a dedicated team. An effecti model includes:
* Threat intelligence
* Asset identification
* Mitigation capabilities
* Risk assessment
To help with this, there are frameworks such as STRIDE (Spoofing identity, Tampering with data, Repudiation threats, Information disclosure, Denial of Service and Ele of pri) and PASTA (Process for Attack Simulation and Threat Analysis)
<img style="display:block; margin:0 auto;"
src="./Images/Pyramid-of-pain.png" alt="Pyramid of pain" width="480"/>
The idea is that organizations should focus their cybersecurity efforts on the assets at the top of the pyramid to prevent the most significant damage from a security breach. The components of the Pyramid of Pain may vary depending on the organization and its specific needs, but typically include sensitive data, critical infrastructure, key personnel, and reputation.
Benefits include better security posture, stakeholder confidence, regulatory compliance, alignment with business objectives, informed decision-making, and competiti.
#### De Go Documents
De go documents can involve the following steps:
1. Identify Scope and Purpose: Define what the document will cover and its necessity.
2. Research and Review: In laws, regulations, and best practices to make the document comprehensive.
3. Draft the Document: Create an actionable, specific draft aligned with organizational goals.
4. Review and Approval: Invol for feedback and final approval.
5. Implementation and Communication: Distribute the document and educate employees.
6. Review and Update: Regularly update the document for relevance and compliance.
#### Preparing a Password Policy - Real-world Scenario
Let's take a real-world scenario of preparing a password policy.
#### Making an Incident Response Procedure - Real-world Scenario
Now, let's take a real-world scenario of making an incident response procedure.
| Stage | Description |
|---|---|
| Information Gathering | This stage in collecting as much publically accessible information about a target/organisation as possible, for example, OSINT and research. Note: This does not invol any systems. |
| Enumeration/Scanning | This stage in disco applications and services running on the systems. For example, finding a web server that may be potentially . |
| Exploitation | This stage in le discovered on a system or application. This stage can involve the use of public exploits or exploiting application logic. |
| Pri Escalation | Once you ha exploited a system or application (known as a foothold), this stage is the attempt to expand your access to a system. You can escalate horizontally and , where horizontally is accessing another account of the same permission group (i.e. another user), whereas is that of another permission group (i.e. an administrator). |
| Post-exploitation | This stage in a few sub-stages: <ol><li>What other hosts can be targeted (pi)</li><li>What additional information can we gather from the host now that we are a pri user</li><li>Co your tracks</li><li>Reporting</li></ol> |
| Box | Description |
|---|---|
| Black | This testing process is a high-le where the tester is not given any information about the inner workings of the application or service. |
| Grey | The tester will have some limited knowledge of the internal components of the application or piece of software. |
| White | The tester will have full knowledge of the application and its expected behaviour. |
OWASP is known for its widely-referenced OWASP Top 10, a standard awareness document for de and web application security that lists the most critical security risks to web applications.
The framework is divided into six core functions:
* Govern: Establish o to manage and reduce cybersecurity risks across the organization.
* Identify: Understand your systems, assets, and risks.
* Protect: Implement safeguards to ensure services' security.
* Detect: Identify cybersecurity threats and breaches in real-time.
* Respond: Take action when cybersecurity events are detected.
* Recover: Restore operations and impro post-incident.
The CAF aligns with NIS regulations and is structured around 14 objectives, categorized into four main goals: managing security risk, protecting against cyber attacks, detecting cybersecurity events, and minimizing the impact of incidents. It provides comprehensi of good practice for organizations to assess and impro security posture
The Unified Kill Chain consists of the following stages:
1. Reconnaissance: Gathering information about the target.
2. Weaponization: De or obtaining the tools needed to exploit .
3. Delivery: Deli the weaponized payload to the target.
4. Exploitation: Exploiting to gain access to the target.
5. Installation: Installing malware or other tools to maintain access to the target.
6. Command and Control: Establishing communication channels to control the compromised system.
7. Actions on Objectives: Achieving the attacker's goals, such as stealing data or disrupting operations.
See the 18 phases of attack here.
The fi principles outlined in ISO/IEC 19249:
1. Domain Separation: Components are grouped into distinct entities, each with its own domain and set of security attributes. This separation helps control access and pri. (Architectural Principle: 1)
2. Layering: The system is structured into abstract levels or layers, enabling the imposition of security policies at different levels and facilitating of system operations. (Architectural Principle: 2)
3. Encapsulation: In hiding low-le and pre direct manipulation of data by pro specific methods, similar to object-oriented programming, to ensure data integrity. (Architectural Principle: 3)
4. Redundancy: Ensures a and integrity by implementing redundancy measures. Examples include redundant power supplies or RAID configurations in data storage. (Architectural Principle: 4)
5. : Sharing a single set of hardware among multiple operating systems, which enhances security boundaries and containment of malicious programs, particularly relevant in the context of cloud services. (Architectural Principle: 5)
An ISMS consists of the policies, procedures, guidelines, and associated resources and acti, collectively managed by an organization, in the pursuit of protecting its information assets.
It is a systematic approach for establishing, implementing, operating, monitoring, re, maintaining and improving an organization’s information security to achie objectives. It is based on a risk assessment and the organization’s risk acceptance levels designed to effectively treat and manage risks.
<details>
<summary>List of contents</summary>
1. File & Directory Management
2. User & Permission Management
</details>
In this section: pwd, ls, tree, mkdir, touch, cat, stat, mv, rm, ln (symbolic links), apt, Operators, File Descriptors
<Details open>
<summary>Hide File & Directory Management Commands</summary>
Key options: -l = long listing format -a = include hidden files (starting with .) -h = human-readable sizes (e.g., KB, MB) -t = sort by modification time (newest first) -r = reverse order of sort -S = sort by file size
You can combine options, e.g., ls -lahtrS
Key options: -a = show hidden files -d = list directories only -L <level> = limit the depth of the directory tree displayed -h = human-readable sizes -f = print the full path prefix for each file
Key options: -p = create parent directories as needed (e.g., mkdir -p Folder/i/am/in) -v = output, showing created directories
Key options: -n = show numbers -b = show numbers for non-blank lines
These informations can be: file name, file size, blocks, type, inode, UID, GID, access, modify, change and creation times.
Key options: -v = output, showing what is being removed -r = Deletes every file in the directory -f = Suppresses all warning prompts
This creates a symbolic link named flag that points to the file /root/flag.txt.
You can also use it with other commands, such as cat to read the contents of the file through the symbolic link:
Which will display the contents of the file /root/flag.txt.
> redirects command output to a file, replacing its contents. >> appends command output to the end of a file, keeping existing data. | pipes the output of one command as input to another command.Data Stream for Input → STDIN – 0
Data Stream for Output → STDOUT – 1
Data Stream for Output that relates to an error occurring. →STDERR – 2
To redirect Redirect STDERR to /dev/null, which is a special file that discards all data written to it, you add 2>/dev/null to your command. This is useful for suppressing error messages.
Redirect STDOUT and STDERR to Separate Files
</Details>
In this section: whoami, adduser & addgroup, chmod, chown, sudo
<Details open>
<summary>Hide User & Permission Management Commands</summary>
adduser and addgroup are commands used to create new users and groups, respectively.The syntax for both of these commands are adduser username and addgroup groupname.
Add a user to a group
> You can add a user to multiple groups by separating the group names with commas.
Permissions
| Digit | Meaning |
|----------|:-------------:|
| 1 | That file can be executed |
| 2 | That file can be written to |
| 3 | That file can be executed and written to |
| 4 | That file can be read |
| 5 | That file can be read and executed |
| 6 | That file can be written to and read |
| 7 | That file can be read, written to, and executed |
To make a binary file just executable for the owner of the file, you can use:
Key options: -R = recursively change ownership of files and directories within a directory -v = output, showing what is being changed
Key options: -u <user> = specify user su = change to root -l = list current sudo pri
</Details>
In this section: ps, top, htop, lsof, kill, free, df, du, ncdu, history, uname
<Details open>
<summary>Hide Process & System Monitoring Commands</summary>
Key options: -f = full format listing -o = user-defined output format (e.g., ps -eo pid,comm) -a = all processes from all users -u user-oriented format -x will display all processes e not associated with the current tty -t Processes associated with the terminal run
Key options: -i <seconds> = delay between updates (default is 3 seconds)
Key options: -C Use colors in the output -d Delay between updates, in tenths of seconds -u Show only processes owned by a specified user -p Show only processes with specified process IDs -s Sort by specified column (use --sort-key help for a list) -t Tree view -U Do not use unicode but plain ASCII
Key options: -i = Show network connections (e.g., lsof -i :80 for port 80) -u = Show files opened by a specific user (e.g., lsof -u username) -p <PID> = Show files opened by a specific process ID -n = Show numerical addresses instead of resolving hostnames
The most commonly used signals:
1 (HUP) - Reload a process.
9 (KILL) - Kill a process.
15 (TERM) - Gracefully stop a process.
Options: -b = to display the amount of memory in bytes -k = to display the amount of memory in kilobytes -m = to display the amount of memory in megabytes -g = to display the amount of memory in gigabytes -h = to display the amount of memory in a human-readable format -s <sec> = to update the output every X seconds
Key options: --block-size=SIZE = scale sizes by SIZE. E.g., -BM prints sizes in units of 1,048,576 bytes. --exclude-type=TYPE = exclude file systems of type TYPE -h = print sizes in human readable format (e.g., 1K 234M 2G) -T = print file system type -t = limit listing to file systems of type TYPE
Key options: -a = to display an entry for each file in a file hierarchy -c = displays total size at the end -d <number> = to specify the depth of the directory tree to be displayed -h = to get a human-readable output -L = dereference all symbolic links -s = to get the total size of the directory --time get the results with timestamps of last modification
Options: -x = This option prevents ncdu from following symbolic links. --si = This option makes ncdu use powers of 1000 instead of 1024 for sizes.
Key options: -a = print all information -s = print the kernel name -n = print the network node hostname -r = print the kernel release -v = print the kernel -m = print the machine hardware name -p = print the processor type (if a) -o = print the operating system name
Install: sudo apt install neofetch or see here.
</Details>
In this section: file, strings, exiftool, hexdump, xxd, objdump, hexeditor, binwalk
<Details open>
<summary>Hide File Inspection & Forensics Commands</summary>
file command is used to determine the type of a file by examining its contents rather than relying on file extensions.Install with: sudo apt install libimage-exiftool-perl
Key options: -all= = remove all metadata from the file -s = short output format -h = HTML output format -json = JSON output format -r = recursi of directories -o = o the original file with the modified file
Key options -C = Canonical hex + ASCII display. -c = One-byte character display. -d = Decimal display. -e <FORMAT> = Specify the output format. -n <N> = Stop after reading N bytes. -s <OFFSET> = Start reading at OFFSET bytes. -v = Display all data, even if it is repeated.
Key options -b = binary digit dump -p = plain hex dump (continuous string) -e = little-endian dump -l <LEN> = stop after <len> octets. -r = hex dump to binary (plain text) -d = show offset in decimal instead of hex. -u = use upper case hex letters. -i = output in C include file style. -s = start at offset.
Key options: -d = disassemble the file -s = display the full contents of the file -t = display the symbol table -x = display all headers and sections -f = display the file header information -h = display the section headers
Key options -a Print all text characters. -n Force Gray scale, no colors.
-- Shortcuts --
CTRL + F = Go to last line
CTRL + C = Exit without saving
CTRL + X = Exit and save
CTRL + U = Undo
CTRL + W = Search
Key options: -e = Extract files -M = Recursively scan extracted files (matryoshka) -v = output -q = Quiet output (suppress non-error messages)
</Details>
In this section: find, where, locate, whatis, apropos, grep, uniq, sort, diff, tail/head, wc, cut, tr, column, jq, sed, awk
<Details open>
<summary>Hide Searching & Text Processing Commands</summary>
Syntax: find <location> <options>
Key options -name = specify file specific name/descriptions to be found -iname = Like -name, but the match is case insensitive. -print = It prints the pathname of the current file to standard output. -regex = True if the whole path of the file matches pattern using expression -type = With -type, you can use d to only find directories, and f to only find files. -user = specify owner -size = specify size -perm = specify permissions -exec = Execute a command on the found files. The command must end with \; -newer = Find files that are newer than a specified file. -newermt = Find files modified after a specific date.
Location specific options
No specification = current folder / = root folder . = this folder and its subdirectories
Time specific options -amin <n> = Access time in minutes. -mmin <n> = Modification time in minutes. -ctime <n> = Change time in minutes. -atime <n> = Access time in days. -mtime <n> = Modification time in days. -ctime <n> = Change time in days.
To put it all together: in order to specify that a file was last accessed more than 30 minutes ago, the option -amin +30 is used.
To specify that it was modified less than 7 days ago, the option -mtime -7 is used.
When you want to specify that a file was modified within the last 24 hours, the option -mtime 0 is used.
Note
1. Suppress the output of any possible errors to make the output more readable. This is done by appending 2> /dev/null to your command. This way, you won't see any results you're not allowed to access.
2. The second thing is the -exec flag. You can use it in your find command to execute a new command, following the -exec flag, like so: -exec whoami \;. (can be used for pri escalation)'
> Good for finding the location of a command or executable file in the system.
Key options -i = ignore case (case insensiti) -o = show only the matching part of the line -l = show only the names of files with matching lines -c = count the number of matching lines -n = line numbers for every string found -w = match whole words only -x = match whole lines only -E = regular expressions -R = recursive grep
Key options -c = count the number of occurrences of each line -d = only print duplicate lines -u = only print unique lines -i = to ignore case
Options: -b = ignore leading blanks -c = check if the file is sorted -r = to sort in reverse order -o = to write output to a file -u = sort and remo lines -n = to sort numerically -g = to sort general-numeric -h = to sort human readable numbers -f = ignore case
Key options: -u = unified diff format (shows context) -c = context diff format (shows more context) -i = ignore case differences -w = ignore all white space -b = ignore changes in the amount of white space -B = ignore changes whose lines are all blank
tail and head commands are used to display the beginning or end of a file.Key options: -n <number> = number of lines to show -c <numbers> = number of bytes
Key options -l = count number of lines -w = count number of words -c = count number of bytes -m = count number of characters
Key options -f = Select by specifying a field, a set of fields, or a range of fields. -c = Select by specifying a character, a set of characters, or a range of characters. -d = Specify a delimiter that will be used instead of the default “TAB” delimiter.
Key options -d = delete characters -s = squeeze repeated characters
column command formats text input into a table-like structure, aligning columns based on whitespace or a specified delimiter.To install use sudo apt install jq
Key options: -c = compact output (minified JSON) -r = raw output (without quotes) -s = read input as an array of JSON objects -f <file> = read filter from a file
The "s" flag at the beginning stands for the substitute command. Then we specify the pattern we want to replace. After the slash (/), we enter the pattern we want to use as a replacement in the third position. Finally, we use the "g" flag, which stands for replacing all matches.
Key options: -F = specify the field separator (default is whitespace) -v = assign a value before processing the input -o = output file (not commonly used)
Commonly used : $0 = Represents the entire line of text. $1, $2, ... = Represents the first, second, etc., fields in the line. $NF = Represents the last field in the line. $NR = Represents the current record number (line number). $FS = Field separator (default is whitespace). $RS = Record separator (default is newline). $OFS = Output field separator (default is space). $ORS = Output record separator (default is newline). /<pattern>/ = Represents a pattern to match in the input.
<details>
<summary>Ad examples</summary> <br>
</details>
</Details>
In this section: ip, ping, traceroute, telnet, curl, wget, ftp, ssh, scp, xfreerdp, netdiscover, netstat, ss, tcpdump, dig, wash, whatweb
<Details open>
<summary>Hide Networking Tools Commands</summary>
ip command is used to show and manipulate routing, devices, policy routing, and tunnels. It is a powerful tool for managing network interfaces and configurations.<details>
<summary>Want to see more ad usage of the <code>ip</code> command?</summary>
</details>
ping command is used to check the reachability of a host on a network and measure the round-trip time for messages sent from the originating host to a destination computer.Key options: -c <count> = Number of packets to send -i <interval> = Inter packets (in seconds) -s <size> = Number of data bytes to be sent -W <timeout> = Time to wait for a response (in seconds) -t <ttl> = Set Time To Li of hops) -I <interface> = Specify the source interface to use
traceroute command is used to trace the route that packets take from the source host to a destination host. It shows the IP addresses of the routers along the path and the time taken for each hop.> On Windows, use tracert instead of traceroute.
Key options: -n = Do not resol (show only IPs) -m <max_ttl> = Set the max number of hops (max TTL) -w <timeout> = Set the timeout (in seconds) for each reply -q <nprobes> = Number of probe packets per hop -I = Use ICMP ECHO instead of UDP packets (like Windows tracert) -T = Use TCP SYN packets instead of UDP
telnet command is used to connect to remote servers using the Telnet protocol. It allows you to interact with remote systems over a network.Key commands inside a Telnet session:
Ctrl + ] = Escape to telnet promptquit = Exit telnetopen <host> <port> = Connect to another host/portclose = Close current connectionstatus = Print status informationKey options: -s to suppress the output (statistics) -# show progress bar -o page.html <URL> to save the output to a file -O <URL> to save the output to a file with the same name as the file in the URL (download) -I <URL> to get the headers only -L <URL> to follow redirects -b <NAME1=;NAME2=> specify cookies -d <data> <URL> to send data -X <METHOD> <URL> to change the request method -T <FILE> <URL> to upload a file -u <USER>:<PASSWORD> to authenticate -A <AGENT> <URL> to change the user agent --referer <URL_REF> <URL> to change the referer -H <HEADER> <URL> to add headers -H "DNT: 1" <URL> to change the DNT(do not track) header -H "X-Forwarded-For: <IP>" <URL> to change the X-Forwarded-For header -H "Accept-Language: da-DK" <URL> to change the Accept-Language header (ex. Danish) -H "Date: Mon, 23 11 2018 23:23:23 GMT" <URL> to change the date
Demo of ad use case
Key options: -O = to specify the output file -b = to run in the background -r = to download recursively -q = to download in quiet mode
Enter your username and password to log in to the server. Some FTP servers allow anonymous logins with a username and password of "anonymous".
Key Commands: ls = list files in the current directory cd <directory> = change directory get <file> = download a file from the server put <file> = upload a file to the server more <file> = view the contents of a file quit = exit the FTP session
See more commands here.
And then type the password to log in. If you have a private key, you can use it to log in without a password.
Creating an SSH tunnel
Key options: -i <path_to_pem> = specify the path to the private key file -p <port> = specify the port to connect to (default is 22) -v = mode (useful for debugging) -X = enable X11 forwarding (allows running GUI applications over SSH) -C = enable compression (useful for slow connections) -N = do not execute a remote command (useful for port forwarding) -L <local_port>:<remote_host>:<remote_port> = local port forwarding -R <remote_port>:<local_host>:<local_port> = remote port forwarding
Key options: -r = copy directories recursively -P <port> = specify the port to connect to (uppercase P) -i <path_to_pem> = specify the path to the private key file -v = mode (useful for debugging) -p = preserve file attributes (permissions, timestamps, etc.)
Key options: /u:<username> - Username /p:<password> - Password /v:<hostname>:<port> - Ser /cert:ignore - Ignore certificate /ipv6, /6 - Prefer IPv6 AAA record over IPv4 A record
aircrack-ng suite).> It is particularly useful for identifying acti on a network, especially in en where DHCP is not a or when you want to quickly disco without using more complex tools.
Key options: -t = show TCP connections -u = show UDP connections -l = show only listening sockets -p = show the process using the socket -n = show numerical addresses instead of resolving hostnames (stops DNS lookups) -a = show all connections and listening ports -r = display the routing table
> 'ss' is now a better alternative to netstat, see below.
netstat command and provides more detailed information about sockets.Key options: -i = to specify the interface to capture traffic on -n = to display IP addresses instead of hostnames (stops DNS lookups) -w = to write the captured packets to a file -r <file>.pcap = to read packets from a file -q = to get brief packet information -e = to include MAC addresses -A = to print packet data as ASCII -c <number> = to specify the number of packets to capture -v = to increase (use -vv for more)
* <domain> = The domain name to query (e.g., example.com)
* <type> = The type of DNS record to query (e.g., A, MX, CNAME, NS, etc.)
Key options: +short = Short output format +trace = Trace the delegation path from the root servers +noall +answer = Show only the answer section of the response -x = Specify IP adress -f = save to a file
aircrack-ng suite).Key options: -a=LEVEL = Aggresion level -U=AGENT = User agent --header = HTTP header --max-redirects=NUM = Maximum number of redirects -u=<user:password> = Basic authentication -c=COOKIES = Use cookies --cookie-jar=FILE = Read cookies from a file -g=STRING|REGEXP = Search for a string --no-errors = Suppress error messages -p=LIST = List all plugins -l = List all plugins -v = mode -q = Quiet output -h = to show help (highly recommended)
</Details>
In this section: Tar, Gzip, 7z
<Details open>
<summary>Hide Compression & Archiving Commands</summary>
tar is a command that allows creating, maintaining, modifying, and extracting files that are archived in the tar format (tar, gzip, zip).Key options: -c tells tar to create an archive. -z tells tar to compress the archive with gzip. -v tells tar to be . -f tells tar that the next argument will be the name of the archive to operate on. -C tells tar to change to the directory specified before performing any operations. -x tells tar to extract files from an archive.
gzip is a file format and a software application used for file compression and decompression. gzip-compressed files have a .gz extension.Key options: -d = decompress a file -k = keep the original file after compression -r = recursively compress files in directories -v = output, showing compression details -1 to -9 = set compression level (1 is fastest, 9 is best compression)
Key options: a = add files to an archive (-tzip for zip archives) x = extract files from an archive l = list contents of an archive -p<SECRET> = create or extract a password-protected archive -m0=LZMA2 = use LZMA2 compression method (default) -mem=AES256 = use AES-256 encryption for the archive -mx=9 = set compression level (0-9, where 9 is the highest compression) -t7z = specify the archive type as 7z -o<output_directory> = specify the output directory for extraction
Demo use case:
Ad Example
> Without -mem=AES256, the contents will be compressed but the file names will still be (no filename encryption).
This command creates a password-protected zip archi secret.zip containing the secret directory, using AES-256 encryption.
For simple zip -e -r secret.zip secret can also be used (legacy).
</Details>
In this section: base64 (Encoding), rax2 (Base Con), hashid (Hash Identification), hash-identifier (Hash Identification), haiti (Hash Analysis), shasums (SHA Checksums), gpg (Encryption/Decryption)
<Details open>
<summary>Hide Cryptography & Encoding Commands</summary>
The -d option is used to decode the base64 encoded data.
Encrypt base64
The -i option is used to specify the input file, and the -o option is used to specify the output file. If no output file is specified, it will print the encoded data to standard output.
A list of most useful flags:
Key options: -e = list all possible hash algorithms including salted passwords -m = include corresponding hashcat mode in output -j = include corresponding JohnTheRipper format in output -o FILE = write output to file (default: STDOUT) -h = show help message and exit
Installation: gem install haiti-hash
Find SHA256 hash for a file
Find MD5 hash for a file
> Enter a passphrase when prompted. This will create an encrypted file named data.txt.gpg.
To decrypt the file:
> Enter the same passphrase you used to encrypt the file. This will output the decrypted content to standard output.
</Details>
In this section: searchsploit, cewl, crunch, fcrackzip
<Details open>
<summary>Hide Exploitation & Pentesting Tools Commands</summary>
Key options: -c [Term] = Perform a case-sensiti -e [Term] = Perform an EXACT search -s = Perform a strict search ("1.1" would not be detected in "1.0 < 1.3") -t [Term] = Search JUST the exploit title (Default is title AND the file's path -p [EDB-ID] = Show the full path to an exploit -w = Show URLs to Exploit-DB.com rather than the local path --exclude="term1|term2" = Exclude results matching terms (use "|" to separate multiple)
Install: sudo apt-get install cewl
Key options:
-w for saving the generated wordlist to a file.-d for setting the depth of the spider.-m for setting the minimum word length.-x for setting the maximum number of words to return.Install: sudo apt-get install crunch
Key options: -t for adding a pattern to the generated wordlist. -o for saving the generated wordlist to a file.
.zip files. It can use brute force or dictionary attacks to crack the password of a zip file.Install: sudo apt-get install fcrackzip
Key options -b for using brute force algorithms. -D for using a dictionary. -v for mode. -p for using a string as a password. -u for unzipping.
</Details>
In this section: gcc
<Details open>
<summary>Hide Compilers Commands</summary>
Key options: -o <output> = specify the output file name
</Details>
Legal Notice: Only use on systems you own or ha to test.
Key tools in suite:
See detailed cheatsheet here
gobuster -w wordlist.txtgobuster dir -u -w /usr/share/wordlists/dirb/megalist.txt DNS subdomain enumeration gobuster dns -d -w /usr/share/SecLists/Discovery/DNS/namelist.txt
dir Directory/file brute forcing mode dns DNS bruteforcing mode-u (url) – full target URL (including scheme), or base domain name. -w (wordlist) – path to the wordlist used for brute forcing (use – for stdin). -a (user agent string) – specify a user agent string to send in the request header. -e (print) - Print the full URLs in your console -o (file) – specify a file name to write the output to. -x (extensions) – list of extensions to check for, if any. -P (password) – HTTP Authorization password (Basic Auth only, prompted if missing). -U (username) – HTTP Authorization username (Basic Auth only). -c <http cookies> (cookie) - Specify a cookie for simulating your auth -s (status-codes) - Set status codes that should be interpreted as valid -k (ssl) - Skip ssl certificate -H (HTTP) - Specify HTTP header -t (threads) - Number of concurrent threads (default: 10) -v () - output -q (quiet) - Quiet output -n (no-redirect) - Do not follow redirects -r (recursive) - Recursively brute force subdirectories Find a list of seclists here.
Syntax: feroxbuster [OPTIONS]
Example: feroxbuster -u -w /usr/share/wordlists/dirb/big.txt
Options: -h, --help - Print help information - - Print information -u, --url <URL> - The target URL -b, --cookies <COOKIE> - Specify HTTP cookies to be used in each request -m, --methods <HTTP_METHODS> - Which HTTP request method(s) should be sent (default: GET) -x, --extensions <FILE_EXTENSION> - File extension(s) to search for (ex: -x php -x pdf js) -C, --filter-status <STATUS_CODE> - Filter out status codes (deny list) (ex: -C 200 -C 401) -s, --status-codes <STATUS_CODE> - Filter status codes (allow list) (default: 200 204 301 302 307 308 401 403 405) -r, --redirects - Allow client to follow redirects -T, --timeout <SECONDS> - Number of seconds before a client's request times out (default: 7) -d, --depth <RECURSION_DEPTH> - Maximum recursion depth, a depth of 0 is infinite recursion (default: 4) -e, --extract-links - Extract links from response body and make new requests based on findings -L, --scan-limit <SCAN_LIMIT> - Limit total number of concurrent scans (default: 0, i.e. no limit) -n, --no-recursion - Do not scan recursively -t, --threads <THREADS> - Number of concurrent threads (default: 50) --time-limit <TIME_SPEC> - Limit total run time of all scans (ex: --time-limit 10m) -w, --wordlist <FILE> - Path to the wordlist -o, --output <FILE> - Output file to write results - - Increase level (use -vv or more for greater effect. '4' -v's is probably too much)
Learn How to brute-force passwords using GPU and CPU in Linux.
Convert WPA/WPA2 handshake from a pcap file to a modern hashcat compatible hash file.
hashcat -m <number> <hash_file> <dict_file>hashcat -m 1800 -a 0 hashed.txt /usr/share/wordlists/rockyou.txt -o output.txt Bruteforce hashcat -m 0 -a 3 -i hashed.txt ?a?a?a?a?a?a?a -o output.txt
-m sets the mode -a sets the attack mode (0=Straight,1=Combination,3=Bruteforce,6=Hybrid:wlist+mask,7=Hybrid:mask+wlist) -o output to filename -r sets rules --status keep screen updated --runtime abort after X seconds --force sets workload to insane (This can lead to false positives) -i increment (bruteforce)?l Lowercase a-z ?u Uppercase A-Z ?d Decimals ?h Hex using lowercase chars ?H Hex using uppercase chars ?s Special chars ?a All (l,u,d,s) ?b Binary hydra -options path hydra -l username -P path/to/wordlist.txt host_ip -t 4 ssh -VGuess Telnet credentials using a list of usernames and a single password, specifying a non-standard port and IPv6: hydra -L path/to/usernames.txt -p password -s port -6 host_ip telnet
Guess FTP credentials using usernames and passwords lists, specifying the number of threads: hydra -L path/to/usernames.txt -P path/to/wordlist.txt -t n_threads host_ip ftp
Guess MySQL credentials using a username and a passwords list, exiting when a username/password pair is found: hydra -l username -P path/to/wordlist.txt -f host_ip mysql
Web form credentials: hydra -l admin -P /usr/share/wordlists/rockyou.txt <ip_adress> http-post-form "/login:username=^USER^&password=^PASS^:F=Username or password invalid" -V
Guess IMAP credentials on a range of hosts using a list of colon-separated username/password pairs: hydra -C path/to/username_password_pairs.txt imap://[host_range_cidr]
Guess POP3 credentials on a list of hosts using usernames and passwords lists, exiting when a username/password pair is found: hydra -L path/to/usernames.txt -P path/to/wordlist.txt -M path/to/hosts.txt -F pop3
-S connect via SSL -f specify host -s specify a port -l single username -L wordlist username(s) -p single password -P wordlist password(s) -o FILE write found login/password pairs to FILE instead of stdout -V mode, see output for every attempt -I ignore the resume dialog -t <number> specifies the number of threads to use -u by default Hydra checks all passwords for one login and then tries the next login. This option loops around the passwords, so the first password is tried on all logins, then the next password. john <hash_file> --wordlist=<wordlist>john --format=raw_md5 --wordlist=/usr/share/wordlists/rockyou.txt hash.txtpython /usr/share/john/ssh2john.py id_rsa > hash.txtssh2john.py can sometimes also be located under /opt/john/ssh2john.py
Crack the hash (or a shadow file) john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt
See more about JTR.
First, convert the zip file to a hash zip2john file.zip > zip.hash
Then crack the hash john zip.hash
Single payloads use an underscore (e.g., generic/shell_re), while staged payloads use a slash (e.g., windows/x64/shell/re).
Initialize the database msfdb init
View ad options for starting the console msfconsole -h
Start metasploit msfconsole
Check db connection db_status
Msf commands help or ? - shows the help page
Search exploit search <exploit_for>
Select module use <module>
Change value of a set <> <value> get <> unset <>
Sa session save
Sa outputs spool
See pri of a current user getprivs
Tranfer files to computer upload
Check if the pc is in a ) run post/windows/gather/checkvm
See what a machine could be to run post/multi/recon/local_exploit_suggester
Spawn a normal system shell shell
word.exe) to interact with it or capture keystrokes. Use migrate <PID>.search -f <filename> to locate files with sensitive data.CTRL+Z to return to Meterpreter.These features make Meterpreter a powerful tool for post-exploitation acti.
See some of the a commands here.
nc -lvnp 6790 > testfile.txt nc [IP address of computer B] 6790 < testfile.txt <details>
<summary>Chat Ser</summary>
</details>
-l Listen to connections (TCP) -v Enable mode (allows you to see who connected to you) -p Specify a port to listen to -e Specify program to execute after connecting to a host -u Connect to UDP ports -n Fast scan by disabling DNS resolution -w Define timeout value -4 IPv4 only -6 IPv6 only > Server file redirection < Client file redirectionnikto -h <ip> -port <port>-h Hostname/IP adress -port Specify ports -nossl Disable ssl -ssl Force ssl -id Specify authentication(username & password) -plugin Select which plugin to use -update Update the plugin list --list-plugins List all possible plugins to use -output Output fingerprinted information to a fileNmap is a utility for network discovery and security auditing.
> Note, there is now a better and much faster alternative to nmap called rustscan. See more about it here.
nmap [options] [ip] Example: nmap -sT -T4 -A -p- 172.162.39.86
-sT -sS -sU ICMP Scanning (host discovery, no port scans) = -sn
Default ping scanning) = -sP
Detect OS = -O
Detect of services = -sV
Scan with the default nmap scripts = -sC
Disable host discovery and just scan for open ports = -Pn
ARP Scan (only on same subnet as target) = -PR
Change = -v
Change level two = -vv (It's good practice to *always* increase the in your scans.)
Save nmap results in three major formats = -oA [filename] [target]
Save nmap results in a text file = -oN [filename] [target]
Save nmap results in grepable format = -oG [filename] [target]
Aggresive mode (Enable OS detection, detection, script scanning, and traceroute) = -A
Timing leves (Speed of scans, can make errors) = -T<Level> (0-5)
Port scan (specific)= -p <port>
Port scan (range) = -p <from>-<to>
Port scan (all) = -p-
Activate a script= —-script=<script_name>
Decoy an ip adress, learn more = -D
Fast mode = -F
Only open ports = --open
List of hosts to scan = -iL
No DNS lookup = -n
Reverse DNS lookup = -R
Scan an IPv6 address = -6
Subnet mask with 255.255.255.0 = <ip>/24
rustscan -a 127.0.0.1 -p 53,80,121,65535Options -a A list of comma separated CIDRs, IPs, or hosts to be scanned -b <size> Batch size for parallel scanning (default 4500) -p <port1>,<port2> A list of commaseperated ports. -r <range> Specify range of ports (ex. 1-1000) --scripts <script> Run scripts -t <timeout> Timeout in milliseconds to consider port closed (default 1500) --tries <tries> Number of tries to consider port closed (default 1) -q Quiet mode.
> Note: RustScan, at the moment, runs Nmap by default. So you can also specify commsnds like -sC and -A.
sqlmap <option> <url>-u - URL to test for SQL injection -g - Google Dork to test for SQL injection -p - Parameter to test for SQL injection -D - Dump a specific database to enumerate -T - Dump a specific table to enumerate -C - Dump specific columns to enumerate --level - Level of tests to perform (1-5) --dbms - Force SQLMap to use a specific DBMS --dump - Dump the contents of the database --dump-all - Dump all databases --os-shell - Get an OS shell --batch - Automatic run, won't ask for user input --tables - Dump all tables --columns - Dump all columns --threads - Number of threads to use --level - Level of tests to perform (1-5 def: 1) --risk - Risk of tests to perform (1-3 def: 1) --dbs - List databases --technique - Specify a technique to use (B: Boolean-based blind, E: Error-based, U: Union-based, S: Stacked queries, T: Time-based blind)
SQLMap to try and bypass the WAF by using --tamper=space2comment
Dumping some data inside columns from a table in a database.
List tables in a database.
List columns in a table in a database.
Dump data from columns in a table in a database.
When to Use GUI Tools:
Key Features:
Common Workflow:
1. Create new case
2. Add data source (disk image, dri files)
3. Configure ingest modules (hash lookup, keyword search, etc.)
4. Analyze results in views
5. Generate reports
Supported Formats:
1. Download Foxy Proxy in order to fully le the proxy, we'll have to install the CA certificate included with Burp Suite (otherwise we won't be able to load anything with SSL).
2. Now click on the extension -> Options -> Add -> Fill in the fields with the following :
1. Title = Burp
2. Proxy type = HTTP
3. Proxy IP adress or DNS name = 127.0.0.1
4. Port = 8080
5. Username and password is optional.
3. And hit save.
4. Finally, click on the FoxyProxy extension icon again and select 'Burp'.
5. With Firefox, na to the following address:
6. Click on 'CA Certificate' in the top right to download and save the CA Certificate.
7. Now that we' the CA Certificate, move over to the settings menu in Firefox. Search for 'Certificates' in the search bar.
8. Click on 'View Certificates'. Next, in the Authorities tab click on 'Import' and then OK.
Ctrl + U to make a payload safe to send.sudo dpkg -i package_file.debsudo /bin/systemctl start nessusd.service (Accept risk in case you get prompted)Since this section is very large, I' an indi page for this, which can be found inside this repository by clicking here.
^G Display help text. ^O Write the current file to disk ^X Exit nano. ^T Invoke spellcheck, if installed. ^Y Next screen. ^V Previous screen. ^L Refresh (force redraw) current screen. ^J Justify current paragraph. (Join together broken lines of text until double newline is encountered.) ^W Search for a string or regular expression. ^\ Search and replace a string or regular expression Command mode – allows you to run commands (Default). Insert mode – allows you to insert/write text. mode – text selector.
h – move the cursor left j – cursor down k – cursor up l – move the cursor right i – enter the insert mode esc – enter the command mode $ – move to the end of the line yy – copy a line p – paste d – delete a line x – cut a character :q – quit :wq – write & quit :q! – quit without saving /word – search for ‘word’ in the document : – grep integration in Vim (allows to search in multiple files)Find other very usefull commands here, or a full cheatsheet here.
Example: 192.168.1.204
Broadcast Address: Sending data here reaches ALL devices on the network (useful for discovery attacks).
Or in hex
c0.a8.01.cc = 192.168.1.204
So a full IP address is made up by 8x4 bits(32-bits), where they are seperated by a dot after every 8 bits meaning there are 4 groups which is also called "octets".
Since an octet consists of 8 bits and there are 4 octets, a valid IP address can only be a number between 0 and 255, meaning it can be 256 different numbers:
(0-255).(0-255).(0-255).(0-255)
This makes the IP pool to have 2^32 = 4,294,967,296 different IP addresses that can be assigned.
When a device wants to connect outside the network, it communicates through the default gateway (the router), typically 192.168.1.1.
Notes
If there is a 255, then the corresponding octet in the IP address will stay the same, but if the number is 0, then that octet can anything in between 0-255. Example:
Subnet mask = 255.255.255.0
IP address = 192.168.1.204
The first 3 octets of the IP address 192.168.1.* will stay the same where the last octet "*" in our case is 204, which in fact is valid since the number can be anything in between 0-255
So the octets that ne is called the "Network portion" where the octet on a subnet mask zero is called the "Host".
IP = 9.1.4.0
Subnet mask = 255.255.255.0
= 256 other networks
The Class A network became a Classless network (when you cut up a network using a different subnet mask). Nowadays, we mainly do classles networks to take ad of the IP addresses we need to use.
So in other words, big and massi can become into a smaller network.
So if the IP is known but the MAC adress is not, a request is broadcasted to every device on the network in order to match an IP address to its corresponding MAC address. This record is then maintained and saved to a table called ARP cache.
An ARP request contains the following information:
1. The senders IP address.
2. The senders MAC adress.
3. The IP address we want to learn the MAC address for.
arp-scan -l -I <interface>> arp-scan is a tool that can be used to scan for IP and MAC addresses on a local network. It can be installed with the command: sudo apt install arp-scan
> sudo arp-scan -I eth0 -l will send ARP queries for all valid IP addresses on the eth0 interface.
If we have the IP and MAC address , a manual thus static record can be made. This is done with the command: arp -s <IP_Address> <MAC_Address>
See all ARP entries with the command: arp -a
Flushing an ARP cache
This can be made with the following command: arp -s -s neigh flush all
This command will delete every dynamic entry there is. The static ones will not be deleted since we added them manually. To remove the static entries run: arp -d <IP_Address>
<details>
<summary>ARP Spoofing with Bettercap</summary>
</details>
~ and .bak and .swpcurl | md5sum curl -v The -v switch enables mode, which will output the headers{{config}} in the url. If it works, try {{ get_user_file("/etc/passwd") }}.htaccess file for apache ser.curl -IL When successfully finding a framework using on of the methods, Framework Stacking can be used afterwards where you check the framework documentation for potential admin portals etc.
What are wordlists?
Wordlists are just text files that contain a long list of commonly used words; they can cover many different use cases. For example, a password wordlist would include the most frequently used passwords, whereas we're looking for content in our case, so we'd require a list containing the most commonly used directory and file names.
Most common Automation tools ffuf, dirb and gobuster.
Example use for all three tools:
Find many more operators here.
Wappalyzer
Wappalyzer is an online tool and browser extension that helps identify what technologies a website uses, such as frameworks, Content Management Systems (CMS), payment processors and much more, and it can even find numbers as well. Read more here.
Wayback Machine
The Wayback Machine is a historical archive of websites that dates back to the late 90s. You can search a domain name, and it will show you all the times the service scraped the web page and saved the contents. This service can help uncover old pages that may still be active on the current website. Find the website here.
Email Har
Email har is the process of gathering email addresses from a website. This can be done manually by searching for email addresses in the source code of a website, or by using a tools such as Hunter.io and Phonebook. In order to the email addresses, you can use EmailHippo.
SSL/TLS Certificates
When a Certificate Authority (CA) issues an SSL/TLS certificate, it logs it in public Certificate Transparency (CT) logs. These logs can be searched for current and historical certificates on sites like crt.sh .
Search Engines
To search for subdomains of a domain: -site:www.domain.com site:*.domain.com
DNS Bruteforce
Bruteforce DNS (Domain Name System) enumeration is the method of trying tens, hundreds, thousands or e of different possible subdomains from a pre-defined list of commonly used subdomains. For this method, the tool DNSrecon, Sublist3r or Turbolist3r can be used. A more modern but slower alternative is Amass.
It is usually also a good idea to probe for HTTP and HTTPS services on the discovered subdomains to filter out any false positives. This can be done with the tool httprobe.
Hosts
Some subdomains aren't always hosted in publically accessible DNS results, such as de of a web application or administration portals. Instead, the DNS record could be kept on a private DNS server or recorded on the de's machines in their /etc/hosts file (or c:\windows\system32\drivers\etc\hosts file for Windows users) which maps domain names to IP addresses.
Because web servers can host multiple websites from one server when a website is requested from a client, the ser which website the client wants from the Host header. We can utilise this host header by making changes to it and monitoring the response to see if we' a new website.
Bruteforce by using the following command: ffuf -w /usr/share/wordlists/SecLists/Discovery/DNS/namelist.txt -H "Host: {domain}" -u -fs {size}
If an attacker is able to successfully pass input that is interpreted correctly, they would be able to do the following:
* Access, Modify and Delete information in a database when this input is passed into database queries. This would mean that an attacker can steal sensiti such as personal details and credentials.
* Execute Arbitrary system commands on a server that would allow an attacker to gain access to users’ systems. This would enable them to steal sensitive data and carry out more attacks against infrastructure linked to the server on which the command is executed.
Inferential SQLi (Blind SQLi)
Inferential SQLi is also known as blind SQL injection. As the name suggests, the itself is not directly present in the application but can be inferred from the behaviour of the application. There are two types of inferential SQLi attacks being:
* Boolean-based SQLi - This type of SQL injection relies on sending SQL queries to the database which e to either TRUE or FALSE. Depending on the result, the content within the HTTP response will change, or remain the same.
* Time-based SQLi - This type of SQL injection relies on sending SQL queries to the database which cause a time delay in the response. The time delay is used to infer if the result of the query is TRUE or FALSE.
See much more database and SQLi related information here.
'' OR 1=1 --'' OR 1=1 --1' OR 1=1 --1' OR 1=1#1' OR 1=1--1' OR 1=1;--1" or "1"="1"-- -A command injection is also known as a "Remote Code Execution" (RCE) because an attacker can trick the application into executing a series of payloads that they provide, without direct access to the machine itself (i.e. an interacti). The webserver will process this code and execute it under the pri and access controls of the user who is running that application.
Example of a code in PHP:
Example of a code in Python (Flask):
Command Injection can be detected in mostly one of two ways:
| Method | Description |
|:---:|---|
| Blind | This type of injection is where there is no direct output from the application when testing payloads. You will have to in the beha of the application to determine whether or not your payload was successful. |
| | This type of injection is where there is direct feedback from the application once you ha a payload. For example, running the whoami command to see what user the application is running under. The web application will output the username on the page directly. |
Detecting Blind Command Injection:
Use time-delay payloads like ping or sleep to test for injection by observing response delays. Another method is redirecting output using > (e.g., whoami > file) and then reading the file with cat.
The curl command is a great way to test for command injection. This is because you are able to use curl to deliver data to and from an application in your payload.
Detecting Command Injection:
This is easier to detect since the output of commands like ping or whoami is displayed directly on the web application.
;, & and && will combine two (or more) system commands and execute them botUseful payloads for command injection (linux):
| Payload | Description |
|:---:|:---:|
| whoami | See what user the application is running under. |
| ls | List the contents of the current directory. You may be able to find files such as configuration files, en files (tokens and application keys), and many more things. |
| ping | This command will invoke the application to hang. This will be useful in testing an application for blind command injection. |
| sleep | This is another useful payload in testing an application for blind command injection, where the machine does not have ping installed. |
| nc | Netcat can be used to spawn a reverse shell onto the application. You can use this foothold to na around the target machine for other services, files, or potential means of escalating pri. |
Useful payloads for command injection (windows):
| Payload | Description |
|:---:|:---:|
| whoami | See what user the application is running under. |
| dir | List the contents of the current directory. You may be able to find files such as configuration files, en files (tokens and application keys), and many more things. |
| ping | This command will invoke the application to hang. This will be useful in testing an application for blind command injection. |
| timeout | This command will also invoke the application to hang. It is also useful for testing an application for blind command injection if the ping command is not installed. |
Commands that quickly can be tested:
To test for a security misconfiguration in Python, we can use the os module to execute commands:
When found cat /etc/os-release can be used to find the OS and other useful information.
A useful tool in Windows we can use to gain RCE is certutil.exe (certutil.exe -urlcache -f <url> <filename>). This command is a nati CLI program installed as part of Certificate Services. It's handy in engagements because it is a binary signed by Microsoft and allows us to make HTTP/s connections. In our scenario, we can use it to make an HTTP request to download a file from a web server that we control to confirm that the command was executed.
See this cheatsheet for more.
#### functions
In PHP, many functions interact with the operating system to execute commands ; these include:
* Exec
* Passthru
* System
Snippet for a code that only accept and process numbers between 0-9 as input:
#### Input sanitisation
Sanitising any input from a user that an application uses is a great way to prevent command injection. This is a process of specifying the formats or types of data that a user can submit. For example, an input field that only accepts numerical data or removes any special characters such as >, & and /.
Read more about the function filter_input() here.
#### Bypassing filters
Applications will employ numerous techniques in filtering and sanitising data that is taken from a user's input. These filters will restrict you to specific payloads; however, we can abuse the logic behind an application to bypass these filters. For example, an application may strip out quotation marks; we can instead use the hexadecimal value of this to achieve the same result.
When executed, although the data given will be in a different format than what is expected, it can still be interpreted and will have the same result.
Common Payloads:
Windows Examples:
Testing Methods:
1. URL parameters: file=../../../etc/passwd
2. POST data: In form fields
3. HTTP headers: User-Agent, Cookie
4. File upload paths
Files to Target:
/etc/passwd, /etc/shadow, /proc/C:\windows\system32\drivers\etc\hosts, C:\boot.iniweb.config, config.php, .envExample command:
Options:
-w: Specifies the wordlist path.-X: Sets the request method (POST in this case).-d: Defines form data with FUZZ placeholder for testing usernames.-H: Adds headers (e.g., Content-Type).-u: URL to send the request.-mr: Looks for specific response text to confirm a valid username.Brute force attacks try common passwords against usernames. After successful username enumeration, you can use the valid usernames for brute-forcing passwords.
Example command:
Options:
-w: Specifies multiple wordlists (e.g., W1 for usernames, W2 for passwords).-X: Sets the request method (POST here).-d: Defines form data with W1 for username and W2 for password.-H: Adds headers (e.g., Content-Type).-fc: Filters responses by excluding status code 200, indicating a failed login attempt.This can be seen here:
Because the above PHP code example uses three equals signs (===), it's looking for an exact match on the string, including the same letter casing. The code presents a logic flaw because an unauthenticated user requesting /adMin will not ha pri checked and have the page displayed to them, totally bypassing the authentication checks.
Example:
A login process: that goes like step 1, 2, 3, 4 but the hacker make it go like 1, 4 which grants the hacker access to another users account.
Case:
Reset another users password and get the link for the reset process to your account. The design flaw here is that you can send a reset password request to support by passing a users name, and then entering your own email to get the link. This can be done by the following command:
curl '<url>/reset?email=robert%40acmeitsupport.thm' -H 'Content-Type: application/x-www-form-urlencoded' -d 'username=robert&email='
The contents of some cookies can be in plain text, and it is obvious what they do. Take, for example, if these were the cookie set after a successful login:
Using this logic, if we were to change the contents of the cookies and make a request we'll be able to change our pri.
For this, curl can be used by using: curl -H "Cookie: logged_in=true; admin=true" <ip_address>/cookie-test
Hashed cookies
Sometimes cookie can look like a long string of random characters; these are called hashes which are an irre representation of the original text. Here are some examples that you may come across:
| Original String | Hash Method | Output |
|:---:|:---:|---|
| 1 | md5 | c4ca4238a0b923820dcc509a6f75849b |
| 1 | sha-256 | 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b |
| 1 | sha-512 | 4dff4ea340f0a823f15d3f4f01ab62eae0e5da579ccb851f8db9dfe84c58b2b37b89903a740e1ee172da793a6e79d560e5f7f9bd058a12a280433ed6fa46510a |
| 1 | sha1 | 356a192b7913b04c54574d18c28d46e6395428ab |
You can see from the abo that the hash output from the same input string can significantly differ depending on the hash method in use. E the hash is irre, the same output is produced every time
Encoded cookies
Encoding is similar to hashing in that it creates what would seem to be a random string of text, but in fact, the encoding is re
Take the below data as an example which is set by the web server upon logging in:Set-Cookie: session=eyJpZCI6MSwiYWRtaW4iOmZhbHNlfQ==; Max-Age=3600; Path=/
This string base64 decoded has the value of {"id":1,"admin": false} we can then encode this back to base64 encoded again but instead setting the admin value to true, which now gives us admin access.
This type of can occur when a web ser user-supplied input to retrie (files, data, documents), too much trust has been placed on the input data, and it is not on the ser to confirm the requested object belongs to the user requesting it.
An example of this:
Imagine you've just signed up for an online service, and you want to change your profile information. The link you click on goes to , and you can see your information.
Curiosity gets the better of you, and you try changing the user_id value to 420 instead (), and to your surprise, you can now see another user's information. You've now discovered an IDOR !
For example, if a user wants to access and display their C the web application, the request may look as follows, , where the file is the parameter and the userCV.pdf, is the required file to access.
!LFI CV
File inclusion are commonly found and exploited in programming languages for web applications, such as PHP that are poorly written and implemented. The main issue of these is the input , in which the user inputs are not sanitized or , and the user controls them. When the input is not , the user can pass any input to the function, causing the .
If the attacker somehow can write to the server such as /tmp directory, then it is possible to gain remote command execution RCE. However, it won't be effective if file inclusion is found with no access to sensitive data and no writing ability to the server.
Also known as Directory tra, a web security allows an attacker to read operating system resources, such as local files on the ser an application. The attacker exploits this by manipulating and abusing the web application's URL to locate and access files or directories stored outside the application's root directory.
An example of this can be seen by running this command on a website with this :
The result would look like this:
!LFI Path
Another code example in PHP:
Similarly, if the web application runs on a Windows server, the attacker needs to provide Windows paths
You can find a list of common OS files here
Most of the time in CTF's the path you are looking for would be: ../../../../etc/passwd
.php at the end of your search, then this tells us that the de specifies the file type to pass to the include function. To bypass this scenario, we can use the NULL BYTE, which is %00.Using null bytes is an injection technique where URL-encoded representation such as %00 or 0x00 in hex with user-supplied data to terminate strings. You could think of it as trying to trick the web app into disregarding whate after the Null Byte.: /etc/passwd%00
NOTE: the %00 trick is fixed and not working with PHP 5.3.4 and above.
/etc/passwd/.....//....//....//....//....//etc/passwd ../ it finds and doesn't do another pass, leaving: ../../../../etc/passwdlanguages/../../../../../etc/passwd include function. One requirement for RFI is that the allow_url_fopen option needs to be on. The risk of RFI is higher than LFI since RFI allow an attacker to gain Remote Command Execution (RCE) on the server. Other consequences of a successful RFI attack include:
* Sensiti Disclosure
* Cross-site Scripting (XSS)
* Denial of Service (DoS)
An external server must communicate with the application server for a successful RFI attack where the attacker hosts malicious files on their server. Then the malicious file is injected into the include function via HTTP requests, and the content of the malicious file executes on the application server.
!RFI
How to
1. Create a file somewhere on your local computer. ex "cmd.txt"
2. Open the file and write some code inside it
3. Now create a webser python by running: python3 http.server <port> in the same path of the file.
4. Now open the browser and enter the http address where you want the attack to direct. This could look like this:
1. Keep system and services, including web application frameworks, updated with the latest .
2. Turn off PHP errors to avoid leaking the path of the application and other potentially re information.
3. A Web Application Firewall (WAF) is a good option to help mitigate web application attacks.
4. Disable some PHP features that cause file inclusion if your web app doesn't need them, such as allow_url_fopen on and allow_url_include.
5. Carefully analyze the web application and allow only protocols and PHP wrappers that are in need.
6. Ne user input, and make sure to implement proper input against file inclusion.
7. Implement whitelisting for file names and locations as well as blacklisting.
Filters can be used by using php://filter. For example, to base64 encode a file, you can use: php://filter/convert.base64-encode/resource=index.php
How CSRF Works:
1. User logs into site (bank.com)
2. User malicious site (evil.com)
3. Malicious site triggers request to bank.com using user's session
4. Bank.com processes request as if user intended it
Example Attack:
Detection:
Pre:
Cross-site scripting are extremely common
This is when an attack payload is executed by manipulating the DOM (Document Object Model) in the target's browser. This type uses the client-side code instead of ser code.
Exploiting the DOM
DOM Based XSS is where the Ja execution happens directly in the browser without any new pages being loaded or data submitted to backend code. Execution occurs when the website Ja code acts on input or user interaction.
Example Scenario:
The website's Ja gets the contents from the window.location.hash parameter and then writes that onto the page in the currently being section. The contents of the hash aren't checked for malicious code, allowing an attacker to inject Ja of their choosing onto the webpage.
Potential Impact:
Crafted links could be sent to potential , redirecting them to another website or steal content from the page or the user's session.
How to test for Dom Based XSS:
DOM Based XSS can be challenging to test for and requires a certain amount of knowledge of Ja to read the source code. You'd need to look for parts of the code that access certain that an attacker can ha over, such as "window.location.x" parameters.
When you' those bits of code, you'd then need to see how they are handled and whether the are e to the web page's DOM or passed to unsafe Ja methods such as eval()
Or in other words, reflected XSS happens when user-supplied data in an HTTP request is included in the webpage source without any .
Example Scenario:
A website where if you enter incorrect input, an error message is displayed. The content of the error message gets taken from the error parameter in the query string and is built directly into the page source.
How to test for Reflected XSS
You'll need to test every possible point of entry; these include:
* Parameters in the URL Query String
* URL File Path
* Sometimes HTTP Headers (although unlikely exploitable in practice)
A small test to see if a reflected XSS is possible is to enter a single quote (') into the input field and see if the page breaks or shows an error message. If it does, then it's likely exploitable.
Another way to test for reflected XSS is to enter the following payload into the input field:
If the page shows an alert box saying "exploitable", then it's likely exploitable.
Example Scenario:
A blog website that allows users to post comments. Unfortunately, these comments aren't checked for whether they contain Ja or filter out any malicious code. If we now post a comment containing Ja, this will be stored in the database, and every other user now the article will have the Ja run in their browser.
How to test for Stored XSS:
You'll need to test every possible point of entry where it seems data is stored and then shown back in areas that other users ha to; a small example of these could be:
* Comments on a blog
* User profile information
* Website Listings
Example Scenario:
A website has a contact form where you can message a member of staff. The message content doesn't get checked for any malicious code, which allows the attacker to enter anything they wish. These messages then get turned into support tickets which staff view on a private web portal.
Potential Impact:
Using the correct payload, the attacker's Ja could make calls back to an attacker's website, re the staff portal URL, the staff member's cookies, and even the contents of the portal page that is being . Now the attacker could potentially hijack the staff member's session and ha to the private portal.
How to test for Blind XSS:
When testing for Blind XSS , you need to ensure your payload has a call back (usually an HTTP request). This way, you know if and when your code is being executed.
A popular tool for Blind XSS attacks is xsshunter. Although it's possible to make your own tool in Ja, this tool will automatically capture cookies, URLs, page contents and more.
The intention is what you wish the Ja to actually do, and the modification is the changes to the code we need to make it execute as every scenario is different.
Session Stealing:
Details of a user's session, such as login tokens, are often kept in cookies on the targets machine. The below Ja takes the target's cookie, base64 encodes the cookie to ensure successful transmission and then posts it to a website under the hacker's control to be logged. Once the hacker has these cookies, they can take over the target's session and be logged as that user.
Key Logger:
The below code acts as a key logger. This means anything you type on the webpage will be forwarded to a website under the hacker's control. This could be very damaging if the website the payload was installed on accepted user logins or credit card details.
Business Logic:
This payload is a lot more specific than the abo. This would be about calling a particular network resource or a Ja function. For example, imagine a Ja function for changing the user's email address called user.changeEmail(). Your payload could look like this:
This command will print "BERKAN_WAS_HERE" on the screen.
What's the impact?
A successful SSRF attack can result in any of the following:
* Access to unauthorised areas.
* Access to customer/organisational data.
* Ability to Scale to internal networks.
* Reveal authentication tokens/credentials.
And then wait for the server to make a request to the attacker-controlled server.
&x= can also be used in some cases to manipulate paths., but attackers can evade this control by creating subdomains on their own domain, like , thus gaining control o HTTP requests..Example of SSTI in Python Flask
In the above code, the render_template_string function is used to render the template. If the user input is not sanitized, an attacker can inject template code to execute arbitrary commands on the server.
For example, if the attacker sends the following request: , the server will render the template as <h1>Welcome to the profile of 49!</h1>. This shows that the server is executing the code provided by the attacker.
${{<%%'"}}%. To manually fuzz all of these characters, they can be sent one by one following each other.<details>
<summary>Manual Fuzzing example</summary> <br>
One of these may yield an error message or a different response, indicating that the application is to SSTI.
</details>
![SSTI
<details>
<summary>Exploitation POC for Jinja2</summary> <br>
Python allows us to call the current class instance with <code>.__class__</code>, we can call this on an empty string:
Classes in Python have an attribute called <code>.\_\_mro\_\_</code> that allows us to climb up the inherited object tree:
Since we want the root object, we can access the second property (first index):
Objects in Python have a method called <code>.\_\_subclassess\_\_</code> that allows us to climb down the object tree:
Now we need to find an object that allows us to run shell commands. Example: The position in the list is 400 (index 401):
The abo essentially calls the subprocess.Popen method, now all we have to do is invoke it (use the code above for the syntax)
</details>
<details>
<summary>Secure Methods</summary>
Most template engines will have a feature that allows you to pass input in as data, rather that concatenating input into the template.
</details>
<details>
<summary>Sanitization</summary>
Creating a whitelist character set for user input can help prevent SSTI . This can be done by checking the input against a list of allowed characters using a regular expression.
</details>
<!--#exec cmd="ls" --><!--#echo var="DATE_LOCAL" --><!--#exec cmd="cat /etc/passwd" -->Use Cases:
The file type is indicated in the contents of the file with a file signature - a magic number
* Hex string at a specific offset
* Eg PNG files: 89 50 4e 47 (last three hex is PNG in ASCII)
* Tool: file
pngcheck
A command-line tool for "checking" a PNG image file. Especially good for checksums.
<details>
<summary>Combining two images</summary>
</details>
Additional information about a file in addition to the content itself
* General: File name, extension, size, time of origin, permissions
* Specific: GPS data in images, number of frames in GIF, CPU architecture in executables, etc.
Why analyze metadata?
* Can store important info - maybe even info that should have been hidden
* In some cases even more important than content - eg with encrypted HTTPS traffic
* Tool: exiftool
Log Analysis
Log files are a record of events that happen on a system. They are used to record e from user activity to system events. Log files are used to track and record the acti of users, processes, and applications on a system.
In order to effectively analyze log files and identify any suspicious activity, it is important to understand the structure of the log files and the type of information they contain. See Log Analysis for more.
PDF Analysis
We can try to read the metadata using the program pdfinfo. Pdfinfo displays metadata related to a PDF file, such as title, subject, author, creator, and creation date. If you don’t have pdfinfo installed, you can install it using: sudo apt install poppler-utils
If the PDF file is password protected, another tool named pdfcrack can be used with a wordlist in order to bruteforce the password.
Example: pdfcrack -q -w /usr/share/wordlists/rockyou.txt encrypted.pdf
Geographical Coordinates
Longitude Latitude
Can be written as:
Typical structure
* Signature file - magic number
Header - typical info to be used to understand the content (metadata)
* Possibly meta data
* Data
* Trailer that completes the file
The format is precisely defined in a specification doc - often publicly a
* Corrupted files: compare file with specification, correct differences with hex editor
* Unknown file types: search for tracks from a file format
Common Tools:
Analysis Techniques:
What to Look For:
File Carving
File carving: extract files based on the file format
* Look for file signatures, headers, trailers, etc.
* Originally used in connection with. extraction of files from disk images and memory dumps
* Useful for extracting files stored in other files in stego challenges
File carving tools:
* binwalk
* foremost
* dd (manual extraction)
* dd if = input.png or = output.txt bs = 1 skip = 1000 count = 32
Tools Steghide = JPEG(primarily), BMP, WAV and AU Zsteg = PNG(primarily), BMP
Useful commands: stegsnow -C -m <message> -p <password> <inputfile> <outputfile> compress a message in a text file and save it to a new filestegsnow -C -p <password> <inputfile> <outputfile> uncompress a message in a text file and save it to a new file
Install steghide with sudo apt install steghide
Useful commands:
> Password is optional, if you don’t provide a password it will ask you to enter one.
Example:
Embed a zip file into a jpg file steghide embed -cf original.jpg -ef test.zip
Installation
And then run it with
After installing stegseek here, you can use it to crack a password protected steghide file with the following command:
Installation:
Useful commands: stego filename - Simple stego scan stego -meta filename - Check file for metadata information stego -steghide filename - Check for StegHide hidden info. stego -extractLSB filename - Extract a specific LSB RGB from the image.
Useful commands: strings file displays printable strings in the given file strings -el file displays printable strings in the given file in little-endian format
Useful commands: exiftool file shows the metadata of the given file exiftool -Comment="something" file to add a comment to the metadata of the file
Useful commands: exiv2 file shows the metadata of the given file
Useful commands: binwalk <filepath> Displays the embedded data in the given file binwalk -e <filepath> Displays and extracts the data from the given file
foremost is another file carving tool like binwalk, and can be installed with sudo apt-get install foremost.Useful commands:
Search for all file types in the gi file foremost image.png
Search for a selection of file types in the gi file (-i image.dd) foremost -t doc,jpg,pdf,xls -i image.dd
Useful commands: zsteg file Runs a simple scan on the given file zsteg -a file Runs all the methods on the given file zsteg -E file Extracts data from the gi (example : zsteg -E b4,bgr,msb,xy
name.png) zsteg -l 0 file Limits the bytes checked to 0
Install with sudo apt install zbar-tools
Useful commands: zbarimg <filename>
Alternatively, you can use a online tool like zxing to decode QR codes.
stegolsb which can hide data and files in wa and can also extract data from wa.Useful commands: python3 WavSteg.py -r -i soundfile -o outputfile extracts data from a wa file and
outputs the data into a new file
Use an online tool like Databorder Morse or Morse Code World if the wav file contains morse code.
Useful commands:
To embed the message hidden.txt into the monkey.jpg image: outguess -k "my secret pass phrase" -d hidden.txt monkey.jpg out.jpg
Retrieve the hidden message from the image: outguess -k "my secret pass phrase" -r out.jpg message.txt
Options: -k <key> key -d <name> filename of dataset -p <param> parameter passed to destination data handler -r retrie from data
Layer → Add Spectrogram should work
<details>
<summary>Making a spectrogram</summary>
1. Create a small white text on a black background
2. Convert the text to audio using this imagetoaudio tool
3. Open Audacity and import the audio file.
4. Select another track and import the audio file again
5. Now merge the two tracks by selecting the first track and then the second track and then Tracks->Mix->Mix and Render
6. Now select the mixed track and then Tracks->Add New->Spectrogram
Now you should see the hidden text in the spectrogram
</details>
What is data?
* data: non-permanent data, disappears when the power goes out
* Typically the contents of main memory RAM
* "Live box forensics"
* Analysis takes place on a memory dump - provides a snapshot
Data that can be found in memory
* Running processes and services
* Open files
* Network connections
* Run commands
* Passwords, keys
* Unencrypted data that is encrypted on disk but must be used in decrypted mode in memory
* Stateless malware - malware that lives only in memory
* E like a basic screenshot or the user's clipboard
A tool used for analyzing memory dumps is 3.
Useful commands:
* vol.py -f <memory dump> imageinfo - Get information about the memory dump
* vol.py -f <file> windows.filescan.FileScan - List all files in the memory dump
* vol.py -f <file> windows.pslist.PsList - List all processes in the memory dump
* vol.py -f <file> windows.dumpfiles.DumpFiles -- <address> - Dump a file from the memory dump
* --pid PID Process ID to include (all other processes are excluded)
* -- Dump a single _FILE_OBJECT at this address
* --physaddr PHYSADDR Dump a single _FILE_OBJECT at this physical address
Remember to append the --output-dir <directory> flag to save the output to a directory. Or simply redirect the output to a file with > <filename>. I' more about 3 here.
Common Tools:
FTK Imager (Windows/GUI):
Image Formats:
Best Practices:
Examples of tools in The Sleuth Kit:
Prerequisites:
Essential Tools: GDB, radare2, Ghidra, pwntools, ROPgadget
Practice Safely: Use dedicated platforms like picoCTF, pwnable.tw, or local VMs. Never test on systems you don't own.
Register Naming Con:
General Purpose Registers:
| 64-bit | 32-bit | 16-bit | 8-bit | Purpose |
|--------|--------|--------|-------|---------|
| RAX | EAX | AX | AL | Accumulator (return , arithmetic) |
| RBX | EBX | BX | BL | Base register (pointer to data) |
| RCX | ECX | CX | CL | Counter (loop operations) |
| RDX | EDX | DX | DL | Data register (I/O operations) |
| RSI | ESI | SI | SIL | Source index (string operations) |
| RDI | EDI | DI | DIL | Destination index (string operations) |
| RBP | EBP | BP | - | Base pointer (stack frame) |
| RSP | ESP | SP | - | Stack pointer (top of stack) |
| R8-R15 | R8D-R15D | R8W-R15W | R8B-R15B | Additional 64-bit registers |
Special Registers:
Example Usage:
Stack Operations:
Stack Frame Structure:
Stack in Function Calls:
1. Arguments pushed onto stack
2. CALL instruction pushes return address
3. Function prologue saves old RBP
4. Local allocated
5. Function epilogue restores RBP
6. RET instruction returns to sa
Security Implications:
If the output contains Canary found and NX enabled, then a stack o is possible. See more about this command here.
Simple Steps:
1. Fill buffer with your shellcode (machine code)
2. O to o return address
3. Make return address point to your shellcode
4. When function ends, it runs your code
Memory Layout:
What shellcode does:
Why it works:
The Idea:
How it works:
1. Find the "win" function address (like 0x401234)
2. O the buffer
3. Replace return address with win function address
4. Program jumps to win function and you get the flag
Memory Layout:
Why it's easier:
Linux 64-bit (most common):
Example - calling system("/bin/sh"):
Why this matters for exploits:
32-bit is different:
Purpose:
What it does:
GOT vs PLT:
GOT O Attack:
1. Find GOT entry for target function
2. O with address of controlled function
3. When target function called, redirects to attacker code
Simple Example:
1. Program calls printf("Hello")
2. Program looks in GOT: "printf is at address 0x123456"
3. You change GOT: "printf is at address 0x789abc" (where system() lives)
4. Program calls system("Hello") instead of printf("Hello")
Finding GOT entries:
Common Targets:
Why this works:
Quick note:
* If some C code contains the function gets() or strcpy(), it is to a buffer o attack.
* An important part of the memory we can o is the instruction pointer (IP/return address), which is called the eip on 32-bit machines, and rip on 64-bit machines. The IP points to the next instruction to be executed, so if we redirect the eip in a binary to point to a different location, we can execute arbitrary code.
* The top of the stack is pointed to by the SP (or stack pointer) which is called esp in 32-bit machines.
The Setup:
The Attack:
Memory Layout:
Why it works:
By carefully selecting and chaining together gadgets that end with a return instruction, attackers can construct a "ROP chain" that allows them to execute their own code on the target system. This technique can be used to bypass security measures such as Data Execution Pre (DEP) and Address Space Layout Randomization (ASLR).
checksec. I' about the tool here.What's the heap?
Common Mistakes Programs Make:
Simple Example:
Why it's hard:
printf or scanf functions without properly or sanitizing the input. This can allow an attacker to execute arbitrary code or read sensitive data from the program's memory. Read more about the functions here.The format specifiers are the following:
| Format Specifier | Description |
|---|---|
| %c | Character |
| %d | Signed decimal integer |
| %e | Scientific notation |
| %f | Decimal floating point |
| %g | Use the shortest representation: %e or %f |
| %i | Signed decimal integer |
| %o | Unsigned octal |
| %s | String of characters |
| %u | Unsigned decimal integer |
| %x | Unsigned hexadecimal integer |
| %X | Unsigned hexadecimal integer (uppercase) |
Its also possible to brute force the stack for .
Concept:
Common Technique:
1. Find PLT entry for desired function
2. Set up arguments in registers/stack
3. Return to PLT entry
Example:
PLT Call:
Assembly is the low-le language that directly corresponds to machine code instructions.
Common Instructions:
Intel vs AT&T Syntax:
Useful for:
strace is a debugging utility in Linux used to monitor the system calls used by a program and all the signals it receives.ltrace is a debugging utility in Linux used to display the calls a user space application makes to shared libraries. It traces the library calls made by a process and the signals received by the process.
inside' another program while it executes -- or what another program was doing at the moment it crashed.radare2
Radare2 is an open-source framework that can perform disassembly, debugging, analysis, comparing data and manipulation of binary files. Ghidra
Ghidra is a software reverse engineering (SRE) framework created and maintained by the National Security Agency (NSA). It is a free and open-source software reverse engineering tool released under the Apache License 2.0.Ghidra GUI
Call Graphs
Cytoscape is a tool for network analysis and that can be used to see call graphs.Useful functions:
Layout -> Grid View = Show a grid view of the nodes.
Pathlinker = Find paths between nodes. Needs a source and a target node. K = number of paths to find. Is mostly one in CTF situations. Decompilers
A decompiler is a computer program that takes an executable file as input, and attempts to create a high level code (like C/C++, Java). Jar files
A jar file is a Ja file that can contain multiple files and folders. Jar files are mainly used for archiving, compression and decompression. Jar files are similar to zip files, but jar files can ha attributes that are required for a Ja to run.To decompile a jar file, procyon can be used. For online DogBolt is a good option.
.NET Decompilers
* dotPeek - Free .NET decompiler and assembly browser
* ILSpy - .NET Decompiler with support for PDB generation, ReadyToRun, Metadata (&more) - cross-platform!Cryptography
Cryptography is the foundation of modern security, protecting data through mathematical algorithms. Understanding crypto principles is essential for both securing systems and attacking weak implementations.Learning Path:
1. Basics: Hashing, symmetric encryption
2. Classical: Caesar, Vigenère, substitution ciphers
3. Modern: AES, RSA, elliptic curves
4. Applications: TLS/SSL, digital signatures, key exchange
5. Attacks: Weak implementations, side channels, quantum threats
Essential Tools: OpenSSL, hashcat, John the Ripper, CyberChef, cryptographic libraries
Implementation Warning: Ne crypto from scratch in production. Use established, audited libraries.
Generating Keys
To generate a private key we use the following command (8912 creates the key 8912 bits long):
openssl genrsa -aes256 -out private.key 8912To generate a public key we use our pre generated private key:
openssl rsa -in private.key -pubout -out public.keyLets now encrypt a file (plaintext.txt) using our public key:
openssl rsautl -encrypt -pubin -inkey public.key -in plaintext.txt -out encrypted.txtNow, if we use our private key, we can decrypt the file and get the original message:
openssl rsautl -decrypt -inkey private.key -in encrypted.txt -out plaintext.txtCryptographic Methods
Cryptii
Cryptii has multiple decoding tools like base64, Ceaser Cipher, ROT13, Vigenère Cipher and more.Keyboard Shift
Dcode If you see any thing that has the shape of a sentence but it looks like nonsense letters, and notes some shift left or right, it may be a keyboard shift...Bit Shift
Sometimes the letters may be shifted by a stated hint, like a binary bit shift ( x >> 1 ) or ( x << 1 ).Bit Calculator is a good tool to calculate bit shifts. For other bit operations, use the RapidTables tool.
Re Text
Sometimes a "ciphertext" is just as easy as re text. Don't forgot to check under this rock! You can reverse a string in Python like so:"UOYMORFEDIHOTGNIYRTEBTHGIMFTCA.TAHTTERCESASISIHT"[::-1]
XOR
ANY text could be XOR'd. Techniques for this are Trey's code, and XORing the data against the known flag format. Typically it is given in just hex, but once it is decoded into raw binary data, it gives it keeps it's hex form (as in \xde\xad\xbe\xef etc..) Note that you can do easy XOR locally with Python like so (you need pwntools installed):python >>> import pwn; pwn.xor("KEY", "RAW_BINARY_CIPHER")Vigenère Cipher
The Vigenère cipher is a method of encrypting alphabetic text by using a series of interwo ciphers, based on the letters of a keyword. It employs a form of polyalphabetic substitution.The encryption of the original text is done using the Vigenère square or Vigenère table. It is a table of alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar ciphers. At different points in the encryption process, the cipher uses a different alphabet from one of the rows. The alphabet used at each point depends on a repeating keyword.
Caesar Cipher
The Caesar cipher is one of the earliest known and simplest ciphers. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.ROT13
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher which was de in ancient Rome.Substitution Cipher
A substitution cipher is a method of encoding by which units of plaintext are replaced with ciphertext, according to a fixed system; the "units" may be single letters (the most common), pairs of letters, triplets of letters, mixtures of the above, and so forth. The recei the text by performing the inverse substitution.Useful tools for substitution ciphers are Cryptii and Dcode.
Encoding
Encoded data can be decoded immediately, without keys. It's NOT a form of encryption, it just a way of representing data.A very popular encoding is Base64.
The basic idea behind Base64 encoding is to represent binary data using only ASCII characters. To do this, Base64 converts each 3 bytes of binary data into 4 bytes of ASCII text. The 3 bytes of binary data are divided into 4 groups of 6 bits each, which are then represented by a character from a set of 64 characters. The 64 characters used in Base64 are:
ABCDEFGHIJKLMNOPQRSTUtu+/The equals sign (=) is also used as a padding character to ensure that the length of the output is a multiple of 4 characters.
For example, let's say we want to encode the binary data "
0001001100011", which represents the ASCII characters "abc". To encode this data in Base64, we first divide it into 3-byte groups:01100001 01100010 01100011Then we divide each 3-byte group into 4 groups of 6 bits each:
011000 010110 001001 100011Next, we convert each group of 6 bits to its corresponding Base64 character:
Y W J jSo the encoded Base64 string for "
abc" is "YWJj".Encoding a string in the terminal
Decoding a string in the terminal
Encoding/Decoding files
Hashing
Hashing is used for 2 main purposes in Cyber Security. To integrity of data, or for passwords. plaintext ➡️ hash
hash ⛔ plaintext
Doing a lookup in a sorted list of hashes that are not salted is quite fast, much much faster than trying to crack the hash. But in case we have to crack, then its done by hashing a large number of different inputs (often rockyou.txt, these are the possible passwords), potentially adding the salt if there is one and comparing it to the target hash.
Tools like Hashcat and John the Ripper are normally used for this.
Ciphers
Methods for encrypting and decrypting data to protect confidentiality.Classical Ciphers:
Caesar: Shift letters by fixed amount
Vigenère: Use repeating key for shifting
Substitution: Replace each letter with another
Transposition: Rearrange letter positions Modern Ciphers:
AES: Ad Encryption Standard (symmetric)
RSA: Ri (asymmetric)
DES: Data Encryption Standard (obsolete) Examples:
Breaking Ciphers:
Frequency analysis
Known plaintext attacks
Brute force (short keys)
Mathematical weaknesses
Encryption (RSA)
Symetric encryption
plaintext ➡️ 🔑 ➡️ ciphertext
plaintext ⬅️ 🔑 ⬅️ ciphertext
(🔑 shared key)Asymetric encryption
plaintext ➡️ 🔑 ➡️ ciphertext
plaintext ⬅️ 🗝 ⬅️ ciphertext
(🔑 public key, 🗝 private keyPublic key to encrypt, private key to decrypt.
Cracking ecrypted files
If you are using Kali linux or Parrot OS, you should have a binary add on called gpg2john. This binary program allows us to convert the gpg file into a hash string that john the ripper can understand when it comes to brute-forcing the password against a wordlist. How to use it (GPG example):
Then you can use john the ripper to crack the password.
The result should reveal the password if you have used a strong wordlist that contains it.
Windows Exploitation
Acti
Acti is a collection of machines and servers connected inside of domains, that are a collective part of a bigger forest of domains, that make up the Acti network. Other related terms include: Domain controllers, Trusts & Policies, Services, Authentication & Cloud security.
Windows Reverse Shells
If you ha to PowerShell, you can get a Reverse shell by using nishang's In.ps1 script inside of the Shells directory. Be sure to add the function call example to the bottom of your script, so all you need to to do to host it is (on your Attacker machine):and then on the machine:
Also, if you want to have nice up and down arrow key usage within your Windows reverse shell, you can use the utility rlwrap before your netcat listener command.
Samba (SMB)
smbmap tells you permissions and access, which smbclient does not do!smbmap
To try and list shares as the anonymous user (this doesn't always work for some weird reason)
smbmap -H <IP> -u anonymousenum4linux
Another enumeration tool is enum4linux which can be used like this:
enum4linux <ip>smbclient
You can use smbclient to look through files shared with SMB. To list a shares:
smbclient -m SMB2 -N -L //10.10.10.125/> The -L flag specifies that we want to retrieve a list of a shares on the remote host, while -N suppresses the password prompt.
For more, see this page: Samba
Shells and Pri Escalation
Public Exploits
Google
A simple search: openssh 7.2 exploitExploit-DB
MetaSploit
* Running reconnaissance scripts to enumerate remote hosts and compromised targets
* scripts to test the existence of a without actually compromising the target
* Meterpreter, which is a great tool to connect to shells and run commands on the compromised targets
Quick exploit search
Then to use it
Other
We can also utilize online exploit databases to search for , like Exploit DB, Rapid7 DB, or Lab.
TTY Shell
The tty command of terminal basically prints the file name of the terminal connected to standard input. tty is short of teletype, but popularly known as a terminal it allows you to interact with the system by passing on the data (you input) to the system, and displaying the output produced by the systemShell Spawning
python -c 'import pty; pty.spawn("/bin/sh")'
echo os.system('/bin/bash')
/bin/sh -i
perl —e 'exec "/bin/sh";'
perl: exec "/bin/sh";
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')
From within IRB
exec "/bin/sh"
From within vi
:!bash
From within vi
:set shell=/bin/bash:shell
From within nmap
!sh Many of these will also allow you to escape jail shells. The top 3 would be my most successful in general for spawning from the command line.
Reverse Shells
Reverse shells are used to connect back to a listening machine. This is useful when you have a shell on a machine, but you want to connect back to your own machine.A useful website to generate a reverse shell is Re.
Other useful reverse shells can be found in this repo: PayloadAllTheThings.
For PHP, you can take a look at this RS from PentestMonkey: PHP Reverse Shell
Shell stabilization
Impro reverse shells to make them more usable and stable.Common Issues with Basic Shells:
No tab completion
No command history
Can't use Ctrl+C
Limited text editing Python TTY Method:
Other Methods:
Full Stabilization Process:
1. Spawn TTY shell → 2. Set terminal type → 3. Configure stty settings → 4. Resize terminal
Pri Escalation
Check for root password
* Run: id
* Run: sudo -l to list commands that can be run as root
* Check cat /etc/*release for OS
* Locate password folder and crack it using johntheripper
* Remember to look for cron jobs or other running tasks. If they require root, use pspy.
* Or use GTFOBins You can also run:
To download and then execute the script on a target machine to see the files that stand out.
Another option would be to run the following command to find all files with the SUID bit set:
find / -perm -u=s -type f 2>/dev/null fine
find / -user root -perm 4000 -print 2>/dev/null good
find / -user root -perm 4000 -exec ls -ldb {} \; 2>/dev/null better
find / -user root -perm 4000 -exec ls -ldb {} \; 2>/dev/null | grep 'bin' best 2>/dev/null will filter out the errors so that they will not be output to your consoleFind info about the users of the system
Find users on a system
cat /etc/passwd | grep “/bin/bash”Find passwords
cat /etc/passwdIf you don't ha, try this
find / -name shadow* 2>/dev/null | headI' the /etc/passwd format here/Passwd-file.md), in case you want to know more.
Pri Escalation using SUID Binaries
-rwsr-xr-x
“s” = SUID. This means that any user can execute these commands and they will be ran as the original owner.Example
Lets say the
cat command had the 's' in its SUID. Then you would be able to use something like the following command to read a flag:
find /home/berkan/flag1.txt -exec cat {} \;Persistence
#### Using SSH
Create a .ssh folder in the home directory of the user you want to keep a backdoor. Keep in mind that the permissions of the .ssh folder should be 700 and the files withing should be 600.Using exploit suggesters
MetaSploit has a tool called suggester that can be used to find exploits for a specific system. Clean up
After you ha your pri, you should clean up the logs to avoid detection. One tool for this is the clearev command for metasploit. & Threats
A in cybersecurity is defined as a weakness or flaw in the design, implementation or beha of a system or application. An attacker can exploit these weaknesses to gain access to unauthorised information or perform unauthorised actionsThere are arguably five main categories of :
| | Description |
|:---:|:---:|
| Operating System | These types of are found within Operating Systems (OSs) and often result in pri escalation. |
| (Mis)Configuration-based | These types of stem from an incorrectly configured application or service. For example, a website exposing customer details. |
| Weak or Default Credentials | Applications and services that have an element of authentication will come with default credentials when installed. For example, an administrator dashboard may have the username and password of "admin". These are easy to guess by an attacker. |
| Application Logic | These are a result of poorly designed applications. For example, poorly implemented authentication mechanisms that may result in an attacker being able to impersonate a user. |
| Human-Factor | Human-Factor are that le human behaviour. For example, phishing emails are designed to trick humans into believing they are legitimate. |
Social Engineering
Phishing
#### Phishing terms
A BEC (Business Email Compromise) is when an ad gains control of an internal employee's account and then uses the compromised email account to convince other internal employees to perform unauthorized or fraudulent actions.
A typosquatting attack, also known as a URL hijacking, a sting site, or a fake URL, is a type of social engineering where threat actors impersonate legitimate domains for malicious purposes such as fraud or malware spreading.
#### Types of Phishing attacks
Spam
Unsolicited junk emails sent out in bulk to a large number of recipients. The more malicious of Spam is known as MalSpam.
Phishing
Emails sent to a target(s) purporting to be from a trusted entity to lure indi into pro sensiti.
Spear phishing
Takes phishing a step further by targeting a specific indi(s) or organization seeking sensiti.
Whaling
Is similar to spear phishing, but it's targeted specifically to C-Le indi (CEO, CFO, etc.), and the objective is the same.
Smishing
Takes phishing to mobile devices by targeting mobile users with specially crafted text messages.
Is similar to smishing, but instead of using text messages for the social engineering attack, the attacks are based on voice calls.
#### Analyze/identify
1. Open Email
2. See its raw format
3. Analyze the results:
* X-Originating-IP - The IP address of the email was sent from (this is known as an X-header)
* Smtp.mailfrom/header.from - The domain the email was sent from (these headers are within Authentication-Results)
* Reply-To - This is the email address a reply email will be sent to instead of the From email address
In case the mail is encoded using base64, the following command can be used to decrypt the message:
base64 -d <filename> > decoded.txt #### Phishing security
Hyperlinks and IP addresses should be defanged.
Expand shortened links with this tool.
Denial of Service (DoS & DDoS)
Denial of Service attacks aim to make a system, service, or network una by o it with traffic or exploiting .Types of DoS Attacks
DoS (Denial of Service): Single-source attack
DDoS (Distributed Denial of Service): Multiple-source coordinated attack
Application Layer: Targets specific applications (HTTP, DNS)
Network Layer: Floods network infrastructure
Protocol: Exploits protocol weaknesses Common DoS Techniques
#### Network Flooding
#### Application Layer Attacks
#### Amplification Attacks
DNS Amplification: Small query → Large response
NTP Amplification: Exploits NTP monlist command
Memcached Amplification: UDP-based amplification Detection and Mitigation
Rate Limiting: Limit requests per IP/user
Traffic Analysis: Monitor unusual patterns
Blacklisting: Block malicious IPs
Load Balancing: Distribute traffic
CDN: Content delivery networks for protection
Firewalls: Filter malicious traffic Tools for Testing (Educational/Legal Use Only)
Legal Warning: Only test on systems you own or ha permission to test. Unauthorized DoS attacks are illegal.
Misconfigurations
Printer Hacking (IPP)
Enumeration and exploitation tools can be found here.
Printer security cheat sheet can be found here.It allows clients to submit one or more print jobs to the printer or print server, and perform tasks such as querying the status of a printer, obtaining the status of print jobs, or canceling indi print jobs."
Most of them appear to run the CUPS server (which is a simple UNIX printing system).
Running
python pret.py` will start an automatic printer discovery in your local network. Example:
tinyurl.com/m+
Other pro: bit.ly, goo.gl, ow.ly, t.co, tinyurl.com, x.co, s.id, tiny.pl & smarturl.it
Start by starting the mysql service:
Now you can use the following commands to read the database:
Type "source" followed by the filename of the mysql database to specify that you wish to view its database.
You can now view the database using the commands from the previous section.
---
<h3 align="center">
<strong>I hope you found this useful! 🚀</strong>
</h2>
<p align="center">If you think others could benefit, please consider sharing it with your network or giving it a star ⭐ on GitHub - every bit of support helps this project grow and reach more people. And if you’re enjoying the content as much as I am, a little ☕ goes a long way in keeping it fueled!</p>
<p align="center">Thank you for being part of this journey, and happy hacking! </p>
<br>
<p align="center">
<a href=" target="_blank">
<img src=" alt="Buy Me A Coffee" height="50px">
</a>
</p>
---
<di="center">
![Share on LinkedIn]()
![Share on Twitter]()
![Share on Facebook]()
![Share on WhatsApp]()
</div>
开发语言:Python
Star 数:1608
该项目属于CTF思路方向的开源资源,代码结构清晰,适合安全研究人员学习参考。项目围绕A collection of essential and foundational cybersecurity knowledge, thoughtfully organized for easy comprehension.展开,提供了可运行的实现,对理解相关安全机制、工具原理与攻防技术具有较高的研究价值。
从技术实现角度看,此类项目的核心在于对底层原理的深入理解与工程化落地。开发者在研究过程中可以结合官方文档与社区讨论,梳理项目的初始化流程、核心模块职责与数据流转,逐步掌握其中的技术细节与设计思路。
1. 下载源码压缩包,解压到本地环境。
2. 根据项目类型准备对应的运行环境与依赖。
3. 按照 README 中的步骤完成配置与部署。
4. 在隔离的测试环境中运行验证,避免影响生产系统。
本资源来源于开源社区,仅供安全研究、技术学习与合法授权范围内的攻防演练使用,请勿用于任何非法或侵害他人权益的用途。使用本项目产生的一切后果由使用者自行承担。
| 资源标题 | CyberSecurity - A collection of essential and foundational cyberse |
| 所属分类 | CTF思路 |
| 发布作者 | admin |
| 发布时间 | 2026-10-05 23:36:47 |
| 下载权限 | 免费下载 |
| 附件数量 | 2 个下载链接 |
| 浏览次数 | 128 |
| 讨论数量 | 0 |
| 主题状态 | 正常讨论中 |