# Table of Contents - [CTF Handbook](#ctf-handbook) - [What is a CTF - CTF Handbook](#what-is-a-ctf-ctf-handbook) - [Overview - CTF Handbook](#overview-ctf-handbook) - [Overview - CTF Handbook](#overview-ctf-handbook) - [Overview - CTF Handbook](#overview-ctf-handbook) - [Overview - CTF Handbook](#overview-ctf-handbook) - [How to connect to services - CTF Handbook](#how-to-connect-to-services-ctf-handbook) - [Overview - CTF Handbook](#overview-ctf-handbook) - [Getting Started with CTFs - CTF Handbook](#getting-started-with-ctfs-ctf-handbook) - [How do I host a CTF - CTF Handbook](#how-do-i-host-a-ctf-ctf-handbook) - [File Formats - CTF Handbook](#file-formats-ctf-handbook) - [Metadata - CTF Handbook](#metadata-ctf-handbook) - [Wireshark - CTF Handbook](#wireshark-ctf-handbook) - [Stegonagraphy - CTF Handbook](#stegonagraphy-ctf-handbook) - [Disk Imaging - CTF Handbook](#disk-imaging-ctf-handbook) - [Memory Forensics - CTF Handbook](#memory-forensics-ctf-handbook) - [Hex Editors - CTF Handbook](#hex-editors-ctf-handbook) - [Packet Capture - CTF Handbook](#packet-capture-ctf-handbook) - [Hashing Functions - CTF Handbook](#hashing-functions-ctf-handbook) - [XOR - CTF Handbook](#xor-ctf-handbook) - [Caesar Cipher/ROT 13 - CTF Handbook](#caesar-cipher-rot-13-ctf-handbook) - [Substitution Cipher - CTF Handbook](#substitution-cipher-ctf-handbook) - [Vigenere Cipher - CTF Handbook](#vigenere-cipher-ctf-handbook) - [Block Ciphers - CTF Handbook](#block-ciphers-ctf-handbook) - [Command Injection - CTF Handbook](#command-injection-ctf-handbook) - [Stream Ciphers - CTF Handbook](#stream-ciphers-ctf-handbook) - [SQL Injection - CTF Handbook](#sql-injection-ctf-handbook) - [RSA - CTF Handbook](#rsa-ctf-handbook) - [Cross Site Request Forgery - CTF Handbook](#cross-site-request-forgery-ctf-handbook) - [Directory Traversal - CTF Handbook](#directory-traversal-ctf-handbook) - [Server Side Request Forgery - CTF Handbook](#server-side-request-forgery-ctf-handbook) - [Cross Site Scripting (XSS) - CTF Handbook](#cross-site-scripting-xss-ctf-handbook) - [Registers - CTF Handbook](#registers-ctf-handbook) - [Disassemblers - CTF Handbook](#disassemblers-ctf-handbook) - [Assembly/Machine Code - CTF Handbook](#assembly-machine-code-ctf-handbook) - [Global Offset Table (GOT) - CTF Handbook](#global-offset-table-got-ctf-handbook) - [Decompilers - CTF Handbook](#decompilers-ctf-handbook) - [PHP - CTF Handbook](#php-ctf-handbook) - [Debuggers - CTF Handbook](#debuggers-ctf-handbook) - [Calling Conventions - CTF Handbook](#calling-conventions-ctf-handbook) - [The C Programming Language - CTF Handbook](#the-c-programming-language-ctf-handbook) - [Format String Vulnerability - CTF Handbook](#format-string-vulnerability-ctf-handbook) - [What are Buffers - CTF Handbook](#what-are-buffers-ctf-handbook) - [What is Binary Security - CTF Handbook](#what-is-binary-security-ctf-handbook) - [No eXecute (NX) - CTF Handbook](#no-execute-nx-ctf-handbook) - [Return Oriented Programming (ROP) - CTF Handbook](#return-oriented-programming-rop-ctf-handbook) - [The Stack - CTF Handbook](#the-stack-ctf-handbook) - [Address Space Layout Randomization (ASLR) - CTF Handbook](#address-space-layout-randomization-aslr-ctf-handbook) - [Buffer Overflow - CTF Handbook](#buffer-overflow-ctf-handbook) - [Relocation Read-Only (RELRO) - CTF Handbook](#relocation-read-only-relro-ctf-handbook) - [Stack Canaries - CTF Handbook](#stack-canaries-ctf-handbook) - [What is the Heap - CTF Handbook](#what-is-the-heap-ctf-handbook) - [Heap Exploitation - CTF Handbook](#heap-exploitation-ctf-handbook) - [I need a server - CTF Handbook](#i-need-a-server-ctf-handbook) - [Recommended Software - CTF Handbook](#recommended-software-ctf-handbook) --- # CTF Handbook [Skip to content](https://ctf101.org/#capture-the-flag-101) Capture The Flag 101 🚩 ======================= Welcome ------- Welcome to **CTF101**, a site documenting the basics of playing Capture the Flags. This guide was written and maintained by the [OSIRIS Lab](https://osiris.cyber.nyu.edu/) at New York University in collaboration with [CTFd](https://ctfd.io/) . In this handbook you'll learn the basics™ behind the methodologies and techniques needed to succeed in Capture the Flag competitions. Ready? [What is a CTF?](https://ctf101.org/intro/what-is-a-ctf/) Contributions ------------- > Thank you to our incredible contributors. They work hard to keep this project open and available to everyone. This project is open sourced under the MIT Open Source License. For more information, check out the [MIT License](https://tlo.mit.edu/understand-ip/exploring-mit-open-source-license-comprehensive-guide) page. Info If you're interested in contributing to make this site great, please check out our [Contributing](https://github.com/osirislab/ctf101#Contributing) section on Github! Back to top --- # What is a CTF - CTF Handbook [Skip to content](https://ctf101.org/intro/what-is-a-ctf/#what-is-a-ctf) What is a CTF? ============== Capture the Flags, or CTFs, are computer security competitions. Teams of competitors (or just individuals) are pitted against each other in various challenges across multiple security disciplines, competing to earn the most points. Why play CTFs? -------------- Real-world vulnerabilities are featured in challenges, allowing you to flex your programming, problem solving, and teamwork skills! CTFs are often the beginning of one's cyber security career due to their team building nature and competitive aspect. In addition, there isn't a lot of commitment required beyond a weekend. CTFs bring these vulnerabilities right to your machine in small, compartmentalized challenges, fostering collaboration and community building (with friendly competition of course!). If you're looking to meet new people in this space, check out your local [CitySec](https://www.reddit.com/r/netsec/wiki/meetups/citysec/) ! Who can play in a CTF? ---------------------- Participants can work individually or in teams to solve challenges. Typically, an organization would feature multiple members playing for the same team, working together to solve challenges. If you're working alone, we encourage you to do some searching or friendly recruiting to have another mind to bounce ideas off of! Info For information about ongoing CTFs, check out [CTFTime](https://ctftime.org/) . Do I need special tools or computers? ------------------------------------- A terminal environment is essential to experiment and install tools in. Linux and MacOS systems should already have terminal emulators installed natively. If you're on Windows, install Linux with [WSL](https://learn.microsoft.com/en-us/windows/wsl/install) or setup a VM ([virtual machine](https://azure.microsoft.com/en-us/resources/cloud-computing-dictionary/what-is-a-virtual-machine) ). See our [recommended software](https://ctf101.org/faq/recommended-software/) . Info Images like [Kali Linux](https://www.kali.org/get-kali/#kali-platforms) come prebuilt with tools for all your pentesting needs! To learn more about getting a server or connecting to challenges, check out the [FAQ](https://ctf101.org/faq/connecting-to-services/) ! Got the hang of it? Move on to [CTF-basics](https://ctf101.org/intro/ctf-basics/) Back to top --- # Overview - CTF Handbook [Skip to content](https://ctf101.org/forensics/overview/#forensics) Forensics ========= Forensics is the art of recovering the digital trail left on a computer. There are plenty of methods to find data which is seemingly deleted, not stored, or worse, covertly recorded. An important part of forensics is having the right tools, as well as being familiar with using them. Approach forensics challenges with an open mind. It's not uncommon to have obscure CTF challenges hide flags in the darkest of corners! Real World Forentics™️ Unlike CTFs normally portray them, real-world forensics are rarely esoteric. For example, it might have you reassembling the boot partitions of a hard drive to recover it's data and file system. Thus, CTF forensics are normally puzzle, "brain-teaser" problems that aims to introduce a tool or method. The [Forensics Wiki](https://forensics.wiki/) is an extraordinary guide to many of the tools used. Give it a read if you're interested in this category! Back to top --- # Overview - CTF Handbook [Skip to content](https://ctf101.org/web-exploitation/overview/#web-exploitation) Web Exploitation ================ Websites all around the world are programmed using various programming languages. While there are specific vulnerabilities in each programming langrage that the developer should be aware of, there are issues fundamental to the internet that can show up regardless of the chosen language or framework. These vulnerabilities often show up in CTFs as web security challenges where the user needs to exploit a bug to gain some kind of higher level privilege. Web Frameworks As a "prerequisite" to getting into web exploitation, understanding the most common web frameworks is a good way to identify potential targets. Back to top --- # Overview - CTF Handbook [Skip to content](https://ctf101.org/reverse-engineering/overview/#reverse-engineering) Reverse Engineering =================== Reverse Engineering in a CTF is typically the process of taking a compiled (machine code, bytecode) program and converting it back into a more human readable format. Very often the goal of a reverse engineering challenge is to understand the functionality of a given program such that you can identify deeper issues. Back to top --- # Overview - CTF Handbook [Skip to content](https://ctf101.org/cryptography/overview/#cryptography) Cryptography ============ Cryptography is the reason we can use banking apps, transmit sensitive information over the web, and in general protect our privacy. However, a large part of CTFs is breaking widely used encryption schemes which are improperly implemented. The math may seem daunting, but more often than not, a simple understanding of the underlying principles will allow you to find flaws and crack the code. The word “cryptography” technically means the art of writing codes. When it comes to digital forensics, it’s a method you can use to understand how data is constructed for your analysis. Math in Cryptography Most modern cryptography systems rely on one way mathematical algorithms derived from [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic) . It's an ongoing arms race to create and implement better hardware and algorithms. For example, the [implementation of the first RSA algorithm](https://people.csail.mit.edu/rivest/Rsapaper.pdf) is completely reliant on the "difficulty of factoring large numbers". It's a great example of security by design, and modern application developers still use similar derivatives. In August 2024, NIST released the first standards for post-quantum encryption to remediate the quantum-computing threat against legacy systems. For more information, check out this [blog post](https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards) ! What is cryptography used for? ------------------------------ **Uses in every day software** * Securing web traffic (passwords, communication, etc.) * Securing copyrighted software code * Key exchange algorithms **Malicious uses** * Hiding malicious communication * Hiding malicious code Additional Links ---------------- Back to top --- # How to connect to services - CTF Handbook [Skip to content](https://ctf101.org/faq/connecting-to-services/#how-to-connect-to-services) How to connect to services ========================== Note While service challenges are often connected to with netcat or PuTTY, solving them will sometimes require using a scripting language like Python. CTF players often use Python alongside [pwntools](https://github.com/Gallopsled/pwntools/) . You can run [pwntools](http://docs.pwntools.com/en/stable/install.html) right in your browser by using [repl.it](https://repl.it/) . Using netcat ------------ [![netcat usage](https://ctf101.org/faq/images/netcat.gif)](https://ctf101.org/faq/images/netcat.gif) `netcat` is a networking utility found on macOS and linux operating systems and allows for easy connections to CTF challenges. Service challenges will commonly give you an address and a port to connect to. The syntax for connecting to a service challenge with netcat is `nc `. Using ConEmu ------------ Windows users can connect to service challenges using ConEmu, which can be downloaded [here](https://conemu.github.io/) . Connecting to service challenges with ConEmu is done by running `nc `. Back to top --- # Overview - CTF Handbook [Skip to content](https://ctf101.org/binary-exploitation/overview/#binary-exploitation) Binary Exploitation =================== Binaries, or executables, are machine code for a computer to execute. For the most part, the binaries that you will face in CTFs are Linux ELF files or the occasional windows executable. Binary Exploitation is a broad topic within Cyber Security which really comes down to finding a vulnerability in the program and exploiting it to gain control of a shell or modifying the program's functions. Back to top --- # Getting Started with CTFs - CTF Handbook [Skip to content](https://ctf101.org/intro/ctf-basics/#how-to-get-started) How to get started ================== First of all, make sure to check out our [recommended software](https://ctf101.org/faq/recommended-software/) section. It's handy to have these tools installed and ready as you get to solving some CTFs. Ideally, you must have : - a decompiler like [Binja](https://binary.ninja/) - a debugger, [gdb](https://www.sourceware.org/gdb/) - a suite of web tools, [Burp](https://portswigger.net/burp/communitydownload) , [sqlmap](https://sqlmap.org/) , and [Wireshark](https://www.wireshark.org/download.html) are solid to begin with - the essential python package [pwntools](https://docs.pwntools.com/en/stable/install.html) to interact with processes easily Back to top --- # How do I host a CTF - CTF Handbook [Skip to content](https://ctf101.org/intro/how-to-run-a-ctf/#how-do-i-run-a-ctf) How do I run a CTF? =================== > "Is it really a CTF if you don't solve the infrastructure problem in the 24 hours before the competition?" Before you start ---------------- Consider a few of the following before starting a CTF. * How many people will play in my CTF? * What type of challenges do I want to write? * How do you want to host your challenges? * What is my budget? Challenge Writing ----------------- Infrastructure -------------- Depending on the size of your competition, you're going to need different types of deployments. Generally, you'll need a [load balancer](https://en.wikipedia.org/wiki/Load_balancing_(computing)) to work concurrently with your web application. Info When we ran CSAW'23, there were over 2500 teams of ~4 people. You can try to gauge how many users your competition might have before writing a deployment. **Open Source Frameworks** -------------------------- ### [CTFd](https://docs.ctfd.io/) CTFd makes it easy to spin up an instance able to support a CTF at any time. Starting a local server is as easy as: `docker run -p 8000:8000 -it ctfd/ctfd # (1)` 1. For more information on Docker, read the [docs](https://docs.docker.com/) ! ### [kCTF](https://google.github.io/kctf/) kCTF is a framework written by Google built on Kubernetes. It has built in load balancing at the platform level. ### [rCTF](https://rctf.redpwn.net/) Written by the redPWN CTF team, rCTF has a separate CI/CD module for supporting challenge deployment as well. `curl https://get.rctf.redpwn.net | sh` **Paid CTF Hosting** -------------------- ### [CTFd Enterprise](https://ctfd.io/pricing/) * Three-tiered pricing service with hosting services and on-call support. * Supports professional workshops generally reserved for industry security teams exercises. ### [Hack the Box CTF](https://www.hackthebox.com/business/business-ctf) Back to top --- # File Formats - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-are-file-formats/#file-formats) File Formats ============ File Extensions are not the sole way to identify the type of a file, files have certain leading bytes called _file signatures_ which allow programs to parse the data in a consistent manner. Files can also contain additional "hidden" data called _metadata_ which can be useful in finding out information about the context of a file's data. File Signatures --------------- **File signatures** (also known as File Magic Numbers) are bytes within a file used to identify the format of the file. Generally they’re 2-4 bytes long, found at the beginning of a file. ### What is it used for? Files can sometimes come without an extension, or with incorrect ones. We use file signature analysis to identify the format (file type) of the file. Programs need to know the file type in order to open it properly. It's useful to analyze the file type before any forensics software. ### How do you find the file signature? You need to be able to look at the binary data that constitutes the file you’re examining. To do this, you’ll use a hexadecimal editor. Once you find the file signature, you can check it against file signature repositories [such as Gary Kessler’s](http://www.garykessler.net/library/file_sigs.html) . Example [![File A](https://ctf101.org/forensics/images/file-a.jpg)](https://ctf101.org/forensics/images/file-a.jpg) The file above, when opened in a hexadecimal editor like `xxd` or `hexdump`, begins with the bytes `FFD8FFE0 00104A46 494600` or in ASCII `ˇÿˇ‡ JFIF` where `\x00` and `\x10` lack symbols. [![Example A](https://ctf101.org/forensics/images/xxd.gif)](https://ctf101.org/forensics/images/xxd.gif) Searching in [Gary Kessler’s](http://www.garykessler.net/library/file_sigs.html) database shows that this file signature belongs to a `JPEG/JFIF graphics file`. You can also use the file utility in Linux to determine the file type! `▲ ~/examples file file-a.jpg file-a.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90", baseline, precision 8, 1024x576, components 3` Back to top --- # Metadata - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-metadata/#metadata) Metadata ======== Metadata is data about data. Different types of files have different metadata. The metadata on a photo could include dates, camera information, GPS location, comments, etc. For music, it could include the title, author, track number and album. CTF challenges often have you looking for specific clues in the metadata of a file (especially media files). Note EXIF Data is metadata attached to photos which can include location, time, and device information. How do I find it? ----------------- One of our favorite tools is [`exiftool`](https://exiftool.org/) , which displays metadata for an input file: - File size - Dimensions (width and height) - File type - Programs used to create (e.g. Photoshop) - OS used to create (e.g. Apple) [![Exiftool](https://ctf101.org/forensics/images/exiftool.gif)](https://ctf101.org/forensics/images/exiftool.gif) Example Let's take a look at a file's metadata with exiftool: ----------------------------------------------------- > File type [![Metadata 1](https://ctf101.org/forensics/images/file-a-metadata-1.png)](https://ctf101.org/forensics/images/file-a-metadata-1.png) > Image description [![Metadata 2](https://ctf101.org/forensics/images/file-a-metadata-2.png)](https://ctf101.org/forensics/images/file-a-metadata-2.png) > Camera make and model: [![Metadata 3](https://ctf101.org/forensics/images/file-a-metadata-3.png)](https://ctf101.org/forensics/images/file-a-metadata-3.png) > GPS Latitude/Longitude [![Metadata 4](https://ctf101.org/forensics/images/file-a-metadata-4.png)](https://ctf101.org/forensics/images/file-a-metadata-4.png) Timestamps ---------- Timestamps are data that indicate the time of certain events (MAC): - Modification – when a file was modified - Access – when a file or entries were read or accessed - Creation – when files or entries were created ### Types of timestamps * Modified * Accessed * Created * Date Changed (MFT) * Filename Date Created (MFT) * Filename Date Modified (MFT) * Filename Date Accessed (MFT) * INDX Entry Date Created * INDX Entry Date Modified * INDX Entry Date Accessed * INDX Entry Date Changed ### Why do we care? Certain events such as creating, moving, copying, opening, editing, etc. might affect the MAC times. If the MAC timestamps can be attained, a timeline of events could be created. ### Timeline Patterns There are plenty more patterns than the ones introduced below, but these are the basics you should start with to get a good understanding of how it works, and to complete this challenge. [![Timeline 1](https://ctf101.org/forensics/images/timeline-1.png)](https://ctf101.org/forensics/images/timeline-1.png) [![Timeline 2](https://ctf101.org/forensics/images/timeline-2.png)](https://ctf101.org/forensics/images/timeline-2.png) [![Timeline 3](https://ctf101.org/forensics/images/timeline-3.png)](https://ctf101.org/forensics/images/timeline-3.png) [![Timeline 4](https://ctf101.org/forensics/images/timeline-4.png)](https://ctf101.org/forensics/images/timeline-4.png) [![Timeline 5](https://ctf101.org/forensics/images/timeline-5.png)](https://ctf101.org/forensics/images/timeline-5.png) Example We know that the BMP files fileA and fileD are the same, but that the JPEG files fileB and fileC are different somehow. So how can we find out what went on with these files? [![Files A, B, C, D](https://ctf101.org/forensics/images/file-a-b-c-d.png)](https://ctf101.org/forensics/images/file-a-b-c-d.png) By using time stamp information from the file system, we can learn that the BMP fileD was the original file, with fileA being a copy of the original. Afterward, fileB was created by modifying fileB, and fileC was created by modifying fileA in a different way. Follow along as we demonstrate. We’ll start by analyzing images in AccessData FTK Imager, where there’s a Properties window that shows you some information about the file or folder you’ve selected. [![Timestamp 1](https://ctf101.org/forensics/images/timestamp-1.png)](https://ctf101.org/forensics/images/timestamp-1.png) [![Timestamp 2](https://ctf101.org/forensics/images/timestamp-2.png)](https://ctf101.org/forensics/images/timestamp-2.png) [![Timestamp 3](https://ctf101.org/forensics/images/timestamp-3.png)](https://ctf101.org/forensics/images/timestamp-3.png) [![Timestamp 4](https://ctf101.org/forensics/images/timestamp-4.png)](https://ctf101.org/forensics/images/timestamp-4.png) Here are the extracted MAC times for fileA, fileB, fileC and fileD: [![Timestamp 5](https://ctf101.org/forensics/images/timestamp-5.png)](https://ctf101.org/forensics/images/timestamp-5.png) Note AccessData FTK Imager assumes that the file times on the drive are in UTC (Universal Coordinated Time). I subtracted four hours, since the USB was set up in Eastern Standard Time. This isn’t necessary, but it helps me understand the times a bit better.\* Highlight timestamps that are the same, if timestamps are off by a few seconds, they should be counted as the same. This lets you see a clear difference between different timestamps. Then, highlight oldest to newest to help put them in order. [![Timestamp 6](https://ctf101.org/forensics/images/timestamp-6.png)](https://ctf101.org/forensics/images/timestamp-6.png) [![Timestamp 7](https://ctf101.org/forensics/images/timestamp-7.png)](https://ctf101.org/forensics/images/timestamp-7.png) [![Timestamp 8](https://ctf101.org/forensics/images/timestamp-8.png)](https://ctf101.org/forensics/images/timestamp-8.png) [![Timestamp 9](https://ctf101.org/forensics/images/timestamp-9.png)](https://ctf101.org/forensics/images/timestamp-9.png) [![Timestamp 10](https://ctf101.org/forensics/images/timestamp-10.png)](https://ctf101.org/forensics/images/timestamp-10.png) [![Timestamp 11](https://ctf101.org/forensics/images/timestamp-11.png)](https://ctf101.org/forensics/images/timestamp-11.png) [![Timestamp 12](https://ctf101.org/forensics/images/timestamp-12.png)](https://ctf101.org/forensics/images/timestamp-12.png) [![Timestamp 13](https://ctf101.org/forensics/images/timestamp-13.png)](https://ctf101.org/forensics/images/timestamp-13.png) [![Timestamp 14](https://ctf101.org/forensics/images/timestamp-14.png)](https://ctf101.org/forensics/images/timestamp-14.png) [![Timestamp 15](https://ctf101.org/forensics/images/timestamp-15.png)](https://ctf101.org/forensics/images/timestamp-15.png) Identify timestamp patterns. [![Timestamp 16](https://ctf101.org/forensics/images/timestamp-16.png)](https://ctf101.org/forensics/images/timestamp-16.png) Back to top --- # Wireshark - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-wireshark/#wireshark) Wireshark ========= Overview -------- [Wireshark](http://www.wireshark.com/) is a network protocol analyzer which is often used in CTF challenges to look at recorded network traffic. Wireshark uses a filetype called .pcap, or "packet capture", to record traffic. Info `.pcap`'s are often distributed in CTF challenges to provide recorded traffic history and are one of the most common forms of forensics challenge. Example Upon opening Wireshark, you are greeted with the option to open a PCAP or begin capturing network traffic on your device. [![Wireshark Start Screen](https://ctf101.org/forensics/images/ws-start-screen.png)](https://ctf101.org/forensics/images/ws-start-screen.png) The network traffic displayed initially shows the packets in order of which they were captured. You can filter packets by protocol, source IP address, destination IP address, length, etc. [![PCAP Screen](https://ctf101.org/forensics/images/ws-pcap-screen.png)](https://ctf101.org/forensics/images/ws-pcap-screen.png) In order to apply filters, simply enter the constraining factor, for example 'http', in the display filter bar. [![PCAP HTTP Filter](https://ctf101.org/forensics/images/ws-filter.png)](https://ctf101.org/forensics/images/ws-filter.png) Filters can be chained together using '&&' notation. In order to filter by IP, ensure a double equals '==' is used. [![PCAP HTTP IP Filter](https://ctf101.org/forensics/images/ws-filter-2.png)](https://ctf101.org/forensics/images/ws-filter-2.png) The most pertinent part of a packet is its data payload and protocol information. [![HTTP TCP Info](https://ctf101.org/forensics/images/ws-tcp-http-info.png)](https://ctf101.org/forensics/images/ws-tcp-http-info.png) Decrypting SSL Traffic ---------------------- By default, Wireshark cannot decrypt SSL traffic on your device unless you grant it specific certificates. ### High Level SSL Handshake Overview In order for a network session to be encrypted properly, the client and server must share a common secret for which they can use to encrypt and decrypt data without someone in the middle being able to guess. The SSL Handshake loosely follows this format: 1. The client sends a list of available cipher suites it can use along with a random set of bytes referred to as `client_random` 2. The server sends back the cipher suite that will be used, such as `TLS_DHE_RSA_WITH_AES_128_CBC_SHA`, along with a random set of bytes referred to as `server_random` 3. The client generates a pre-master secret, encrypts it, then sends it to the server. 4. The server and client then generate a common master secret using the selected cipher suite 5. The client and server begin communicating using this common secret ### Decryption Requirements There are several ways to be able to decrypt traffic. * If you have the client and server random values _and_ the pre-master secret, the master secret can be generated and used to decrypt the traffic * If you have the master secret, traffic can be decrypted easily * If the cipher-suite uses `RSA` and is sufficiently vulnerable in complexity, you can factor _n_ in the key in order to break the encryption on the encrypted pre-master secret and generate the master secret with the client and server randoms. [![Wireshark SSL Preferences](https://ctf101.org/forensics/images/ws-ssl-pref.png)](https://ctf101.org/forensics/images/ws-ssl-pref.png) Back to top --- # Stegonagraphy - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-stegonagraphy/#steganography) Steganography ============= Steganography is the practice of hiding data in plain sight. Steganography is often embedded in images or audio. You could send a picture of a cat to a friend and hide text inside. Looking at the image, there’s nothing to make anyone think there’s a message hidden inside it. [![Steg with text](https://ctf101.org/forensics/images/steg-cat-text.png)](https://ctf101.org/forensics/images/steg-cat-text.png) You could also hide a second image inside the first. [![Steg with an Image](https://ctf101.org/forensics/images/steg-cat-image.png)](https://ctf101.org/forensics/images/steg-cat-image.png) Steganography Detection ----------------------- So we can hide text and an image, how do we find out if there is hidden data? [![Group of images](https://ctf101.org/forensics/images/steg-a-b-c-d.png)](https://ctf101.org/forensics/images/steg-a-b-c-d.png) FileA and FileD appear the same, but they’re different. Also, FileD was modified after it was copied, so it’s possible there might be steganography in it. FileB and FileC don’t appear to have been modified after being created. That doesn’t rule out the possibility that there’s steganography in them, but you’re more likely to find it in fileD. This brings up two questions: 1. Can we determine that there is steganography in fileD? 2. If there is, what was hidden in it? LSB Steganography ----------------- File are made of bytes. Each byte is composed of eight bits. [![Steganography Process Step 1](https://ctf101.org/forensics/images/steg-step-1.png)](https://ctf101.org/forensics/images/steg-step-1.png) Changing the least-significant bit (LSB) doesn’t change the value very much. [![Steganography Process Step 2](https://ctf101.org/forensics/images/steg-step-2.png)](https://ctf101.org/forensics/images/steg-step-2.png) So we can modify the LSB without changing the file noticeably. By doing so, we can hide a message inside. ### LSB Steganography in Images LSB Steganography or _Least Significant Bit_ Steganography is a method of Steganography where data is recorded in the lowest bit of a byte. Say an image has a pixel with an RGB value of (255, 255, 255), the bits of those RGB values will look like By modifying the lowest, or least significant, bit, we can use the 1 bit space across every RGB value for every pixel to construct a message. Consider this rgb(255,255,255) is represented by `11111111` in binary. However, what difference does changing this to `11111110` make? The reason steganography is hard to detect by sight is because a 1 bit difference in color is insignificant as seen below. [![1 Bit Difference](https://ctf101.org/forensics/images/lsb-color-difference.png)](https://ctf101.org/forensics/images/lsb-color-difference.png) Example Let’s say we have an image, and part of it contains the following binary: [![Steganography Process Step 3](https://ctf101.org/forensics/images/steg-step-3.png)](https://ctf101.org/forensics/images/steg-step-3.png) And let’s say we want to hide the character y inside. First, we need to convert the hidden message to binary. [![Steganography Process Step 4](https://ctf101.org/forensics/images/steg-step-4.png)](https://ctf101.org/forensics/images/steg-step-4.png) Now we take each bit from the hidden message and replace the LSB of the corresponding byte with it. [![Steganography Process Step 5](https://ctf101.org/forensics/images/steg-step-5.png)](https://ctf101.org/forensics/images/steg-step-5.png) And again: [![Steganography Process Step 6](https://ctf101.org/forensics/images/steg-step-6.png)](https://ctf101.org/forensics/images/steg-step-6.png) And again: [![Steganography Process Step 7](https://ctf101.org/forensics/images/steg-step-7.png)](https://ctf101.org/forensics/images/steg-step-7.png) And again: [![Steganography Process Step 8](https://ctf101.org/forensics/images/steg-step-8.png)](https://ctf101.org/forensics/images/steg-step-8.png) And again: [![Steganography Process Step 9](https://ctf101.org/forensics/images/steg-step-9.png)](https://ctf101.org/forensics/images/steg-step-9.png) And again: [![Steganography Process Step 10](https://ctf101.org/forensics/images/steg-step-10.png)](https://ctf101.org/forensics/images/steg-step-10.png) And again: [![Steganography Process Step 11](https://ctf101.org/forensics/images/steg-step-11.png)](https://ctf101.org/forensics/images/steg-step-11.png) And once more: [![Steganography Process Step 12](https://ctf101.org/forensics/images/steg-step-12.png)](https://ctf101.org/forensics/images/steg-step-12.png) Decoding LSB steganography is exactly the same as encoding, but in reverse. For each byte, grab the LSB and add it to your decoded message. Once you’ve gone through each byte, convert all the LSBs you grabbed into text or a file. (You can use your file signature knowledge here!) Back to top --- # Disk Imaging - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-disk-imaging/#disk-imaging) Disk Imaging ============ A forensic image is an electronic copy of a drive (e.g. a hard drive, USB, etc.). It’s a bit-by-­bit or bitstream file that’s an exact, unaltered copy of the media being duplicated. Wikipedia said that the most straight­forward disk imaging method is to read a disk from start to finish and write the data to a forensics image format. “This can be a time-consuming process, especially for disks with a large capacity." Checksum -------- Validating files is one of the most important aspects of disk forensics. This hash will change if any part of file is changed, making it great for catching alterations to the original source. Validating Downloads Checking the hash of a download is also good practice when using third-party vendors for common software. It catches tampered files that could potentially contain malware. [![Dell MD5](https://ctf101.org/forensics/images/sha.png)](https://ctf101.org/forensics/images/sha.png) We can use tools like `md5sum` or `sha256sum` from the command line to generate the hashes of a file. _Observe the different hash when the file is altered._ [![Hash](https://ctf101.org/forensics/images/hash.gif)](https://ctf101.org/forensics/images/hash.gif) Write Blocker ------------- It's common practice to use a write blocker before imagining a disk. This prevents unintended writes to the disk to maintain integrity. [Kali Linux](https://www.kali.org/docs/general-use/kali-linux-forensics-mode/) has a "forensics" mode that features a write blocker and is designed for all sorts of forensics in mind. Why image a disk? ----------------- * Prevents tampering with the original data­ evidence * Allows you to play around with the copy, without worrying about messing up the original Forensic Image Extraction This example uses the tool [AccessData FTK Imager](http://accessdata.com/product-download) . **Step 1**: Go to `File > Create Disk Image` [![File Image Demo](https://ctf101.org/forensics/images/image-demo-1.png)](https://ctf101.org/forensics/images/image-demo-1.png) **Step 2**: Select `Physical Drive`, because the USB or hard drive you’re imaging is a physical device or drive. [![File Image Demo](https://ctf101.org/forensics/images/image-demo-2.png)](https://ctf101.org/forensics/images/image-demo-2.png) **Step 3**: Select the drive you’re imaging. The 1000 GB is my computer hard drive; the 128 MB is the USB that I want to image. [![File Image Demo](https://ctf101.org/forensics/images/image-demo-3.png)](https://ctf101.org/forensics/images/image-demo-3.png) **Step 4**: Add a new image destination [![File Image Demo](https://ctf101.org/forensics/images/image-demo-4.png)](https://ctf101.org/forensics/images/image-demo-4.png) **Step 5**: Select whichever image type you want. Choose `Raw (dd)` if you’re a beginner, since it’s the most common type [![File Image Demo](https://ctf101.org/forensics/images/image-demo-5.png)](https://ctf101.org/forensics/images/image-demo-5.png) **Step 6**: Fill in all the evidence information [![File Image Demo](https://ctf101.org/forensics/images/image-demo-6.png)](https://ctf101.org/forensics/images/image-demo-6.png) **Step 7**: Choose where you want to store it [![File Image Demo](https://ctf101.org/forensics/images/image-demo-7.png)](https://ctf101.org/forensics/images/image-demo-7.png) **Step 8**: The image destination has been added. Now you can start the image extraction [![File Image Demo](https://ctf101.org/forensics/images/image-demo-8.png)](https://ctf101.org/forensics/images/image-demo-8.png) **Step 9**: Wait for the image to be extracted [![File Image Demo](https://ctf101.org/forensics/images/image-demo-9.png)](https://ctf101.org/forensics/images/image-demo-9.png) **Step 10**: This is the completed extraction [![File Image Demo](https://ctf101.org/forensics/images/image-demo-10.png)](https://ctf101.org/forensics/images/image-demo-10.png) **Step 11**: Add the image you just created so that you can view it [![File Image Demo](https://ctf101.org/forensics/images/image-demo-11.png)](https://ctf101.org/forensics/images/image-demo-11.png) **Step 12**: This time, choose image file, since that’s what you just created [![File Image Demo](https://ctf101.org/forensics/images/image-demo-12.png)](https://ctf101.org/forensics/images/image-demo-12.png) **Step 13**: Enter the path of the image you just created [![File Image Demo](https://ctf101.org/forensics/images/image-demo-13.png)](https://ctf101.org/forensics/images/image-demo-13.png) **Step 14**: View the image. 1. Evidence tree Structure of the drive image 2. File list List of all the files in the drive image folder 3. Properties Properties of the file/folder being examined 4. Hex viewer View of the drive/folders/files in hexadecimal [![File Image Demo](https://ctf101.org/forensics/images/image-demo-14.png)](https://ctf101.org/forensics/images/image-demo-14.png) **Step 15**: To view files in the USB, go to `Partition 1 > [USB name] > [root]` in the Evidence Tree and look in the File List [![File Image Demo](https://ctf101.org/forensics/images/image-demo-15.png)](https://ctf101.org/forensics/images/image-demo-15.png) **Step 16**: Selecting fileA, fileB, fileC, or fileD gives us some properties of the files & a preview of each photo [![File Image Demo](https://ctf101.org/forensics/images/image-demo-16.png)](https://ctf101.org/forensics/images/image-demo-16.png) **Step 17**: Extract files of interest for further analysis by selecting, right-clicking and choosing `Export Files` [![File Image Demo](https://ctf101.org/forensics/images/image-demo-17.png)](https://ctf101.org/forensics/images/image-demo-17.png) Back to top --- # Memory Forensics - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-memory-forensics/#memory-forensics) Memory Forensics ================ There are plenty of traces of someone's activity on a computer, but perhaps some of the most valuble information can be found within memory dumps, that is images taken of RAM. These dumps of data are often very large, but can be analyzed using a tool called [Volatility](http://www.volatilityfoundation.org/) Volatility Basics ----------------- Memory forensics isn't all that complicated, the hardest part would be using your toolset correctly. A good workflow is as follows: 1. Run `strings` for clues 2. Identify the image profile (which OS, version, etc.) 3. Dump processes and look for suspicious processes 4. Dump data related interesting processes 5. View data in a format relating to the process (Word: .docx, Notepad: .txt, Photoshop: .psd, etc.) ### Profile Identification In order to properly use Volatility you must supply a profile with `--profile=PROFILE`, therefore before any sleuthing, you need to determine the profile using imageinfo: `$ python vol.py -f ~/image.raw imageinfo Volatility Foundation Volatility Framework 2.4 Determining profile based on KDBG search... Suggested Profile(s) : Win7SP0x64, Win7SP1x64, Win2008R2SP0x64, Win2008R2SP1x64 AS Layer1 : AMD64PagedMemory (Kernel AS) AS Layer2 : FileAddressSpace (/Users/Michael/Desktop/win7_trial_64bit.raw) PAE type : PAE DTB : 0x187000L KDBG : 0xf80002803070 Number of Processors : 1 Image Type (Service Pack) : 0 KPCR for CPU 0 : 0xfffff80002804d00L KUSER_SHARED_DATA : 0xfffff78000000000L Image date and time : 2012-02-22 11:29:02 UTC+0000 Image local date and time : 2012-02-22 03:29:02 -0800` ### Dump Processes In order to view processes, the `pslist` or `pstree` or `psscan` command can be used. `$ python vol.py -f ~/image.raw pslist --profile=Win7SP0x64 pstree Volatility Foundation Volatility Framework 2.5 Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit ------------------ -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------ 0xffffa0ee12532180 System 4 0 108 0 ------ 0 2018-04-22 20:02:33 UTC+0000 0xffffa0ee1389d040 smss.exe 232 4 3 0 ------ 0 2018-04-22 20:02:33 UTC+0000 ... 0xffffa0ee128c6780 VBoxTray.exe 3324 1123 10 0 1 0 2018-04-22 20:02:55 UTC+0000 0xffffa0ee14108780 OneDrive.exe 1422 1123 10 0 1 1 2018-04-22 20:02:55 UTC+0000 0xffffa0ee14ade080 svchost.exe 228 121 1 0 1 0 2018-04-22 20:14:43 UTC+0000 0xffffa0ee1122b080 notepad.exe 2019 1123 1 0 1 0 2018-04-22 20:14:49 UTC+0000` ### Process Memory Dump Dumping the memory of a process can prove to be fruitful, say we want to dump the data from notepad.exe: `$ python vol.py -f ~/image.raw --profile=Win7SP0x64 memdump -p 2019 -D dump/ Volatility Foundation Volatility Framework 2.4 ************************************************************************ Writing System [ 2019] to 2019.dmp $ ls -alh dump/2019.dmp -rw-r--r-- 1 user staff 111M Apr 22 20:47 dump/2019.dmp` ### Other Useful Commands [There are plenty of commands](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference) that Volatility offers but some highlights include: * `$ python vol.py -f IMAGE --profile=PROFILE connections`: view network connections * `$ python vol.py -f IMAGE --profile=PROFILE cmdscan`: view commands that were run in cmd prompt Back to top --- # Hex Editors - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-a-hex-editor/#hex-editor) Hex Editor ========== A hexadecimal (hex) editor (also called a binary file editor or byte editor) is a computer program you can use to manipulate the fundamental binary data that constitutes a computer file. The name “hex” comes from “hexadecimal,” a standard numerical format for representing binary data. A typical computer file occupies multiple areas on the platter(s) of a disk drive, whose contents are combined to form the file. Hex editors that are designed to parse and edit sector data from the physical segments of floppy or hard disks are sometimes called sector editors or disk editors. A hex editor is used to see or edit the raw, exact contents of a file. Hex editors may used to correct data corrupted by a system or application. A [list of editors](https://forensics.wiki/tools/#hex-editors) can be found on the forensics Wiki. Your hex editor should have two sections, the `hexadecimal` and `character` representations of that data. It's helpful to also have a "goto" feature in your hex editor to navigate large dumps of data. Example A simple CTF challenge is modifying the header of a file. In this example, I changed the first byte of this file to `AA` instead of the conventional `FF` needed in the JFIF(JPEG File Interchangable Format). Observe how it changes the behavior of the `file` command. ``scribbl@rogstation:~/examples$ xxd example | head 00000000: aad8 ffe0 0010 4a46 4946 0001 0101 0060 ......JFIF.....` 00000010: 0060 0000 fffe 003b 4352 4541 544f 523a .`.....;CREATOR: 00000020: 2067 642d 6a70 6567 2076 312e 3020 2875 gd-jpeg v1.0 (u 00000030: 7369 6e67 2049 4a47 204a 5045 4720 7638 sing IJG JPEG v8 00000040: 3029 2c20 7175 616c 6974 7920 3d20 3930 0), quality = 90 00000050: 0aff db00 4300 0302 0203 0202 0303 0303 ....C........... 00000060: 0403 0304 0508 0505 0404 050a 0707 0608 ................ 00000070: 0c0a 0c0c 0b0a 0b0b 0d0e 1210 0d0e 110e ................ 00000080: 0b0b 1016 1011 1314 1515 150c 0f17 1816 ................ 00000090: 1418 1214 1514 ffdb 0043 0103 0404 0504 .........C...... scribbl@rogstation:~/examples$ file example example: data`` Using a hexeditor like [hexcurse](https://manpages.ubuntu.com/manpages/focal/man1/hexcurse.1.html) , we can change the header back to `FF` to be recognizable again by `file`. [![Hexedit](https://ctf101.org/forensics/images/hexedit.gif)](https://ctf101.org/forensics/images/hexedit.gif) Finally, `file` and programs recognize the header again. `scribbl@rogstation:~/examples$ file example example: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90", baseline, precision 8, 1024x576, components 3` Back to top --- # Packet Capture - CTF Handbook [Skip to content](https://ctf101.org/forensics/what-is-packet-capture/#packet-capture) Packet Capture ============== Some special challenges require competitors to capture packets from an endpoint. This guide will go over the packet-capturing tool, `tcpdump` as well as [Wireshark](https://www.wireshark.org/download.html) . Info This simulates a more realistic offensive security element of collecting data from networks. Additionally, packet captures are great for debugging networking and infrastructure. * * * `tcpdump` `tcpdump` is a built in command line utility that captures network traffic and prints it out for you. For example, if I want to show all packets on the `eth0` interface. I can specify `tcpdump` to listen to it. `sudo tcpdump -i eth0` [![Eth0 Example](https://ctf101.org/forensics/images/eth0.gif)](https://ctf101.org/forensics/images/eth0.gif) `scribbl@rogstation:~/examples$ sudo tcpdump -i eth0 tcpdump: verbose output suppressed, use -v[v]... for full protocol decode listening on eth0, link-type EN10MB (Ethernet), snapshot length 262144 bytes 17:32:07.557403 IP rogstation.mshome.net.57621 > 172.22.207.255.57621: UDP, length 44 17:32:07.633396 IP 172.22.206.250.58387 > rogstation.mshome.net.domain: 38921+ PTR? 255.207.22.172.in-addr.arpa. (45) 17:32:07.634756 IP rogstation.mshome.net.mdns > mdns.mcast.net.mdns: 0 PTR (QM)? 255.207.22.172.in-addr.arpa.local. (51) 17:32:07.635213 IP6 rogstation.mdns > ff02::fb.mdns: 0 PTR (QM)? 255.207.22.172.in-addr.arpa.local. (51) 17:32:07.640442 IP rogstation.mshome.net.mdns > mdns.mcast.net.mdns: 0 PTR (QM)? 255.207.22.172.in-addr.arpa.local. (51) 17:32:07.640689 IP6 rogstation.mdns > ff02::fb.mdns: 0 PTR (QM)? 255.207.22.172.in-addr.arpa.local. (51) 17:32:08.718973 IP rogstation.mshome.net.mdns > mdns.mcast.net.mdns: 0 PTR (QM)? 255.207.22.172.in-addr.arpa.local. (51) ...` Let's specify `tcpdump` to only list traffic from the source `172.22.206.250` and save the information to a file. `sudo tcpdump -i eth0 -w packets.pcap src 172.22.206.250` We can then use a tool like [`tshark`](https://tshark.dev/) to see our packets in the command line. `scribbl@rogstation:~/examples$ tshark -r packets.pcap 1 0.000000 172.22.192.1 → 224.0.0.251 MDNS 87 Standard query 0x0000 PTR _spotify-connect._tcp.local, "QM" question 2 0.000355 fe80::a6ee:2618:bd01:f6c5 → ff02::fb MDNS 107 Standard query 0x0000 PTR _spotify-connect._tcp.local, "QM" question 3 3.036792 172.22.192.1 → 239.255.255.250 SSDP 167 M-SEARCH * HTTP/1.1 4 12.456780 172.22.192.1 → 172.22.207.255 UDP 86 57621 → 57621 Len=44 5 45.024825 172.22.192.1 → 172.22.207.255 UDP 86 57621 → 57621 Len=44` * * * Wireshark Wireshark is a really good resource to view packets and see their contents. We can also use Wireshark to capture packets on our interface just like `tcpdump`. Here in this example, I have a ping command running in a WSL instance. [![Wireshark Record](https://ctf101.org/forensics/images/wireshark-record.gif)](https://ctf101.org/forensics/images/wireshark-record.gif) Back to top --- # Hashing Functions - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-are-hashing-functions/#hashing-functions) Hashing Functions ================= Hashing functions are one way functions which theoretically provide a unique output for every input. MD5, SHA-1, and other hashes which were considered secure are now found to have _collisions_ or two different pieces of data which produce the same supposed unique output. String Hashing -------------- A string hash is a number or string generated using an algorithm that runs on text or data. The idea is that each hash should be unique to the text or data (although sometimes it isn’t). For example, the hash for “dog” should be different from other hashes. You can use command line tools or online resources such as this one. Example: `$ echo -n password | md5 5f4dcc3b5aa765d61d8327deb882cf99` Here, “password” is hashed with different hashing algorithms: * **SHA-1**: 5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8 * **SHA-2**: 5E884898DA28047151D0E56F8DC6292773603D0D6AABBDD62A11EF721D1542D8 * **MD5**: 5F4DCC3B5AA765D61D8327DEB882CF99 * **CRC32**: BBEDA74F Generally, when verifying a hash visually, you can simply look at the first and last four characters of the string. File Hashing ------------ A file hash is a number or string generated using an algorithm that is run on text or data. The premise is that it should be unique to the text or data. If the file or text changes in any way, the hash will change. What is it used for? - File and data identification - Password/certificate storage comparison How can we determine the hash of a file? You can use the md5sum command (or similar). `$ md5sum samplefile.txt 3b85ec9ab2984b91070128be6aae25eb samplefile.txt` Hash Collisions --------------- A collision is when two pieces of data or text have the same cryptographic hash. This is very rare. What’s significant about collisions is that they can be used to crack password hashes. Passwords are usually stored as hashes on a computer, since it’s hard to get the passwords from hashes. [![Password to Hash](https://ctf101.org/cryptography/images/hashing-collision-1.png)](https://ctf101.org/cryptography/images/hashing-collision-1.png) If you bruteforce by trying every possible piece of text or data, eventually you’ll find something with the same hash. Enter it, and the computer accepts it as if you entered the actual password. Two different files on the same hard drive with the same cryptographic hash can be very interesting. “It’s now well-known that the cryptographic hash function MD5 has been broken,” [said Peter Selinger of Dalhousie University](http://www.mscs.dal.ca/~selinger/md5collision/) . “In March 2005, Xiaoyun Wang and Hongbo Yu of Shandong University in China published an article in which they described an algorithm that can find two different sequences of 128 bytes with the same MD5 hash.” [1](https://ctf101.org/cryptography/what-are-hashing-functions/#fn:1) For example, he cited this famous pair: [![Password to Hash](https://ctf101.org/cryptography/images/hashing-collision-2.png)](https://ctf101.org/cryptography/images/hashing-collision-2.png) and [![Password to Hash](https://ctf101.org/cryptography/images/hashing-collision-3.png)](https://ctf101.org/cryptography/images/hashing-collision-3.png) Each of these blocks has MD5 hash 79054025255fb1a26e4bc422aef54eb4. Selinger said that “the algorithm of Wang and Yu can be used to create files of arbitrary length that have identical MD5 hashes, and that differ only in 128 bytes somewhere in the middle of the file. Several people have used this technique to create pairs of interesting files with identical MD5 hashes.” Ben Laurie [has a nice website that visualizes this MD5 collision](http://www.links.org/?p=6) . For a non-technical, though slightly outdated, introduction to hash functions, see [Steve Friedl’s Illustrated Guide](http://www.unixwiz.net/techtips/iguide-crypto-hashes.html) . And [here’s a good article](http://www.forensicmag.com/articles/2008/12/hash-algorithm-dilemma%E2%80%93hash-value-collisions) from DFI News that explores the same topic. * * * 1. http://www.mscs.dal.ca/~selinger/md5collision/ [↩](https://ctf101.org/cryptography/what-are-hashing-functions/#fnref:1 "Jump back to footnote 1 in the text") Back to top --- # XOR - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-is-xor/#xor) XOR === Data Representation ------------------- Data can be represented in different bases, an 'A' needs to be a numerical representation of Base 2 or binary so computers can understand them [![Data Representation](https://ctf101.org/cryptography/images/data-representation.png)](https://ctf101.org/cryptography/images/data-representation.png) XOR Basics ---------- An XOR or _eXclusive OR_ is a bitwise operation indicated by `^` and shown by the following truth table: | A | B | A ^ B | | --- | --- | --- | | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | So what XOR'ing bytes in the action `0xA0 ^ 0x2C` translates to is: | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | | 0 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | | --- | --- | --- | --- | --- | --- | --- | --- | | | | | | | | | | `0b10001100` is equivelent to `0x8C`, a cool property of XOR is that it is reversable meaning `0x8C ^ 0x2C = 0xA0` and `0x8C ^ 0xA0 = 0x2C` [![XOR Basics](https://ctf101.org/cryptography/images/xor.png)](https://ctf101.org/cryptography/images/xor.png) What does this have to do with CTF? ----------------------------------- XOR is a cheap way to encrypt data with a password. Any data can be encrypted using XOR as shown in this Python example: `>>> data = 'CAPTURETHEFLAG' >>> key = 'A' >>> encrypted = ''.join([chr(ord(x) ^ ord(key)) for x in data]) >>> encrypted '\x02\x00\x11\x15\x14\x13\x04\x15\t\x04\x07\r\x00\x06' >>> decrypted = ''.join([chr(ord(x) ^ ord(key)) for x in encrypted]) >>> decrypted 'CAPTURETHEFLAG'` This can be extended using a multibyte key by iterating in parallel with the data. Exploiting XOR Encryption ------------------------- ### Single Byte XOR Encryption Single Byte XOR Encryption is trivial to bruteforce as there are only 255 key combinations to try. ### Multibyte XOR Encryption Multibyte XOR gets exponentially harder the longer the key, but if the encrypted text is long enough, character frequency analysis is a viable method to find the key. Character Frequency Analysis means that we split the cipher text into groups based on the number of characters in the key. These groups then are bruteforced using the idea that some letters appear more frequently in the english alphabet than others. Back to top --- # Caesar Cipher/ROT 13 - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-is-caesar-cipher-rot-13/#caesar-cipherrot-13) Caesar Cipher/ROT 13 ==================== Caesar Cipher ------------- The Caesar Cipher or Caesar Shift is a cipher which uses the alphabet in order to encode texts. The idea is to encode each letter with another letter in a "fixed" set of shifts. Info `CAESAR` encoded with a shift of 8 is `KIMAIZ` so `ABCDEFGHIJKLMNOPQRSTUVWXYZ` becomes `IJKLMNOPQRSTUVWXYZABCDEFGH` Breaking a ciphertext is incredibly easy as there are only 25 possible "shifts" in the English alphabet. Bruteforce? We can use a tool like [cyberchef](https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,false,13)) to do this quickly but can also print out all the combinations in Python. `secret = "iwtgt xh cd gxvwi pcs lgdcv. iwtgth dcan ujc pcs qdgxcv.".lower() for i in range(0, 26): decrypted_string = "" for j in range(0, len(secret)): letter = ord(secret[j]) if (letter > 122) or (letter < 97) or secret[j] == " ": continue else: letter += 1 if letter > 122: letter = 97 letter = chr(letter) decrypted_string += str(letter) secret = decrypted_string.strip() print(decrypted_string) #output #... #thereisnorightandwrongtheresonlyfunandboring #...` ROT13 ----- ROT13("Rotate 13") is the same thing but a fixed shift of 13, this is a trivial cipher to bruteforce because there are only 25 shifts. Generally, Caesar's Cipher and ROT13 are used in conjunction of other encryption methods to make the challenge more difficult! Back to top --- # Substitution Cipher - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-is-a-substitution-cipher/#substitution-cipher) Substitution Cipher =================== Introduction ------------ A Substitution Cipher is system of encryption where different symbols are substituted by a different alphabet. We can take the letter `A` and replace all occurrences with `F`, `B` with `Y`, and so on. This gives us a key to use with encrypting and decrypting. Tip We often have to keep track of each individual letter in the alphabet and what they're mapped to. Dictionaries make keeping track of keys in python very easy! `key = { "a": "f", "b": "y", "c": "a", "d": "b", "e": "z", "f": "c", "g": "m", "h": "s", "i": "n", "j": "t", "k": "o", "l": "h", "m": "q", "n": "v", "o": "r", "p": "x", "q": "w", "r": "i", "s": "k", "t": "u", "u": "l", "v": "j", "w": "p", "x": "g", "y": "d", "z": "e" } secret = "The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.".lower() secret = filter(str.isalpha, secret) encrypted = "".join([key[i] for i in secret]) print(encrypted) #uszuirlyhzpnussfjnvmfvrxzvqnvbrcarlikznkusfuxzrxhzpnhhnvknkurvarqnvmfhrvmfvbuidnvmurxluusnvmknvnu` Language Entropy ---------------- [xkcd (936)](https://xkcd.com/936/) Often times, we aren't going to be given a key to the cipher. In these cases, we use a strategy from natural language processing known as language entropy. We're looking to "predict" the occurrence of a certain letter based on it's usage in the language.[1](https://ctf101.org/cryptography/what-is-a-substitution-cipher/#fn:1) For example, knowing "vowels are used in most words" gives you a hint that reduces the computation complexity when we attempt to "guess" the usage of certain letters. With this in mind, there are algorithms that use these clues to give you a "best estimate" what the original phrase. Info In 1948, Claude Shannon published the first paper on the entropy of the English language. Modern natural language processing algorithms still cite the original research. Read the paper [here](https://people.math.harvard.edu/~ctm/home/text/others/shannon/entropy/entropy.pdf) . If you're interested in language and information theory, there's a fascinating book on natural language processing in the footnotes!.[2](https://ctf101.org/cryptography/what-is-a-substitution-cipher/#fn:2) Example ------- Substitution cipher without a key Without the key used to create the cipher, we can only try bruteforcing the combinations using the English language. Using the sample below, we can use a tool like [quipqiup.com](https://quipqiup.com/) to bruteforce what the original text is. `Rbo rpktigo vcrb bwucja wj kloj hcjd, km sktpqo, cq rbwr loklgo vcgg cjqcqr kj skhcja wgkja wjd rpycja rk ltr rbcjaq cj cr.` [![Cryptogram Example](https://ctf101.org/cryptography/images/quipqiup.gif)](https://ctf101.org/cryptography/images/quipqiup.gif) Our best guess at what the original phrase is: `The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.` * * * 1. https://cs.stanford.edu/people/eroberts/courses/soco/projects/1999-00/information-theory/entropy\_of\_english\_9.html [↩](https://ctf101.org/cryptography/what-is-a-substitution-cipher/#fnref:1 "Jump back to footnote 1 in the text") 2. https://nltk.org [↩](https://ctf101.org/cryptography/what-is-a-substitution-cipher/#fnref:2 "Jump back to footnote 2 in the text") Back to top --- # Vigenere Cipher - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-is-a-vigenere-cipher/#vigenere-cipher) Vigenere Cipher =============== Vigenere Cipher --------------- A Vigenere Cipher is an extended [Caesar Cipher](https://ctf101.org/cryptography/what-is-caesar-cipher-rot-13/) where a message is encrypted using various Caesar shifted alphabets. A `key` is used to determine how many shifts each letter receives. It adds an additional layer of complexity that relies on the shared key instead of a predetermined shift length. Example We'll use the following table can be used to encode a message: [![Vigenere Square](https://ctf101.org/cryptography/images/vigenere-square.png)](https://ctf101.org/cryptography/images/vigenere-square.png) Encryption ---------- Plaintext: `SUPERSECRET` KEY: `CODE` 1. `CODE` gets padded to the length of `SUPERSECRET` so the key becomes `CODECODECOD`. 2. For each letter in `SUPERSECRET` we use the table to get the Alphabet to use, in this instance row `C` and column `S`. 3. The ciphertext's first letter then becomes `U`. 4. We eventually get `UISITGHGTSW`. Decryption ---------- 1. Go to the row of the key, in this case `C` 2. Find the letter of the cipher text in this row, in this case `U` 3. The column is the first letter of the decrypted ciphertext, so we get `S` 4. After repeating this process we get back to `SUPERSECRET` Cryptanalysis ------------- The key part of breaking a Vigenere Cipher is (not a pun) the key itself. Because it repeats, it's vulnerable to brute forcing the rotation by figuring out what the length of the key is. After, frequency analysis or key elimination is used to reverse the secret. We're not going to cover it here, but check out the footnotes for more![2](https://ctf101.org/cryptography/what-is-a-vigenere-cipher/#fn:2) Online cipher solvers automatically use these steps! Info For more information on how to determine the key length, check out this video on the [Kasiski Examination](https://www.youtube.com/watch?v=asRbswE2hFY) . * * * 1. https://en.wikipedia.org/wiki/Vigen%C3%A8re\_cipher#Cryptanalysis [↩](https://ctf101.org/cryptography/what-is-a-vigenere-cipher/#fnref:1 "Jump back to footnote 1 in the text") 2. https://www.youtube.com/watch?v=LaWp\_Kq0cKs [↩](https://ctf101.org/cryptography/what-is-a-vigenere-cipher/#fnref:2 "Jump back to footnote 2 in the text") Back to top --- # Block Ciphers - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-are-block-ciphers/#block-ciphers) Block Ciphers ============= A **Block Cipher** is an algorithm which is used in conjunction with a cryptosystem in order to package a message into evenly distributed 'blocks' which are encrypted one at a time. Definitions ----------- * Mode of Operation: How a block cipher is applied to an amount of data which exceeds a block's size * Initialization Vector (IV): A sequence of bytes which is used to randomize encryption even if the same plaintext is encrypted * Starting Variable (SV): Similar to the IV, except it is used during the first block to provide a random seed during encryption * Padding: Padding is used to ensure that the block sizes all line up and ensure the last block fits the block cipher * Plaintext: Unencrypted text; Data without obfuscation * Key: A secret used to encrypt plaintext * Ciphertext: Plaintext encrypted with a key Common Block Ciphers -------------------- | Mode | Formulas | Ciphertext | | --- | --- | --- | | ECB | Y~i~ = F(PlainText~i~, Key) | Y~i~ | | CBC | Y~i~ = PlainText~i~ XOR Ciphertext~i-1~ | F(Y, key); Ciphertext~0~ = IV | | PCBC | Y~i~ = PlainText~i~ XOR (Ciphertext~i-1~ XOR PlainText~i-1~) | F(Y, key); Ciphertext~0~ = IV | | CFB | Y~i~ = Ciphertext~i-1~ | Plaintext XOR F(Y, key); Ciphertext~0~ = IV | | OFB | Y~i~ = F(Key, I~i-1~);Y~0~=IV | Plaintext XOR Y~i~ | | CTR | Y~i~ = F(Key, IV + g(i));IV = token(); | Plaintext XOR Y~i~ | Note In this case ~i~ represents an index over the # of blocks in the plaintext. F() and g() represent the function used to convert plaintext into ciphertext. ### Electronic Codebook (ECB) ECB is the most basic block cipher, it simply chunks up plaintext into blocks and independently encrypts those blocks and chains them all into a ciphertext. [![ECB Encryption](https://ctf101.org/cryptography/images/ecb-encryption.png)](https://ctf101.org/cryptography/images/ecb-encryption.png) [![ECB Decryption](https://ctf101.org/cryptography/images/ecb-decryption.png)](https://ctf101.org/cryptography/images/ecb-decryption.png) #### Flaws Because ECB independently encrypts the blocks, patterns in data can still be seen clearly, as shown in the CBC Penguin image below. | Original Image | ECB Image | Other Block Cipher Modes | | --- | --- | --- | | [![Tux](https://ctf101.org/cryptography/images/tux.jpg)](https://ctf101.org/cryptography/images/tux.jpg) | [![ECB Tux](https://ctf101.org/cryptography/images/tux-ecb.jpg)](https://ctf101.org/cryptography/images/tux-ecb.jpg) | [![Other Tux](https://ctf101.org/cryptography/images/tux-secure.jpg)](https://ctf101.org/cryptography/images/tux-secure.jpg) | ### Cipher Block Chaining (CBC) CBC is an improvement upon ECB where an Initialization Vector is used in order to add randomness. The encrypted previous block is used as the IV for each sequential block meaning that the encryption process cannot be parallelized. CBC has been declining in popularity due to a variety of [![CBC Encryption](https://ctf101.org/cryptography/images/cbc-encryption.png)](https://ctf101.org/cryptography/images/cbc-encryption.png) [![CBC Decryption](https://ctf101.org/cryptography/images/cbc-decryption.png)](https://ctf101.org/cryptography/images/cbc-decryption.png) Note Even though the encryption process cannot be parallelized, the decryption process can be parallelized. If the wrong IV is used for decryption it will only affect the first block as the decryption of all other blocks depends on the _ciphertext_ not the plaintext. ### Propogating Cipher Block Chaining (PCBC) PCBC is a less used cipher which modifies CBC so that decryption is also not parallelizable. It also cannot be decrypted from any point as changes made during the decryption and encryption process "propogate" throughout the blocks, meaning that both the plaintext and ciphertext are used when encrypting or decrypting as seen in the images below. [![PCBC Encryption](https://ctf101.org/cryptography/images/pcbc-encryption.png)](https://ctf101.org/cryptography/images/pcbc-encryption.png) [![PCBC Decryption](https://ctf101.org/cryptography/images/pcbc-decryption.png)](https://ctf101.org/cryptography/images/pcbc-decryption.png) ### Counter (CTR) Note Counter is also known as CM, integer counter mode (ICM), and segmented integer counter (SIC) CTR mode makes the block cipher similar to a stream cipher and it functions by adding a counter with each block in combination with a nonce and key to XOR the plaintext to produce the ciphertext. Similarly, the decryption process is the exact same except instead of XORing the plaintext, the ciphertext is XORed. This means that the process is parallelizable for both encryption and decryption _and_ you can begin from anywhere as the counter for any block can be deduced easily. [![CTR Encryption](https://ctf101.org/cryptography/images/ctr-encryption.png)](https://ctf101.org/cryptography/images/ctr-encryption.png) [![CTR Decryption](https://ctf101.org/cryptography/images/ctr-decryption.png)](https://ctf101.org/cryptography/images/ctr-decryption.png) #### Security Considerations If the nonce chosen is non-random, it is important to concatonate the nonce with the counter (high 64 bits to the nonce, low 64 bits to the counter) as adding or XORing the nonce with the counter would break security as an attacker can cause a collisions with the nonce and counter. An attacker with access to providing a plaintext, nonce and counter can then decrypt a block by using the ciphertext as seen in the decryption image. Padding Oracle Attack --------------------- A Padding Oracle Attack sounds complex, but essentially means abusing a block cipher by changing the length of input and being able to determine the plaintext. ### Requirements * An oracle, or program, which encrypts data using CBC * Continual use of the same key ### Execution 1. If we have two blocks of ciphertext, C~1~ and C~2~, we can get the plaintext P~2~ 2. Since we know that CBC decryptionis dependent on the prior ciphertext, if we change the last byte of C~1~ we can see if C~2~ has correct padding 3. If it is correctly padded we know that the last byte of the plaintext 4. If not, we can increase our byte by one and repeat until we have a successful padding 5. We then repeat this for all successive bytes following C~1~ and if the block is 16 bytes we can expect a maximum of 4080 attempts which is trivial Back to top --- # Command Injection - CTF Handbook [Skip to content](https://ctf101.org/web-exploitation/command-injection/what-is-command-injection/#command-injection) Command Injection ================= Command Injection is a vulnerability that allows an attacker to submit system commands to a computer running a website. This happens when the application fails to encode user input that goes into a system shell. It is very common to see this vulnerability when a developer uses the `system()` command or its equivalent in the programming language of the application. `import os domain = user_input() # ctf101.org os.system('ping ' + domain)` The above code when used normally will ping the `ctf101.org` domain. But consider what would happen if the `user_input()` function returned different data? `import os domain = user_input() # ; ls os.system('ping ' + domain)` Because of the additional semicolon, the `os.system()` function is instructed to run two commands. It looks to the program as: `ping ; ls` Note The semicolon terminates a command in bash and allows you to put another command after it. Because the `ping` command is being terminated and the `ls` command is being added on, the `ls` command will be run in addition to the empty ping command! This is the core concept behind command injection. The `ls` command could of course be switched with another command (e.g. wget, curl, bash, etc.) Command injection is a very common means of privelege escalation within web applications and applications that interface with system commands. Many kinds of home routers take user input and directly append it to a system command. For this reason, many of those home router models are vulnerable to command injection. Example Payloads ---------------- * `;ls` * `$(ls)` * `` `ls` `` Related Challenges ------------------ Back to top --- # Stream Ciphers - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-are-stream-ciphers/#stream-ciphers) Stream Ciphers ============== A Stream Cipher is used for symmetric key cryptography, or when the same key is used to encrypt and decrypt data. Stream Ciphers encrypt pseudorandom sequences with bits of plaintext in order to generate ciphertext, usually with XOR. A good way to think about Stream Ciphers is to think of them as generating one-time pads from a given state. Definitions ----------- * A **keystream** is a sequence of pseudorandom digits which extend to the length of the plaintext in order to uniquely encrypt each character based on the corresponding digit in the keystream One Time Pads ------------- A _one time pad_ is an encryption mechanism whereby the entire plaintext is XOR'd with a random sequence of numbers in order to generate a random ciphertext. The advantage of the one time pad is that it offers an immense amount of security BUT in order for it to be useful, the randomly generated key must be distributed on a separate secure channel, meaning that one time pads have little use in modern day cryptographic applications on the internet. Stream ciphers extend upon this idea by using a key, usually 128 bit in length, in order to seed a pseudorandom _keystream_ which is used to encrypt the text. Types of Stream Ciphers ----------------------- ### Synchronous Stream Ciphers A Synchronous Stream Cipher generates a keystream based on internal states _not_ related to the plaintext or ciphertext. This means that the stream is generated pseudorandomly outside of the context of what is being encrypted. A _binary additive stream cipher_ is the term used for a stream cipher which XOR's the bits with the bits of the plaintext. Encryption and decryption require that the synchronus state cipher be in the same state, otherwise the message cannot be decrypted. ### Self-synchronizing Stream Ciphers A Self-synchronizing Stream Cipher, also known as an asynchronous stream cipher or ciphertext autokey (CTAK), is a stream cipher which uses the previous _N_ digits in order to compute the keystream used for the next _N_ characters. Note Seems a lot like block ciphers doesn't it? That's because block cipher feedback mode (CFB) is an example of a self-synchronizing stream ciphers. Stream Cipher Vulnerabilities ----------------------------- ### Key Reuse The key tenet of using stream ciphers securely is to **NEVER** repeat key use because of the communative property of XOR. If C~1~ and C~2~ have been XOR'd with a key K, retrieving that key K is trivial because C~1~ XOR C~2~ = P~1~ XOR P~2~ and having an english language based XOR means that cryptoanalysis tools such as a character frequency analysis will work well due to the low entropy of the english language. ### Bit-flipping Attack Another key tenet of using stream ciphers securely is considering that just because a message has been decrypted, it does not mean the message has not been tampered with. Because decryption is based on state, if an attacker knows the layout of the plaintext, a Man in the Middle (MITM) attack can flip a bit during transit altering the underlying ciphertext. If a ciphertext decrypts to 'Transfer $1000', then a middleman can flip a single bit in order for the ciphertext to decrypt to 'Transfer $9000' because changing a single character in the ciphertext does not affect the state in a synchronus stream cipher. Back to top --- # SQL Injection - CTF Handbook [Skip to content](https://ctf101.org/web-exploitation/sql-injection/what-is-sql-injection/#sql-injection) SQL Injection ============= SQL Injection is a vulnerability where an application takes input from a user and doesn't vaildate that the user's input doesn't contain additional SQL. `` If we look at the $username variable, under normal operation we might expect the username parameter to be a real username (e.g. kchung). But a malicious user might submit different kind of data. For example, consider if the input was `'`? The application would crash because the resulting SQL query is incorrect. `SELECT * FROM users WHERE username='''` Note Notice the extra single quote at the end. With the knowledge that a single quote will cause an error in the application we can expand a little more on SQL Injection. What if our input was `' OR 1=1`? `SELECT * FROM users WHERE username='' OR 1=1` 1 is indeed equal to 1. This equates to true in SQL. If we reinterpret this the SQL statement is really saying `SELECT * FROM users WHERE username='' OR true` This will return every row in the table because each row that exists must be true. We can also inject comments and termination characters like `--` or `/*` or `;`. This allows you to terminate SQL queries after your injected statements. For example `'--` is a common SQL injection payload. `SELECT * FROM users WHERE username=''-- '` This payload sets the username parameter to an empty string to break out of the query and then adds a comment (`--`) that effectively hides the second single quote. Using this technique of adding SQL statements to an existing query we can force databases to return data that it was not meant to return. Preventing SQL Injection ------------------------ The best way to prevent SQL Injection is to use prepared statements. Prepared statements are a way to execute SQL queries that separates the query logic from the data being passed into the query. `prepare('SELECT * FROM users WHERE username = :username'); $stmt->execute(['username' => $username]); ?>` In this example, the `:username` is a placeholder that is replaced with the value of the `$username` variable. The database driver will automatically escape the value of `$username` to prevent SQL Injection. Another way to prevent SQL Injection is to use an ORM (Object Relational Mapping) library. ORM libraries abstract the database layer and allow you to interact with the database using objects instead of raw SQL queries. `first(); ?>` ORM libraries automatically escape user input to prevent SQL Injection. Back to top --- # RSA - CTF Handbook [Skip to content](https://ctf101.org/cryptography/what-is-rsa/#rsa) RSA === RSA, which is an abbreviation of the author's names (Rivest–Shamir–Adleman), is a cryptosystem which allows for asymmetric encryption. Asymmetric cryptosystems are alos commonly referred to as **Public Key Cryptography** where a public key is used to encrypt data and only a secret, private key can be used to decrypt the data. Definitions ----------- * The **Public Key** is made up of \\((n, e)\\) * The **Private Key** is made up of \\((n, d)\\) * The message is represented as \\(m\\) and is converted into a number * The encrypted message or ciphertext is represented by \\(c\\) * \\(p\\) and \\(q\\) are prime numbers which make up \\(n\\) * \\(e\\) is the public exponent * \\(n\\) is the modulus and its length in bits is the bit length (i.e. 1024 bit RSA) * \\(d\\) is the private exponent * The totient \\(\\lambda(n)\\) is used to compute \\(d\\) and is equal to the \\(lcm(p-1, q-1)\\), another definition for \\(\\lambda(n)\\) is that \\\[\\lambda(pq) = lcm(\\lambda(p), \\lambda(q))\\\] What makes RSA viable? ---------------------- If public \\(n\\), public \\(e\\), private \\(d\\) are all very large numbers and a message \\(m\\) holds true for 0 < \\(m\\) < \\(n\\), then we can say: \\\[ (m^e)^d \\equiv m \\;(\\bmod\\; n) \\\] Note The triple equals sign in this case refers to [modular congruence](https://en.wikipedia.org/wiki/Modular_arithmetic) which in this case means that there exists an integer _k_ such that \\\[(m^e)^d = kn + m\\\] RSA is viable because it is incredibly hard to find \\(d\\) even with \\(m\\), \\(n\\), and \\(e\\) because factoring large numbers is an arduous process. Implementation -------------- RSA is implemented in 3 steps: 1. [Key Generation](https://ctf101.org/cryptography/what-is-rsa/#key-generation) 2. [Encryption](https://ctf101.org/cryptography/what-is-rsa/#encryption) 3. [Decryption](https://ctf101.org/cryptography/what-is-rsa/#decryption) ### Key Generation We are going to follow along Wikipedia's small numbers example in order to make this idea a bit easier to understand. Note In this example we are using _Carmichael's_ totient function where \\\[\\lambda(n) = lcm(\\lambda(p), \\lambda(q))\\\] but _Euler's_ totient function is perfectly valid to use with RSA. Euler's totient is \\\[\\phi(n) = (p − 1)(q − 1)\\\] 1. Choose two prime numbers such as: * \\(p = 61\\) and \\(q = 53\\) 2. Find \\(n\\): * \\(n = pq = 3233\\) 3. Calculate \\(\\lambda(n) = lcm(p-1, q-1)\\) * \\(\\lambda(3233) = lcm(60, 52) = 780\\) 4. Choose a public exponent such that \\(1 \\lt e \\lt \\lambda(n)\\) and is coprime (not a factor of) \\(\\lambda(n)\\). The standard is most cases is \\(65537\\), but we will be using: * \\(e = 17\\) 5. Calculate \\(d\\) as the modular multiplicative inverse or in english find \\(d\\) such that: \\(d \* e \\;(\\bmod\\; \\lambda(n)) = 1\\) * \\(d \* 17 (\\bmod\\; 780) = 1\\) * \\(d = 413\\) Now we have a public key of \\((3233, 17)\\) and a private key of \\((3233, 413)\\) ### Encryption With the public key, \\(m\\) can be encrypted trivially The ciphertext is equal to \\(m^e (\\bmod\\; n)\\) or: \\\[c = m^{17} (\\bmod\\; 3233)\\\] ### Decryption With the private key, \\(m\\) can be decrypted trivially as well The plaintext is equal to \\(c^d (\\bmod\\; n)\\) or: \\\[m = c^{413} (\\bmod\\; 3233)\\\] Exploitation ------------ From the [RsaCtfTool README](https://github.com/RsaCtfTool/RsaCtfTool) > Attacks: > > * Weak public key factorization > * Wiener's attack > * Hastad's attack (Small public exponent attack) > * Small \\(q (q \\lt 100,000)\\) > * Common factor between ciphertext and modulus attack > * Fermat's factorisation for close \\(p\\) and \\(q\\) > * Gimmicky Primes method > * Past CTF Primes method > * Self-Initializing Quadratic Sieve (SIQS) using Yafu > * Common factor attacks across multiple keys > * Small fractions method when p/q is close to a small fraction > * Boneh Durfee Method when the private exponent d is too small compared to the modulus (i.e \\(d \\lt n^0.292\\)) > * Elliptic Curve Method > * Pollards \\(p-1\\) for relatively smooth numbers > * Mersenne primes factorization Back to top --- # Cross Site Request Forgery - CTF Handbook [Skip to content](https://ctf101.org/web-exploitation/cross-site-request-forgery/what-is-cross-site-request-forgery/#cross-site-request-forgery-csrf) Cross Site Request Forgery (CSRF) ================================= A Cross Site Request Forgery or CSRF Attack, pronounced _see surf_, is an attack on an authenticated user which uses a state session in order to perform state changing attacks like a purchase, a transfer of funds, or a change of email address. The entire premise of CSRF is based on session hijacking, usually by injecting malicious elements within a webpage through an `` tag or an `