# Table of Contents - [ Intro to Windows & AD Hacking ](#-intro-to-windows-ad-hacking-) - [ Intro to Cryptography ](#-intro-to-cryptography-) - [ Intro to Web Exploitation ](#-intro-to-web-exploitation-) - [ Intro to Purple Teaming: Min-maxing your logging setup ](#-intro-to-purple-teaming-min-maxing-your-logging-setup-) - [ Hello, World ](#-hello-world-) - [ Intro to OSINT (Redacted) ](#-intro-to-osint-redacted-) - [ Active Defense and Cyber Deception: Dirty Blue Team Tricks ](#-active-defense-and-cyber-deception-dirty-blue-team-tricks-) - [ Hiding in Plain Sight: A Survey of EDR Evasion Techniques ](#-hiding-in-plain-sight-a-survey-of-edr-evasion-techniques-) - [ My journey to OSCP ](#-my-journey-to-oscp-) - [ CTF Cheat Sheet ](#-ctf-cheat-sheet-) - [ Intro to Reverse Engineering ](#-intro-to-reverse-engineering-) - [ GitHub-Style Alerts in Jekyll with Liquid ](#-github-style-alerts-in-jekyll-with-liquid-) - [Redirecting...](#redirecting-) - [ Intro to Windows & Active Directory ](#-intro-to-windows-active-directory-) - [ Remotely dumping Windows security questions with Impacket ](#-remotely-dumping-windows-security-questions-with-impacket-) - [ Intro to Binary Exploitation ](#-intro-to-binary-exploitation-) - [ Intro to Windows & AD Hacking - v2 ](#-intro-to-windows-ad-hacking-v2-) - [ Intro to Windows & AD Defense ](#-intro-to-windows-ad-defense-) - [ LLM Hacking ](#-llm-hacking-) - [ How to effectively take inventory ](#-how-to-effectively-take-inventory-) - [ blog · adamkadaban ](#-blog-adamkadaban-) - [ about · adamkadaban ](#-about-adamkadaban-) - [ presentations · adamkadaban ](#-presentations-adamkadaban-) - [ tags · adamkadaban ](#-tags-adamkadaban-) - [Unknown](#unknown) - [ blog · adamkadaban ](#-blog-adamkadaban-) - [ presentations · adamkadaban ](#-presentations-adamkadaban-) - [ tags · adamkadaban ](#-tags-adamkadaban-) --- # Intro to Windows & AD Hacking [home..](https://hackback.zip/) [presentations..](https://hackback.zip/presentations) Intro to Windows & AD Hacking ============================= Adam Hassan / October 2023 (1690 Words, 10 Minutes) [windows](https://hackback.zip/tags#windows) #### Transcript: Windows & AD Hacking Zero to Hero Windows & AD Hacking Zero to Hero\* \*Only if you practice Why do I care about AD? Most enterprise networks run Windows (~88% of the operating system market share is Windows according to a random stat I pulled from a random site in 2020) The standard for managing major enterprise networks is Active Directory About Internal Pentests (aka. Pivot (aka. Assumed Breach)) What? Testing the security posture of the internal networks of the target organization Why? Strong external/perimeter security – Great! Unknown internal network security – Not great. Goals “Let’s assume that the attackers are inside. What now?” Finding misconfigurations (and vulnerabilities) Layered defense 1. The basics File System Is similar to Linux Directories use backslashes () instead though Root of the filesystem is C: Paths are case-insensitive and (kinda) don’t require quotes Registry A large collection of configurations and environment variables Includes keys, subkeys, and values HKEY: Handle to Keys HKCU: Handle Key Current User HKLM: Handle Key Local Machine Value Types: DWORD/QWORD: 32 / 64 bit numbers (double word / quad word) \*\_SZ: a string TryHackMe https://tryhackme.com/module/windows-fundamentals Active Directory TryHackMe https://tryhackme.com/room/winadbasics Local vs Domain Accounts Every account on windows has a local admin and local users If an account is on AD, it will also have a domain account This is often associated with a specific machine account Sometimes passwords are re-used Local System, and NT AUTHORITY\\SYSTEM The same thing. Local Admin SYSTEM Also local admin, but slightly different Domain Admin (Admin of all accounts on the domain) Windows Credentials I LM Old, extremely weak hashing from windows. Mostly unused AAD3B435B51404EEAAD3B435B51404EE NT The equivalent of a password in Windows. Not as weak, but still weak hash. ufsit ⇔ 272AEA395D8D6B05F1BC78E1A7213AEF NTLM LM + NT hash AAD3B435B51404EEAAD3B435B51404EE:272AEA395D8D6B05F1BC78E1A7213AEF For Network Auth: NetNTLMv1: Reversible hash NetNTLMv2: Crackable Hash Windows Credentials II SAM: Security Access Manager Stored in Registry (HKLM\\SAM) HKLM means this stores local passwords Stored in file (C:\\Windows\\System32\\config\\SAM) LSASS: Local Security Subsystem Service Handles and stores logon information in memory This happens at boot and stores hashes and Kerberos tickets Crucial for SSO to work NTDS: NT Directory Services AD database that includes hashes of all domain accounts (also has user info, group info, security descriptors…) On the domain controller C:\\Windows\\NTDS\\ntds.dit LAPS: Local Administrator Password Solution Basically a password manager for accounts on a domain (AD) Can be cloud or not cloud Services Background processes Usually run as SYSTEM Windows Identifiers SID: Security Identifier S-1-5-21-2574976019-2108132042-3243833284 Domain SID S-1-5-21-2574976019-2108132042-3243833284-512 Group SID RID: Relative Identifier Last part of the SID. 500-1000 is built-in users and groups 1000+ is users 1. Tools CrackMapExec (CME) ””” A swiss army knife for pentesting networks Forged by @byt3bl33d3r and @mpgn\_x64 using the powah of dank memes “”” Protocols: vnc, ssh, ftp, winrm, wmi, smb, mssql, rdp, ldap CME NetExec (NXC) ””” The network execution tool Maintained as an open source project by @NeffIsBack, @MJHallenbeck, @\_zblurx For documentation and usage examples, visit: https://www.netexec.wiki/ “”” Protocols: vnc, ssh, ftp, winrm, wmi, smb, mssql, rdp, ldap NXC Impacket Impacket is a collection of Python classes for working with network protocols. This is great for developers, but why do I care? Example Scripts Tons of scripts that let you do basically anything you want https://github.com/fortra/impacket/tree/master/examples pipx install impacket 1. Recon Network Recon 1. Common Services & Abuses (for initial access) Common Windows Services Windows Services: IIS - Port 80/443 TCP RPC - Port 135/139 TCP SMB - Port 445 TCP MSSQL - Port 1433 TCP RDP - Port 3389 TCP AD (DC) Services: DNS - Port 53 TCP/UDP Winrm - Port 5985 TCP LDAP - Port 389/636 TCP Kerberos - Port 88 TCP IIS: 80/443 TCP Is almost never vulnerable by default The vulnerability will often be in the webapp that is being hosted Typically aspx (.NET) files, but can also run PHP IIS RCE?? Sometimes you can write files to the app’s webroot If you can write an executable file to the app, you can get execution on the app IIS is also sometimes vulnerable -> RPC: 135/139 TCP Duct Tape for a lot of Windows backend Is not directly exploitable, but a lot of exploits and windows functionality works using this SMB: 445 TCP SMB: Server Message Block For sharing files over the network Also for IPC, SYSVOL, NETLOGON SYSVOL stores a domain’s public files, which are replicated to each domain controller. NETLOGON contains logon scripts and group policies that can be used by computers deployed within a domain. Null Authentication No username or password Guest Authentication Username, but no password SMB Shares Rid Brute Intro to Relay: SMB Share Relay with Responder sudo Responder -I tun0 More about Relaying Sometimes you can capture a hash by getting people to browse to your SMB share Sometimes you can Coerce authentication (more on this later) https://github.com/p0dalirius/Coercer Technically, Relaying is the act of capture a hash AND forwarding (relaying) it to another host to authenticate nxc smb \--gen-relay-list relayable.txt Command Execution?? MSSQL: 1433 TCP SQL, but make it Bill Gates Mostly the same as other SQL but if you’re an admin, you can get code execution Two types of authentication: Windows Authentication Using a Domain Account SQL Authentication Using an account that only works on the SQL Database (On the local computer) Here, –local-auth means we are using SQL auth, not domain auth RDP: 3389 TCP RDP: Remote Desktop Protocol Lets you remotely access a computer with a GUI DNS: 53 TCP/DCP DNS: Domain Name System This is VERY important to get right for a lot of exploitation nano /etc/hosts resolvectl dns resolvectl domain systemd-resolve --interface \--set-dns \--set-domain Verifying NS with nslookup Winrm: 5985 TCP winrm: Windows Remote Management Enabled by default on users that are local admin This is meant for sysadmins, but is abused by attackers evil-winrm Also lets you upload and download files You can also log in with a hash (-H) LDAP: 389,636,3268,3269 LDAP: Lightweight Directory Access Protocol Allows for authorization and identification of AD Objects “cn=adamhassan,ou=People,dc=ufl,dc=edu” ldapsearch - getting the naming contexts ldapsearch - searching ldapsearch + bash magic How to make it easier Kerberos: 88 TCP Authentication protocol Uses tickets instead of hashes Uses hostnames instead of IPs Done by the krbtgt account on the KDC KDC: Key Distribution Center TGT: Ticket Granting Ticket TGS: Ticket Granting Service ST: Service Ticket Kerberos Attacks Two attacks that can let you steal password hashes and (maybe) crack them ASReproasting An issue for all users with No Pre-Authentication impacket-GetNPUsers.py -request Kerberoasting An issue for all service accounts that have an SPN (Service Principal Name) impacket-GetUserSPNs -request Note: There are different encryption types (etypes) 23 is rc4-hmac (weak, but default) 18 is aes256-cts-hmac-sha1-96 www.iana.org/assignments/kerberos-parameters/kerberos-parameters.xhtml AS-Reproasting (Before and After) Kerberoasting (Before and After) 1. Post-Exploitation Credentials!!! Password Spraying Try the passwords you do have for other accounts (people reuse passwords A LOT) Generate custom wordlist for password cracking: https://github.com/p0dalirius/LDAPWordlistHarvester Password Dumping Mimikatz.exe impacketsecretsdump.py nxc smb \--lsa --sam --ntds --laps LSA and SAM if you're local Admin NTDS if you're Domain Admin or have DCSync Rights (more on this later) LAPS for your own user if you're local admin (sometimes) TryHackMe https://tryhackme.com/room/postexploit 1. Local Privilege Escalation Dangerous Privileges SeInstallAlwaysElevated You can install anything as the administrator This means you can install malicious code and make it run as admin (basically means you can be admin) SeDebugPrivilege Let’s you debug (read/write) process memory This means you can dump LSA secrets (domain creds) SeImpersonate This lets you impersonate another client Usually means easy privesc through potato attacks SeBackupPrivilege, SeRestorePrivilege Lets you (read, write) any files More Privileges https://blog.palantir.com/windows-privilege-abuse-auditing-detection-and-defense-3078a403d74e https://jlajara.gitlab.io/Potatoes\_Windows\_Privesc Potato Attacks & SeImpersonatePrivilege Service accounts often have SeImpersonatePrivilege, as they need to impersonate other users to work correctly. This can be used to impersonate any user (including SYSTEM) This essentially works by coercing another user to authenticate to a named pipe controlled by us, which allows us to steal their security token. Coercing is done in many different ways: https://jlajara.gitlab.io/Potatoes\_Windows\_Privesc Eternal Blue (CVE-2017-0144) Remote Code Execution Vulnerability on Windows if SMB is open Can get you NT\\Authority System Unquoted Service Path C:\\Program.exeC:\\Program Files\\A.exeC:\\Program Files\\A Subfolder\\B.exeC:\\Program Files\\A Subfolder\\B Subfolder\\C.exeC:\\Program Files\\A Subfolder\\B Subfolder\\C Subfolder\\SomeExecutable.exe Automating Findings winPEAS https://github.com/carlospolop/PEASS-ng SeatBelt https://github.com/GhostPack/Seatbelt PowerView / SharpView https://github.com/tevora-threat/SharpView 1. Domain Privilege Escalation BloodHound Uses graph theory to find privilege escalation paths Attackers can use BloodHound to easily identify highly complex attack paths that would otherwise be impossible to quickly identify. Defenders can use BloodHound to identify and eliminate those same attack paths. SharpHound & Bloodhound.py Aggregators that use LDAP to collect data about Domain This data can then be uploaded to BloodHound .\\SharpHound.exe -c All -d python3 bloodhound.py -u validUser -p validPass -d domain.local -c All Dangerous Privileges: GenericAll - Full rights to the object (add users to a group or reset user’s password) GenericWrite - Update object’s attributes (i.e logon script) WriteOwner - Change object owner to attacker controlled user take over the object WriteDACL - Modify object’s ACEs and give attacker full control right over the object AllExtendedRights - Add user to a group or reset password ForceChangePassword - Change user’s password DCSync - Sync to the DC (can be used to grab domain credentials) Vulnerability in the Netlogon Remote Protocol (MS-NRPC) Lets you bruteforce an AES key that allows you to call a function (NetrServerPasswordSet2) to change the password of the domain admin ZeroLogon (CVE-2020-1472) PrintNightmare (CVE-2021-1675, CVE-2021–34527, CVE-2021–34481) Vulnerability that lets you use the print spooler (RPC) to remotely add printer drivers on the system as admin This means you can execute arbitrary code as admin and become admin PetitPotam Vulnerability that allows you to coerce a windows host to authenticate to other machines Uses RPC functions like (MS-EFSRPC) Microsoft’s Encrypting File System Remote Protocol https://github.com/topotam/PetitPotam noPac noPac abuses two CVE’s: (CVE-2021-42278 and CVE-2021-42287) CVE-2021-42278: allows the creation of machine accounts without the $ symbol. CVE-2021-42287: A logic flaw in the way Kerberos will access tickets and tokens when an account does not exist. Abuse Functions How can we abuse this from Linux? nxc smb \-u \-p
-M nopac python3 noPac.py domain.local/username:password -dc-ip $dcip -dc-host $dc01 --impersonate $userToImpersonate –dump https://github.com/Ridter/noPac ADCS Active Directory Certificate Services (ADCS) is a Windows server role that implements public key infrastructure. Certificates (and certificate templates) can be used to access resources Certipy is a great tool for performing ADCS recon: certipy find -u @ -p
-vulnerable -enabled A certificate template is a blueprint of settings, options and permissions that can specified when generating a certificate. Some Options Include: Enrollment Permissions: Specify who can request a certificate with the template. PkiExtendedKeyUsage: Specifies what the certificate can be used for. SCCM SCCM: System Center Configuration Manager Manages task automation, remote control, and OS deployment Recently had a whole suite of vulnerabilities released that allow for: Stealing domain credentials Taking over site servers (the thing that can control everyone’s computer) Coercing Authentication https://www.thehacker.recipes/a-d/movement/sccm-mecm https://github.com/Mayyhem/SharpSCCM Lab - TryHackMe Enterprise https://tryhackme.com/room/enterprise Thanks to Shikata, Scott Brink, Sung Gwan Choi, and Dylan Tran Much of the content from these slides were adapted from their material References © 2025 Adam Hassan --- # Intro to Cryptography [home..](https://hackback.zip/) [presentations..](https://hackback.zip/presentations) Intro to Cryptography ===================== Adam Hassan / April 2021 (3085 Words, 18 Minutes) [crypto](https://hackback.zip/tags#crypto) I made this a while ago, so some details may be wrong #### Transcript: Intro to Cryptography Number Systems Try Yourself: 110001 = ? 000101 = ? Number Systems Try Yourself: 110001 = 49 000101 = 5 Encoding - Ascii and Hex Ascii consists of the (latin) alphabet and key special characters Each of these has a decimal mapping that can be turned into hex 65 = 0x41 = A 66 = 0x42 = B Encoding - Bases Base32 - Consists of (A-Z), (2-7), and = for padding. Length multiples of 8 JFZW4J3UEBRXSYTFOIQHG3ZAMNXW63B7EBCXQ5DSME====== Base64 - Consists of (A-Z), (a-z), (0-9), +, /, and = for padding. Length multiples of 4 SXNuJ3QgY3liZXIgc28gY29vbD8= Base16, Base36, Base58, ,Base62, Base85, Base91, Base92 … also exist These are all easily reversible, just like all encoding Encoding - Big Integers Numeric way of representing bytes (each character is a byte) 0x41 = A (is one byte, or 8 bits) message: HELLO ALL ascii bytes: \[72, 69, 76, 76, 79, 32, 65, 76, 76\] hex bytes: \[0x48, 0x45, 0x4c, 0x4c, 0x4f, 0x20, 0x41, 0x4c, 0x4c\] base-16: 0x48454c4c4f20414c4c base-10: 1333159023296662031436 ⇐ This is the “BIG INTEGER” representation Intro to Ciphers - Shift Cipher Characters in the message are shifted by n positions in the given alphabet If our alphabet is A-Z and our shift is 3 A -> D | B -> E | Z -> C If your alphabet is A-Z,a-z,0-9 and our shift is 3 A -> d | B -> e | Z -> c | z -> 2 Intro to Ciphers - Vigenère Cipher Upgrade from Shift cipher, because we can use text as a key instead of a number Plaintext: ATTACKATDAWN Key: LEMON Keystream: LEMONLEMONLE Ciphertext: LXFOPVEFRNHR Intro to Ciphers - Vigenère Cipher Upgrade from Shift cipher, because we can use text as a key instead of a number Plaintext: ATTACKATDAWN Key: LEMON Keystream: LEMONLEMONLE Ciphertext: LXFOPVEFRNHR Intro to Ciphers - Vigenère Cipher Upgrade from Shift cipher, because we can use text as a key instead of a number Plaintext: ATTACKATDAWN Key: LEMON Keystream: LEMONLEMONLE Ciphertext: LXFOPVEFRNHR Intro to Ciphers - Vigenère Cipher Upgrade from Shift cipher, because we can use text as a key instead of a number Plaintext: ATTACKATDAWN Key: LEMON Keystream: LEMONLEMONLE Ciphertext: LXFOPVEFRNHR What’s the problem with ciphers? Very easy to crack - computers can do millions of instructions per second Only works on text - how do we encrypt an image? Keys can be stolen - would make encoding useless Breaking ciphers - Brute Forcing If you have a 26 character alphabet, you only need to try 25 keys in a shift cipher If key of Vigenere cipher is 6 characters long, a message using a 26 character alphabet only takes 26^6 instructions to break (small for a computer) Breaking Ciphers - Frequency Analysis Naturally, some characters in the alphabet show up more than others. We can look for a distribution of letters that matches the correct English Frequency to figure out which decoded messages are most likely to be correct Solving Ciphers Substitution Ciphers: https://www.quipqiup.com/ Obscure Ciphers: https://dcode.fr/ Cipher Detector: https://www.boxentriq.com/code-breaking/cipher-identifier Types of Encryption - Private key (symmetric) Same key is used for encrypting and decrypting Can be insecure, because ␋key might be stolen Types of Encryption - Public key (asymmetric) Different keys used for encrypting and decrypting Has a public and private key Asymmetric encryption Cryptography conventions: Alice: User A Bob: User B Eve (or Mallory): Eavesdropper (or Malicious) To send to Bob: Alice encrypts data with Bob’s public key Bob decrypts data with his private key Types of Ciphers - Block Ciphers Encrypt chunks (typically 64 bits) of plaintext at a time Simpler but slower and larger More secure (in theory) Types of Ciphers - Stream Ciphers Encrypt each byte of plaintext at a time Faster, smaller and more complex Used most often to trade versatility and security for speed, especially in low-power environments (less RAM, CPU needs) Best used when data length is unknown or continuous Easily reversed Has an Initialization Vector (IV) Should be different every time you start a new stream Simple example of stream cipher symmetric Encryption Algorithms - RSA (Rivest-Shamir-Adleman) One of the original public-key encryption systems.␋Depends on the idea that large prime numbers (often 2^2048 bits) are difficult to factor Encryption Algorithms - DES (Data Encryption System) Encrypts the plaintext with a 64-bit key Key is permuted to get a new 56-bit key This key is used to generate 16 48-bit subkeys Each subkey is a left-shift of the previous subkey Message is broken into 64-bit blocks, each of which is permuted Overall, is a symmetric-key block cipher Encryption Algorithms - 3DES DES was insecure. In 1998, a message could be cracked in 3 days Now, it could be cracked in hours. Is literally just the DES algorithm 3 times. Uses 3 different keys. (Effective key-length of 56\*3 = 168 bits)␋␋2DES is the same as 1DES because of the Meet-in-the-Middle attack. Example Attack Cool Video about Breaking 2DES AES (Advanced Encryption Standard) Upgrade of 3DES. If we could crack 1DES, it won’t be long until 3DES is cracked. Symmetric block cipher 128-bit block size 32-bit multiples for key length (Main reason it was better than DES) Now, you’ve probably seen 2048-bit keys So common that some instruction sets include special instructions for AES operations AES - ECB (Electronic Code Book) Plaintext is divided into blocks of 64 bits For each block, the same key is used for encryption Only suitable for small messages. Why? If a section of plaintext repeats, the encrypted section will also repeat Problem with ECB? AES - CBC (Cipher Block Chaining) Previous block is used to encrypt next block Has an IV (Initialization vector) to encrypt initial block (same length as block size) Crypto Math - XOR ( ⊕ ) XOR is the exclusive or. If one input is true, but not both a b a and b a or b a xor b True True True True False True False False True True False False False False False False True False True True Crypto Math - XOR ( ⊕ ) We can also apply this to numbers This is the easiest using multiple bits (called a bit string) 1 is True and 0 is False & represents an AND | represents an OR ^ represents an XOR 00100 & 11101 = 00100 | | | | --- | --- | | 00100 | 11101 = 11101 | 00100 ^ 11101 = 11001 TRY YOURSELF: 11001 & 00001 = ? | | | | --- | --- | | 11001 | 00001 = ? | 11001 ^ 00001 = ? Crypto Math - XOR ( ⊕ ) We can also apply this to numbers This is the easiest using multiple bits (called a bit string) 1 is True and 0 is False & represents an AND | represents an OR ^ represents an XOR 00100 & 11101 = 00100 | | | | --- | --- | | 00100 | 11101 = 11101 | 00100 ^ 11101 = 11001 TRY YOURSELF: 11001 & 00001 = 00001 | | | | --- | --- | | 11001 | 00001 = 11001 | 11001 ^ 00001 = 11000 Crypto Math - XOR ( ⊕ ) Properties Commutative: A ⊕ B = B ⊕ A Associative: A ⊕ (B ⊕ C) = (A ⊕ B) ⊕ C Identity: A ⊕ 0 = A Self-Inverse: A ⊕ A = 0 Crypto Math - Modular Arithmetic Often described as clock math For (12 hour) clocks, we do MOD 12 Works by getting the remainder in a division. 15 MOD 6 = 3 15 / 6 = 2 remainder 3 21 MOD 4 = 1 21 / 4 = 5 remainder 1 TRY YOURSELF: 36 MOD 13 = ? Crypto Math - Modular Arithmetic Often described as clock math For (12 hour) clocks, we do MOD 12 Works by getting the remainder in a division. 15 MOD 6 = 3 15 / 6 = 2 remainder 3 21 MOD 4 = 1 21 / 4 = 5 remainder 1 TRY YOURSELF: 36 MOD 13 = 10 Throwback Math - GCD and LCM GCD = product of common prime factors LCM = product of highest prime factors 4200 = 2^3 \* 3^1 \* 5^2 \* 7 180 = 2^2 \* 3^2 \* 5^1 GCD(4200,180) = 2^2 \* 3^1 \* 5^1 = 60 LCM(600,180) = 2^3 \* 3^2 \* 5^2 \* 7 = 12600 A\*B = LCM(A,B) \* GCD(A,B) Throwback Math - GCD and LCM (v2.0) Euclidean Algorithm - Basic def gcd(a, b): if a == 0 return b return gcd(b%a, a) # % is the same as MOD (from earlier) gcd(600,180) 600 / 180 = 3 r 60 180 / 60 = 3 r 0 Because the remainder is 0, 60 is the gcd Throwback Math - GCD and LCM (v2.0) Euclidean Algorithm - Extended def egcd(a, b): if a == 0: return (b, 0, 1) g, y, x = egcd(b%a,a) return (g, x - (b//a) \* y, y) Finds values x,y such that gcd(a,b) = ax + by gcd(123,45) 123 / 45 = 2 r 33 45 / 33 = 1 r 12 33 / 12 = 2 r 9 12 / 9 = 1 r 3 9 / 3 = 3 r 0 Because the remainder is 0, 3 is the gcd ecgd(123,45) = 3 = 123x + 45y Rewrite original equations and substitute until you get your answer. 123 / 45 = 2 r 33 ⇔ 123 = 45 \* 2 + 33 Rewrite: 33 = 123 - 45 \* 2 12 = 45 - 33 \* 1 Substitute: 12 = 45 - (123 - 45 _2) \* 1 12 = 45_3 - 123 Continue until you get 3 = 123(-4) + 45(11) egcd(123,45) = 3, -4, 11 We Love Python XOR Cryptography Many cryptosystems use XORs. This can sometimes be broken by bruteforce with if part of the plaintext is known. RSA Math d = private key (private exponent) e = public key (public exponent) m = plaintext message c = ciphertext n = modulus Encryption Very elegant cryptosystem compared to AES, but much slower RSA Math d = 11 e = 5 m = B = 2 c = 4 = D n = 14 Encryption: 25(mod 14) = 32(mod 14) = 4 = D Decryption: 411(mod 14) = 4,194,304(mod 14) = 2 = B RSA Math - TJCTF d = 10924704402434431641693027830372982936967195199035477485425 e = 65537 m = 39614169128650010573550764077907923138941 = “tjctf{RSA\_2\_3asy}” c = 29031324384546867512310480993891916222287719490566042302485 n = 379557705825593928168388035830440307401877224401739990998883 Encryption: me(mod n) = 29031324384546867512310480993891916222287719490566042302485 Which equals (in bytes) b’\\x04\\x9f\\xfd+M\`\\xa4\\x7f>M,gn\\xd5\\x80R \\xf4r\\xd5\\xdd\\x1c\\x0e8\\x15’ Decryption: cd(mod n) = 39614169128650010573550764077907923138941 Which equals b“tjctf{RSA\_2\_3asy}” Chinese Remainder Theorem (CRT) Public Key files come with (n, e) If we can get d, we can get the plaintext If we can get p,q (factor n), we can get d RSA has a lot of weaknesses if not done correctly: phi is dependent on all primes that make up n Breaking RSA - Small Primes Websites to get factors: http://factordb.com/ https://www.alpertron.com.ar/ECM.HTM␋ Breaking RSA - Small Primes RSA can have as many primes as you want Size of primes matter. Not of n. Cheaper & effective to have 2 big primes. Breaking RSA - Weak Primes - Smooth Primes Not all Primes are created equal: Smooth Primes: https://en.wikipedia.org/wiki/Smooth\_number ␋Computationally cheaper to generate, as checking “smoothness” is expensive. Easy to Factor Breaking RSA - Weak Primes - Smooth Primes Based on Pollard’s factorization method, which makes products of primes easy to factor if they are (B)smooth This is the case if p-1 | B! and q - 1 has a factor > B Breaking RSA - Weak Primes - Smooth Primes Not all Primes are created equal: Smooth Primes: https://en.wikipedia.org/wiki/Smooth\_number ␋Computationally cheaper to generate, as checking “smoothness” is expensive. Easy to Factor Breaking RSA - Weak Primes - Similar Primes Based on Fermat’s factorization theorem, which states that any number can be represented as a difference of squares. If primes are too close to each other (or one based on the other), you can crack it. Proof: https://en.wikipedia.org/wiki/Fermat%27s\_factorization\_method Breaking RSA - Small public key Not all Exponents are created equal: Making an exponent cheaper is computationally cheaper, but unsafe. Smallest possible e is 3 Breaking RSA - Small public key Coppersmith attack Used for when exponent is very small (e <= 5) Early variants of RSA proposed exponents as small as 3. We now use 2^16 + 1 = 65537 Proof: https://web.eecs.umich.edu/~cpeikert/lic13/lec04.pdf Breaking RSA - Small private key (or large public key) Not all Exponents are created equal: Making an exponent cheaper is computationally cheaper, but unsafe. Smallest possible e is 3 Breaking RSA - Small private key (or large public key) Dachshund / Wiener attack Used for when private exponent is very small: d < ⅓N^(¼) Proof: https://sagi.io/crypto-classics-wieners-rsa-attack/ Diffie Hellman Key Exchange Public-key protocol to exchange keys Distribute shared key without man-in-the-middle figuring out keys Use shared key for symmetric key cryptography Used in TLS handshake for communication between client and server Diffie Hellman - Secret Key Sharing g is a generator Usually shared at the start of the handshake p is a large prime number a and b are private values, one for each of the devices These are not meant to be shared A and B are public values a & g are combined and b & g are combined. These combined values are typically exchanged between devices. Diffie Hellman Diffie Hellman To determine the secret key, g^(ab), the attacker must determine a or b. Note that g^(ab) = g^a^b Diffie Hellman - Discrete Log Problem http://ramanujan.math.trinity.edu/rdaileda/teach/s18/m3341/lectures/discrete\_log.pdf Diffie Hellman - Discrete Log Problem Diffie Hellman - Discrete Log Problem Because the plot is so random, log\_g(a) is considered hard to compute. We can bruteforce log\_g(a) by computing: g^1, g^2, g^2… until it equals a There is no know algorithm that is more efficient… Diffie Hellman - Discrete Log Problem Because the plot is so random, log\_g(a) is considered hard to compute. We can bruteforce log\_g(a) by computing: g^1, g^2, g^2… until it equals a There is no know algorithm that is more efficient…␋for the general case Diffie Hellman - Bad Generator - Too small If the generator is small enough, we can solve the problem in O(sqrt(n)) time, where n is the order of the generator (g) This is much better than brute force Baby Step Giant Step Algorithm Diffie Hellman - Bad Generator - Nonprime If the generator is non-prime (or smooth), we can solve the problem much faster than baby step does. Pohlig Hellman algorithm An Aside - Sagemath Python Library to solve math things. Has built-in functions for solving discrete\_log, baby step, pollard… https://doc.sagemath.org/ https://sagecell.sagemath.org/␋ An Aside - Sagemath Also has its own interpreter Almost the same as python Can run online: sagecell https://doc.sagemath.org/ https://sagecell.sagemath.org/␋ Elliptic Curve Cryptography (ECC) Public-Key cryptography also based on solving the discrete-log problem, but much cheaper Requires shorter key length for same strength␋␋ Secure Elliptic Curves have a lot of restrictions: Elliptic Curve Cryptography (ECC) Curves follow the equation: y^2 = axy + by = x^3 + cx^2 + dx + e␋Coefficients determine security https://www.desmos.com/calculator/dipjuaeocw Elliptic Curve Cryptography (ECC) https://pycryptodome.readthedocs.io/en/latest/src/public\_key/ecc.html␋ Elliptic Curve Cryptography (ECC) Pick 2 points: A,B Use the points to make a line Find the intersection with the curve Flip the point on the other side. One Cycle: Elliptic Curve Cryptography (ECC) Pick 1 points: P Find the tangent line at the point Find the intersection with the curve Flip the point on the other side. One Cycle: (More Efficient) Elliptic Curve Cryptography (ECC) Repeat until you get to N iterations N is your private key and NP is your public key. Here, the public key is 3P Elliptic Curve Cryptography (ECC) This is even harder, because you don’t know where to start. ␋␋(A + B) + C = A + (B + C)␋␋This is why we can have a smaller key for the same security Elliptic Curve Cryptography (ECC) Same idea as modular arithmetic. Elliptic Curve Cryptography (ECC) For Alice (A) and Bob (B) to share a secret key, they can exchange their public keys (NP and MP respectively) They both agree to start at a point P on the curve, and then use the other’s public key to reach the final destination Alice uses Bob’s MP: MP + MP + … + MP = N x MP = NMP Bob uses Alice’s NP: NP + NP + … + NP = M x NP = NMP Shared Secret Key = NMP Elliptic-Curve Diffie–Hellman ECDH is nearly identical to regular DHKE Alice and Bob publicly agree on: an elliptic curve E, defined by a and b a modulus p a generator point G on E Alice and Bob generate secret values A and B, then publicly share A_G and B_G Alice and Bob can now independently calculate the shared secret A_B_G the x-coordinate of A_B_G can be put into a Key-Derivation Function the y-coordinate is entirely determined by the x-coordinate, so we don’t lose any security by throwing it out Why Elliptic Curves? solving ECDLP is much harder than DLP, so a smaller key provides the same amount of security the difference is small, but significant embedded applications a server that has to perform thousands of handshakes every second Symmetric RSA/DHKE Elliptic Curve 80 1024 160 112 2048 224 128 3072 256 192 7680 384 256 15360 512 NIST recommended key sizes, in bits Elliptic Curve Cryptography (ECC) - Small N We know the elliptic curve equation and the generator base element We also know the public key and the ciphertext If the modulus is too small, we can Elliptic Curve Cryptography (ECC) - Small g We know the elliptic curve equation and the generator base element We also know the public key and the ciphertext If the generator is too small, we can use pohlig hellman (just like we did before with diffie hellman) Elliptic Curve Cryptography (ECC) - CTF Challenge p1 Elliptic Curve Cryptography (ECC) - CTF Challenge p2 Now that we have B, we can use pohlig hellman to calculate the discrete log of all possible prime factors. Then use the CRT to find n, which we can use to get the private key Elliptic Curve Cryptography (ECC) - Small E If the elliptic curve order is too small, we can use a MOV attack MOV: Menezes, Okamoto, Vanstone For small elliptic curves, we can map the points onto a different curve where discrete log calculations are easier A New Age - Quantum Computing All of these algorithms work fine with classical computing techniques, but what about quantum computing? Shor’s Algorithm: Can solve large factorization problems and discrete log in polynomial time, while it generally is exponential time. The solution? Lattice based cryptography Lattice Based Cryptography Has many different implementations. Based on the idea that large lattices (matrices) are hard to solve. One iteration is the shortest vector problem: Shortest Independent Vector Problem (SIVP) NP-hard problem that doesn’t have a polynomial solution for quantum or classical computing. Lattice Based Cryptography Lattice Basis Vectors We want to analyze the lattice and reduce as easily as possible. Thus, we use the LLL algorithm to change the vector the right to the one on the left (short and right angle) Lenstra–Lenstra–Lovász lattice basis reduction algorithm https://en.wikipedia.org/wiki/Lenstra%E2%80%93Lenstra%E2%80%93Lov%C3%A1sz\_lattice\_basis\_reduction\_algorithm Lattice Based Cryptography - Solving Use LLL to find better basis vector Find shortest vector in basis Make a lattice using original vectors and the shortest vector in your reduced basis Use the lattice to solve for all unknown variables in equation Scale solutions by varying the bit-length of variables Sometimes given. Sometimes you have to estimate / bruteforce Moving Forward: https://cryptohack.org/ https://cryptopals.com/ https://pycryptodome.readthedocs.io/en/latest/ https://doc.sagemath.org/html/en/tutorial/ https://github.com/Adamkadaban/CTFs © 2025 Adam Hassan --- # Intro to Web Exploitation [home..](https://hackback.zip/) [presentations..](https://hackback.zip/presentations) Intro to Web Exploitation ========================= Adam Hassan / October 2022 (2757 Words, 16 Minutes) [web](https://hackback.zip/tags#web) s/o to [tjcsc](https://activities.tjhsst.edu/csc/presentations) . much of this content was taken from them. #### Transcript: Intro to Web Security (speedrun pt.2) Schedule Basic Web Concepts: OWASP Top 10 Common Files Javascript & the DOM PHP Cookies Web Tokens Vulnerabilities (This is only a few of them) Insecure Direct Object References (IDOR) SQL Injection (SQLi) Command Injection Cross Site Scripting (XSS) Server Side Template Injection (SSTI) Directory Traversal Local File Inclusion (LFI) Remote File Inclusion (RFI) Tools: Burpsuite Gobuster OWASP Top 10 (you should know these) OWASP Top 10 The Open Web Application Security Project www.owasp.org OWASP is a not-for-profit worldwide charitable organization focused on improving the security of application software. “The OWASP Top Ten provides a powerful awareness document for web application security. The OWASP Top Ten represents a broad consensus about what the most critical web application security flaws are.” https://owasp.org/www-project-top-ten/ Common Files (good for CTFs) Robots.txt Robots.txt is a file in the website directory that shows which files should show up on a search engine and which shouldn’t. Most websites leave it openly accessible. https://www.google.com/robots.txt A lot of CTFs will place a flag here or place a flag in one of these directories or files sitemap.xml Lists every page on a website. Designed to help search engines Provides info about the kind of content available and how it can be reached. Sometimes provides info about when individual pages were last updated and how important certain parts of the site are Also is openly accessible https://www.google.com/sitemap.xml .git/ This one should NOT be there, but CTFs love using it as an example of a bad setup This is the directory for git that provides commit histories the “.” (dot) indicates that it is a hidden folder .htaccess/ used for an apache web server as a way to configure the details of your website without altering the server configuration files should not be writable by the server, but sometimes is (and can be used for remote code execution) Javascript & the DOM (not that kind of dom) DOM Basics Document Object Model Basically a programming interface for web pages Represents a web page as nodes and objects webpage = document DOM = allow document manipulation Can use JS to access & edit the DOM let obj= document.getElementById(‘my\_id’) will get element with id: my\_id obj.innerText = “Hello” Writes obj’s inner text as “Hello” DOM Basics pt.2 DOM isn’t only visual stuff! document.location document.cookies Etc. What are some things DOM access allow? Edit information on screen (such as webpage elements) Retrieve \[even sensitive\] information on screen (such as cookies) So what’s the issue with all this? XSS (more on this later) PHP (nobody likes this language) PHP Basics Server side scripting language Runs PHP code that renders directly into HTML PHP code is not visible on front-end Code in is executed on server and rendered on client $ are variables $\_GET\[‘param’\] Request parameter Cookies (tasty) Cookies - Basics Small blocks of data in the form of strings that store info about the client Able to be accessed and changed client side Extensions like EditThisCookie are good for changing values You can also edit straight from your browser devtools btw don’t share your cookies bc you might get your account stolen Web Tokens JSON Web Token JWT - JSON Web Token JSON: JavaScript Object Notation Standard to securely transfer data in JSON format Authentication, information access Claim based token: stores user information Allows server to verify information without a database query Defined in RFC 7519 (crypto stuff) Each Token has uses a cryptographic algorithm Can be broken if not implemented properly JSON Web Token - Structure https://jwt.io/ JWT vs Cookies? The biggest difference between bearer tokens and cookies is that the browser will automatically send cookies, where bearer tokens need to be added explicitly to the HTTP request. This feature makes cookies a good way to secure websites, where a user logs in and navigates between pages using links. https://stackoverflow.com/questions/37582444/jwt-vs-cookies-for-token-based-authentication Vulnerabilities General ideas Almost every issue here is a result of improper input “sanitization” If a website uses input as-is or does not filter it out properly, we can exploit that IDOR I 🚪 IDOR IDOR: Insecure Direct Object References Happens when a developer exposes a reference to an internal object Without an access control check or other protection, attackers can manipulate these references to access unauthorized data Example: http://myserver2.com/scripts/results.jsp?user=25 If the user can change it to “user=10”, then they might be able to access another user’s account Resources https://portswigger.net/web-security/access-control/idor https://thehackerish.com/idor-tutorial-hands-on-owasp-top-10-training/ SQL Injection (SQLi) SQL Injection - SQL Basics SQL - Structured Query Language Language that lets you communicate with a database: Think of it like a spreadsheet each sheet is it’s own table A bunch of rows with data There are also “relational” databases with columns in one table that refer to that of another table There are tons of types of SQL, each with its own quirks: SQLite PostgreSQL Oracle MySQL NoSQL MongoDB Relational Database Each Box is a table Each line is an attribute SQL Injection - The Actual SQL SQL Injection - Attacking Injecting malicious code into SQL databases Occurs when queries aren’t properly escaped SQL Processes commands after it finishes “preprocessing” What if the someone’s username is admin’–? Since – is a comment, everything after ‘admin’ is ignored Example I found in the wild SQL Injection - Attacking (pt.2) We can change what happens here. Enter in an ‘sql injection string’ We can add inject: ‘ OR 1=1– Notice OR 1=1 is always true Also notice our comment (–) greys out the rest of the query SQL Injection - Advanced Attacks - Union Attack We can extract information by extending results returned from original query Can be used if data type and number of columns are the same for both queries If your attack meets those requirements, you need to find out: How many columns are being returned in the original query Which columns returned from the original query are of the correct data type to be put into the injected query SQL Injection - Advanced Attacks - Union Attack (pt.2) You want to be able to check how many columns are in a table when doing a Union Attack Two methods: ORDER BY NULL Selection Increment the number until you get an out of range error. If The ORDER BY position number 3 is out of range, there are two columns. Add more NULLs until you don’t get an error. If the number of nulls does not match the number of columns, the database returns an error. All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists. SQL Injection - Advanced Attacks - Blind SQLi What if the attacker doesn’t directly get the data back from the server? Attacker can use true/false responses to extract data Example: We can bruteforce a value one character at a time using “LIKE” SQL Injection - Advanced Attacks - Blind SQLi We can also find the length of an attribute: This means the password length is 27 SQL Injection - Advanced Attacks - Timing Attack What if the attacker doesn’t directly get the data back from the server? Attacker can use time-based responses to extract data If a condition is met, the response will have a pause MySQL SLEEP(duration\_secs) BENCHMARK(count, expression) If the following expression is true, there will be a pause before the server responds: SQL Injection - Sanitized Characters Sometimes a developer will try to prevent SQL injection by blocking some inputs We can get around that with some modifications: ‘string’ → hex string space → /\*\*/ – → # OR → || SQL Injection - Automation SQLMap Automatic SQL Injection Tool Can (try to) detect database type Can (try to) automatically do injections Can (try to) automatically dump databases There are tons of tools, but this is the main one Other tools do different things… feel free to try them out Don’t use this on the UF network without a VPN They once blocked my account for it Resources https://portswigger.net/web-security/sql-injection/cheat-sheet https://www.sqlinjection.net/time-based/ https://www.w3schools.com/sql/default.asp https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection https://github.com/sqlmapproject/sqlmap/wiki/Usage Command Injection (pew pew) Command Injection - Basics Sometimes a developer will use input on the website as part of a command without sanitizing it Maybe we can inject code? what if we inject a separate command?: INPUT: site.com; echo “command success” Command Injection - Log Poisoning Often your input will be put into a log somewhere If logs are not properly configured, maybe you can inject code into a logfile and execute it This is how the infamous Log4J worked Command Injection Examples Resources https://portswigger.net/web-security/os-command-injection https://owasp.org/www-community/attacks/Command\_Injection https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection Cross Site Scripting (XSS) XSS An exploit where we execute JS into a user’s webpage If we can access JS - we can probably access the DOM We can control displayed content (phish users?) We can access secret information (steal a user’s session from their cookies?) Some real world examples A Self-Retweeting Tweet Getting a boatload of MySpace friends In our quest to execute malicious code, we often test with alert(1); How does it work? Often categorized three ways: Reflected XSS A payload is attached to a request Stored XSS A payload is stored server-side (database) DOM XSS A payload executed through insecure client-side code Reflected XSS Our exploit payload is embedded within our HTTP query, and is not sanitized https://buggy-website/showtext?=superigamerbeanwafflemcpe